text:
Q: How to access list/dictionary in a function from a different function I'm new to python and I was wondering if there's a way for me to access a list or dictionary with data already stored in it from a different function.
I was wondering if there's a way for me to make the list global so I can access it outside the function, or any other alternative solution.
def upload():
    numlist = [1,2,3,4]

def add():
   for i in numlist:
       print(i)

A: Generally speaking global variables are not brilliant, so it would be better to have a function that creates and returns the list, and then use that in the second function. Even better, you could have a 3rd function that coordinates the 2 separate parts - creation of the list, and processing of the list:
def create_numlist():
    numlist = [1,2,3,4]
    return numlist

def print_numbers(numbers):
    for i in numbers:
        print(i)

def main():
    numbers = create_numlist()
    print_numbers(numbers)

Now the function that loads/creates the list is completely separate from the function that does something with that list.

A: One option is to pass it as parameter, hooking everything together
def add(add_list):
  for value in add_list:
    print(value)

def upload():
  numlist = [1, 2, 3, 4]
  add(numlist)

A: No, you can't access local variables outside of their functions.
An option would be to define a Class that contains:

*

*The variables you're using

*The functions that need access to
these variables.

This would allow you to define local variables that can be accessed by all of the functions in the class without having to return values from one function to the next.
Example :
class Upload:
    def __init__(self):
        self.numlist = [1,2,3,4]

    def add(self):
        for i in self.numlist:
            print(i)

foo = Upload()
foo.add()

Output :
1
2
3
4

A: Yes, as you guessed you can make the list global.
You just need to declare it outside of the function (otherwise it is only local to the function).
numlist = None

def upload():
    global numlist
    numlist = [1,2,3,4]

def add():
    for i in numlist:
        print(i)

upload()
add()

Global variables are somewhat frowned upon. You might research this topic in some depth, for example Why are global variables evil?
Therefore it would be better to try and structure your code so that a global variable is not required. For example:
def upload():
    return [1,2,3,4]

def add():
    numlist = upload()
    for i in numlist:
        print(i)

add()


text:
Q: Centering navigation images html I'm wanting to center my images/hyperlinked pictures: http://i.stack.imgur.com/E051u.png
This is the nav section of my HTML:

body{
  background-color:#163350;
  background-repeat: repeat-x;
  margin: 0;
}

header {
  background-color:#ded7c2;
  color:white;
  text-align:center;
  padding:5px;

}
h1{
  font-family:"Courier New", Courier, monospace;
  font-size:30px;
  color: #ffffff;
  text-align:center;
}

h2{
  font-family:"Courier New", Courier, monospace;
  font-size:30px;
  color:#ffffff;
  text-align:center;
}
p{
  font-family:"Trebuchet MS", Helvetica, sans-serif;
  font-size:15px;
  color:white;
}
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;

}

li {
  float: left;

}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  background-color: #111;
}

.active {
  background-color: #4CAF50;
}

section {
  width:400px;
  float:left;
  padding:10px;
}
footer {
  font-family:"courier new";
  font-size:20px;
  background-color:#ded7c2;
  color:white;
  clear:both;
  text-align:center;
  padding:5px;
  width: 100%;
  height:37px;
}
img section{
  float:left;
  text-align:center;
}
img section two{
  float:center;
  text-align:center;
}
img section three
float:right;
text-align:center;
}

.menu {
  width: 100%;
  text-align:center;
}

google{
  display: block;
  margin-left: auto;
  margin-right: auto
    font-family:"Courier New", Courier, monospace;
  font-size:12px;
  color: #ffffff;
  text-align:center;
  line-height:30px;
  background-color:#68594c;
  height:690px;
  width:100px;
  float:left;
  padding:0px;
}

iframe{
  padding: 200px;
}

h3{
  font-family:"Courier New", Courier, monospace;
  font-size:12px;
  color:#ffffff;
  text-align:center;
}

Any help would be great. Thank you! :)
(it says add more detail but I have nothing to write.....)

A: remove floating... try this code:
https://jsfiddle.net/Lyga3ft2/1/
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  text-align: center;
}

li {
  display:inline-block;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  background-color: #111;
}

A: Make a div element with the ID inside_nav. outside of your ul/li elements. Your code should now look like this.

Now, inside of your css, add the margin: auto property to the div element with the ID inside_nav.
#inside_nav {
    margin: auto;
}

Your images/links should now center align.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can a hover effect be created for a grouping of controls? This seems so simple but I just can't seem to figure it out.
See the image below:

It is a panel with 5 labels on it.
The behavior I want is that if the mouse enters the box (anywhere), the background color changes (for ex: AliceBlue instead of White). The problem is in Windows Forms, the transparency is wierd among other problems. If I set the background of the panel on mouse enter, the labels all still have white backgrounds and so I have white blocks around the labels. Etc.
I am sure others have run into this problem. And I'm sure it's simple. I just can't get it.

A: BackColor is an 'ambient' property.  It doesn't work right because you set the labels' BackColor explicitly.  Right-click the BackColor property of the labels and click Reset so it is no longer shown in bold.  Changing the panel's BackColor will now automatically change the labels' BackColor as well.
This however still doesn't solve your problem.  The panel's MouseLeave event will fire when you move the mouse across one of the labels.  There is no clean solution for this in Winforms, subscribing all the labels and the panel's MouseEnter/Leave events doesn't eliminate corner cases.  Like when the user very quickly moves the mouse from a label that's close to the edge of the panel.  You'll get the MouseLeave for the label but not the MouseEnter + Leave for the panel.
The only good fix for this is a timer or the Application.Idle event.  Like this:
public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        Application.Idle += Application_Idle;
    }
    protected override void OnFormClosed(FormClosedEventArgs e) {
        Application.Idle -= Application_Idle;
        base.OnFormClosed(e);
    }
    void Application_Idle(object sender, EventArgs e) {
        var pos = panel1.PointToClient(Cursor.Position);
        if (panel1.DisplayRectangle.Contains(pos)) panel1.BackColor = Color.Red;
        else panel1.BackColor = this.BackColor;
    }
}


text:
Q: Парсинг контактов предприятия с помощью регулярного выражения в PHP Добрый день.
Есть такой SHTML-код:

Контактные данные

                            адрес:
                            Mielczarskiego 4/9

                                95-035 Ozorków                           (Озоркув)

                            воеводство:
                            łódzkie

                            сайт:

                                                            www.pomocnadrogach.pl

                            email:
                            pomoc@pomocnadrogach.pl

                            тел:
                            +48 606808101

                                контакт:
                                Томаш Корчиньски

Мне нужно из этого кода извлечь данные: телефон Воеводтства, сайт, емейл, контакт.
Вот что я начал делать:
(адрес):(?(1)<[\w\W]+?([\w\W]+?)<\/td>|)[\w\W]+?(воеводство):(?(3)[\w\W]+?([\w\W]+?)<\/td>[\w\W]+?\/\/([\w\W]+?)")[\w\W]+?(email):(?(6)[\w\W]+?:([\w\W]+?)\?)

Для примера описал парсинг первых трех данных.
Найденные данные:
1.  [178-183]   `адрес`
2.  [218-328]   `Mielczarskiego 4/9

                            95-035 Ozorków                           (Озоркув)                        `
3.  [431-441]   `воеводство`
4.  [476-483]   `łódzkie`
5.  [719-740]   `www.pomocnadrogach.pl`
6.  [1054-1059] `email`
7.  [1110-1133] `pomoc@pomocnadrogach.pl`

Проблема такая: иногда бывает что порядок меняется или какие-то пункты есть, а в другом примере их нет. Можно как то условия задать не на "матч", а на имя. Или может есть какие-то другие варианты, чтобы удовлетворять данные условия.

A: Вот пример на основе DOMDocument:
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$xpath = new DOMXPath($dom);
$links = $xpath->query('//tr');
$arr = array();
foreach($links as $link) {
   $arr[] = array($link->getElementsByTagName("td")[0]->nodeValue, $link->getElementsByTagName("td")[1]->nodeValue);
}

print_r($arr);

A: вобщем сделал я без X-path а именно
если че - контент выбираем только раз)))
$reg_addr = '/(?<=адрес):(<[\w\W]+?([\w\W]+?)<\/td>|)/mi';
        preg_match_all( $reg_addr ,$content, $arr_addr);
        $reg_voevod = '/(?<=воеводство:)[\w\W]+?<\/tr>/mi';
        preg_match_all( $reg_voevod ,$content, $arr_voevod);
        $reg_site = '/(сайт):[\w\W]+?\/\/([\w\W]+?)"/mi';
        preg_match_all( $reg_site ,$content, $arr_site);
        $reg_email = '/(?<=email):[\w\W]+?mailto:([\w\W]+?)\?/mi';
        preg_match_all( $reg_email ,$content, $arr_email);
        $reg_phone = '/(?<=тел):[\w\W]+?([\w\W]+?)<\/td>/mi';
        preg_match_all( $reg_phone ,$content, $arr_phone);
        $reg_fax = '/(?<=факс):[\w\W]+?([\w\W]+?)<\/td>/mi';
        preg_match_all( $reg_fax ,$content, $arr_fax);
        $reg_time_work = '/(?<=время работы):[\w\W]+?<p([\w\W]+?)<\/p/mi';
        preg_match_all( $reg_time_work ,$content, $arr_time_work);
        $reg_facebook = '/(?<=время работы):[\w\W]+?[\w\W]+?(facebook.com[\w\W]+?)"[\w\W]+?<\/td>/mi';
        preg_match_all( $reg_facebook ,$content, $arr_facebook);
        $reg_contact = '/(?<=контакт):[\w\W]+?([\w\W]+?)<\/td>/mi';
        preg_match_all( $reg_contact ,$content, $arr_contact);

        $company_info = array();
        (!$arr_addr[1][0])?$company_info['addres'] = '' :     $company_info['addres'] = clear($arr_addr[1][0]);
        (!$arr_voevod[0][0])? $company_info['voevod'] = '' : $company_info['voevod'] = clear($arr_voevod[0][0]);
        (!$arr_site[2][0])? $company_info['site'] = '' : $company_info['site'] = $arr_site[2][0];
        (!$arr_email[1][0])? $company_info['email'] = '' : $company_info['email'] = $arr_email[1][0];
        (!$arr_phone[1][0])? $company_info['phone'] = '' : $company_info['phone'] = clear($arr_phone[1][0]);
        (!$arr_fax[1][0])? $company_info['fax'] = '' : $company_info['fax'] = $arr_fax[1][0];
        (!$arr_time_work[1][0])? $company_info['time_work'] = '' : $company_info['time_work'] = clear($arr_time_work[1][0]);
        (!$arr_facebook[1][0])? $company_info['facebook'] = '' : $company_info['facebook'] = $arr_facebook[1][0];
        $company_info['urlArray'] = $url;
        $company_info['source'] = 'www.primer-site.com';

        array_push($global_arr, $company_info);
        print "\n done  inner".$inner."and outer - >".$outer;

далее настакал массивов в json сохранил и можно делать что хош))


text:
Q: unable to upload file on server "Error 500 Inter server Error" I am stuck in upload file it works fine on local but when I deploy on server it show

500 internal server Error..

Here its my code please review..where m wrong?
Here's my controller code

[HttpPost]
public ActionResult GlovalValues(Global_values REC, HttpPostedFileBase uploadFile)
{
    string strPath = "~/Laptop_File/";
    string Server_path = "";
    string GetFileName = "";

    int id = REC.ID;
    string Desc = REC.GS_Desc;
    string Name = REC.GS_Name;
    string values = REC.GS_Values;
    int Effrows = 0;

    if (uploadFile != null && uploadFile.ContentLength > 0)
    {
        try
        {
            if (!Directory.Exists(Server.MapPath(strPath)))
            {
                DirectoryInfo di = Directory.CreateDirectory(Server.MapPath(strPath));
            }
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];
                var filePath = Request.FilePath;

                var FileExtension = uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf('.') + 1).ToLower();

                string ActualFileName = uploadFile.FileName;

                GetFileName = Path.GetFileNameWithoutExtension(uploadFile.FileName);

                if (file != null && file.ContentLength > 0)
                {
                    string UploadFileName = Path.GetFileName(GetFileName + "." + FileExtension);
                    Server_path = Path.Combine(Server.MapPath("~/Laptop_File/"), UploadFileName);

                    if (FileExtension == "xlsx" || FileExtension == "xltx" || FileExtension == "xls" ||      FileExtension == "xlt ")
                    {
                        file.SaveAs(Server_path);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }
    return RedirectToAction("Global_Values_List", "GS_Global_Values");
}

here's my view

@using (Html.BeginForm("GlovalValues", "GS_Global_Values", FormMethod.Post, new { @id = "id", @enctype = "multipart/form-data" }))
{

         Uplaod File :

            <input type="file" name="uploadFile"  id="fileupload" />

             <input type="submit" value="Create" class="btn btn-default" />

}

Please help I cant figure out whats wrong

A: In my case it reason from permission.When I ran my project locally on IIS Express everything was fine,and I could upload files correctly, but when I deployed it on IIS 8,it had returned me "Error 500 Internal server Error" for file uploading.
I have changed the permissions for "IIS_IUSRS" on "upload" folder in IIS 8 as follows:

now it is working fine.

A: Check on server that your application pool has rights of network services or other user with higher authority to Modify the directory & file writing.
If your code is working in local this seems the only issue at moments.


text:
Q: Android graphical layout has a default actionbar shown in some cases In the xml graphical layout of my android application there is a actionbar shown in one of my android studio projects and not in others. Out of curiosity i would like to know the reason behind this. I don't see any changes in the themes of either of the layouts and activities.
Something like this is shown :

PS: the part above the dotted line is the actionbar. I want it removed somehow. It's not there in any of my other Android Studio projects.

A: Try adding this in your styles.xml
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

and add AppTheme.NoAction to your activity in Manifest


text:
Q: Facebook redirect uri not maintaining my passed values My ultimate goal is to store Facebook user tokens in my DB for use later.  I have no problem with the theory - this helped: http://facebook.stackoverflow.com/questions/4608713/can-i-store-facebook-access-token-and-use-it-later
I'm using the Facebook PHP SDK (v.3.1.1).
I am having issues passing data to the redirect_uri and having that data successfully come back to that url from Facebook.
Code:
$args['redirect_uri'] = 'http://tld.com/add.php?id='. $uid .'&filename='. $pfilename .'&gid='. $gid;
$loginUrl = $facebook->getLoginUrl($args);
header("Location: $loginUrl");

After Facebook does its work and sends back to my domain I successfully have the user token, but my passed data is lost.
After research I have found this: on facebook connect login uri, can I add an extra get param on url, and have that passed to my script once user logs in? -- problem is the answer with two votes is what I am doing above and not working.  And as for the second answer, I couldn't get it working by changing my ? to %3F.
My question is how can this be done and whats the correct working method to accomplish passing data to the Facebook login url using the redirect_uri and retrieving that data.

A: Solved.  I had errors in my passing my data.  The theory and everything I described above works fine - you can pass data to the redirect_uri just fine.


text:
Q: how to resolve Mern Stack app connection Failed error Failed to load resource: net::ERR_CONNECTION_REFUSED getting this error. an the another one is Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:84)
plaese tell me more about this how do i fix this bug.
Client side app.js file
import { useState } from 'react';
import './App.css';
import Axios from 'axios';

function App() {

  const [foodname,setFoodName]  = useState("");
  const [days,setDays] = useState(0);

  const addToList = () =>{
    Axios.post("http://localhost:3001/insert", {
      foodname: foodname,
      days: days
    });
  };

  return (

CRUD APP WITH MERN

        Enter Food Name:
        <input
          type="text"
          onChange={(event) => {
            setFoodName(event.target.value);
          }}/>
        Days Since I Ate:
        <input
          type="number"
          onChange={(event) => {
          setDays(event.target.value);
          }}/>

        <button onClick={addToList}>Add to List</button>

  );
}

export default App;

Server side index.js file
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();

const FoodModel = require("./models/Food");

app.use(express.json());
app.use(cors());

mongoose.connect("mongodb+srv://crudop:crudop@crud.jmbry.mongodb.net/food?retryWrites=true&w=majority",{
    useNewUrlParser: true,
    useUnifiedTopology: true
});

app.post('/insert',async (req,res)=>{

    const FoodName = req.body.foodname;
    const days = req.body.days;

    const food = new FoodModel({foodname: FoodName, daysSinceIAte:days});

    try{
        await food.save();
        res.send("inserted");
    }
    catch(err){
        console.log(err);
    }
});

app.listen(3001, ()=>{
     console.log("server is running on port 3001...");
})

A: wait for MongoDB connection
after that start listening onto the port
    mongoose
   .connect(DB_URL, {
       useUnifiedTopology: true,
       useNewUrlParser: true,
    })
   .then((result) => {
         app.listen(3001, () => {
    console.log("Server started on port 3001");
    });
  })
  .catch((err) => console.log(err));


text:
Q: I wanted to do a Binary search but the result is faulty I wanted to do binary search on a list but the result shows 'false' even if I check a number from the list.
def clist(a):

    l = [2,6,5,9,7,1,4,8,3]
    newl = sorted(l)
    check = int(1+len(newl)/2)

    if newl[check] == a:
        return True

    if check > a:
        for x in newl[:check]:
            if x == a:
                return True
            return False

    if check < a:
        for x in newl[check::]:
            if x == a:
                return True
            return False

print(clist(7))

A: You could write your script in such a way that:

*

*take the element at the middle of the list

*return it if that's what you need

*if your needle is gt than the middle, then call bsearch on the remaining right side of the list

*othwewise call bsearch with the left side

def bsearch(needle, haystack):
    l = len(haystack)
    half = int(l / 2)
    element = haystack[half];

    if element == needle:
        return element

    if needle <= element:
        return bsearch(needle, haystack[0:half])

    if needle > element:
        return bsearch(needle, haystack[half:l])

print(bsearch(7, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))

in binary search:

*

*list must be ordered

*as stated by @tripleee, you have to recursively split the list in halves

A: Please go through this:
def clist(a):

    l = [2,6,5,9,7,1,4,8,3]
    newl = sorted(l)
    check = int(1+len(newl)/2)

    if newl[check] == a:
        return True

    if newl[check] > a:              #fixed the bug here
        for x in newl[:check]:
            if x == a:
                return True

    if newl[check] < a:             #fixed the bug here
        for x in newl[check:]:
            if x == a:
                return True

    return False        #Return false should be universal. When the entire search fails it should be called.

print(clist(7))

A: Your function is not binary search, you are checking element by element of a sorted list after checking the middle element.
def binary_search(arr, i):
    n = len(arr)
    arr = sorted(arr)
    left = 0
    right = n - 1

    # Define the condition when the loop should be broken
    while (left <= right):
        mid = left + (right-left) // 2
        if arr[mid] == i:
            return True
        elif arr[mid] < i:
            left = mid + 1
        else:
            right = mid - 1
    return False

l = [2,6,5,9,7,1,4,8,3]
i = 7
binary_search(l, i)


text:
Q: Forcing children type in react-typescript: Type 'Element' is not assignable to type 'FunctionComponent I am trying to type a react component such that it only accepts certain types of children.  The component is called ItemGroup, and it should only accept components (or arrays of components) called Submenu or MenuItem.  For now, let's say it can only accept a single Submenu as a child:
I define the Submenu component and props:
interface SubmenuProps {
  popupId: string;
}

export const Submenu: React.FC<SubmenuProps> = ({ popupId }: SubmenuProps) => {
  return
some stuff
;
};

And now I define the ItemGroup, and type its children to allow only React.ElementTypes of SubmenuProps, or an array thereof:
interface ItemGroupProps {
  title: string;
  children: React.ElementType<SubmenuProps> | React.ElementType<SubmenuProps>[];
}

export const ItemGroup: React.FC<ItemGroupProps> = (props: ItemGroupProps) => {
  const { title, children } = props;
  return (
    <>

{title}

      {children}
    </>
  );
};

I try to actually use it as such:
export default function App() {
  return (
    <ItemGroup title="something">
      <Submenu popupId="123" />
    </ItemGroup>
  );
}

On the use of <Submenu />, I get an error:
Type 'Element' is not assignable to type 'FunctionComponent<SubmenuProps> | ComponentClass<SubmenuProps, any> | ElementType<SubmenuProps>[] | ... 20 more ... | (ElementType<...>[] & ReactPortal)'.
  Type 'Element' is not assignable to type 'ElementType<SubmenuProps>[] & ReactPortal'.
    Type 'Element' is missing the following properties from type 'ElementType<SubmenuProps>[]': length, pop, push, concat, and 25 more.ts(2322)
App.tsx(14, 3): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & ItemGroupProps & { children?: ReactNode; }'

Codesandbox demonstrating the problem
I have done this type of thing before, i.e. forcing certain types of children, by using a children: React.Elementype<ChildProps> in the props interface for the parent.  Why am I getting an error here.  How can I type the ItemGroup's children prop to only allow Submenus and/or MenuItems?


text:
Q: How To use lag and Rangebetween in Pyspark windows function My data looks like below.
+------------------+--------------------+----------------+
|               out|           timestamp|        Sequence|
+------------------+--------------------+----------------+
|0.5202757120132446|2019-11-07 00:00:...|               1|
|              null|2019-11-07 00:00:...|               2|
|              null|2019-11-07 00:00:...|               3|
|              null|2019-11-07 00:00:...|               4|
|0.5220348834991455|2019-11-07 00:00:...|               5|
| 0.724998414516449|2019-11-07 00:00:...|               6|
|              null|2019-11-07 00:00:...|               7|
|              null|2019-11-07 00:00:...|               8|
|0.7322611212730408|2019-11-07 00:00:...|               9|
|              null|2019-11-07 00:00:...|              10|
|              null|2019-11-07 00:00:...|              11|

Now i want replace the null values with previous sequence value . I'm using windows function to acheive this but i'm getting following error
'Window Frame RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW must match the required frame ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING;'

My code:
window1 =Window.partitionBy('timestamp').orderBy('Sequence').rangeBetween(Window.unboundedPreceding,0)
df = df.withColumn('out',F.when(F.col('out').isNull(),F.lag('out').over(window1)).otherwise(F.col('out')))

A: import sys
import pyspark.sql.functions as f
df.withColumn("newout", f.last('out', True).over(Window.partitionBy('timestamp').orderBy('sequence').rowsBetween(-sys.maxsize, 0))).show()

+------------------+--------------------+--------+------------------+
|               out|           timestamp|sequence|            newout|
+------------------+--------------------+--------+------------------+
|0.5202757120132446|2019-11-07 00:00:...|       1|0.5202757120132446|
|              null|2019-11-07 00:00:...|       2|0.5202757120132446|
|              null|2019-11-07 00:00:...|       3|0.5202757120132446|
|              null|2019-11-07 00:00:...|       4|0.5202757120132446|
|0.5220348834991455|2019-11-07 00:00:...|       5|0.5220348834991455|
| 0.724998414516449|2019-11-07 00:00:...|       6| 0.724998414516449|
|              null|2019-11-07 00:00:...|       7| 0.724998414516449|
|              null|2019-11-07 00:00:...|       8| 0.724998414516449|
|0.7322611212730408|2019-11-07 00:00:...|       9|0.7322611212730408|
|              null|2019-11-07 00:00:...|      10|0.7322611212730408|
|              null|2019-11-07 00:00:...|      11|0.7322611212730408|
+------------------+--------------------+--------+------------------+


text:
Q: Filter bonded device in bluetooth android I am building a Health application in which blood pressure monitor is used. I already paired so many BLE devices. I want to filter only particular device like Blood Pressure Monitor. I also did this in scan filter through like this
BloodPressurePairViewModel.kt
class BloodPressurePairViewModel : ViewModel() {

    companion object {
        private const val SCAN_PERIOD: Long = 10000 // For 1 minute scan
        private const val UUID_MASK_STRING = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"
        private const val BLUETOOTH_PRESSURE_128_STRING = "00001810-0000-1000-8000-00805f9b34fb"
        private const val BLUETOOTH_PRESSURE_MEASUREMENT_128_STRING = "00002A35-0000-1000-8000-00805f9b34fb"
    }

    var bluetoothLeScanner: BluetoothLeScanner? = null
    var isBluetoothEnabled by mutableStateOf(false)
        private set
    val mLeDevices: MutableStateFlow<List<ScanResult>> = MutableStateFlow(emptyList())
    var scanning: MutableStateFlow<Boolean> = MutableStateFlow(true)
        private set
    private val leScanCallback: ScanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            super.onScanResult(callbackType, result)
            if (!mLeDevices.value.equals(result)) {
                if (result.device?.name != null) {
                    if (checkDuplicateScanResult(mLeDevices.value, result)) {
                        mLeDevices.value += result
                    }
                }
            }
        }

        override fun onBatchScanResults(results: MutableList<ScanResult>?) {
            super.onBatchScanResults(results)
            logE("onBatchScanResults >> $results")
        }

        override fun onScanFailed(errorCode: Int) {
            super.onScanFailed(errorCode)
            logE("onScanFailed >> $errorCode")
        }
    }

    fun setBluetoothEnable(newValue: Boolean) {
        isBluetoothEnabled = newValue
    }

    fun startScan() {
        viewModelScope.launch {
            delay(SCAN_PERIOD)
            scanning.value = false
            bluetoothLeScanner?.startScan(scanFilters(), ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER).build(), leScanCallback)
        }
    }

    private fun scanFilters(): MutableList<ScanFilter> {
        val scanFilterList = mutableListOf<ScanFilter>()
        val parcelUuidMask = ParcelUuid.fromString(UUID_MASK_STRING)
        val listItem = listOf(BLUETOOTH_PRESSURE_128_STRING, BLUETOOTH_PRESSURE_MEASUREMENT_128_STRING)
        listItem.forEach {
            val scanFilter = ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(it), parcelUuidMask).build()
            scanFilterList.add(scanFilter)
        }
        return scanFilterList
    }

    fun stopScan() {
        bluetoothLeScanner?.stopScan(leScanCallback)
    }

    private fun checkDuplicateScanResult(value: List<ScanResult>, result: ScanResult): Boolean {
        val checkDevice = value.count { it.device == result.device }
        return checkDevice < 1
    }
}

I used scanFilters() to find particular type of device like BPM. Now I want to filter according to my 128 bit string in my bonded device. I tried this piece of code from this stack overflow but it didn't work.  I tried this piece of code
val getUuidsMethod: Method = BluetoothAdapter::class.java.getDeclaredMethod("getUuids", null)
val uuids = getUuidsMethod.invoke(bluetoothAdapter, null)

but it giving me error
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:526)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
                                                                                Caused by: java.lang.reflect.InvocationTargetException
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
                                                                                Caused by: java.lang.NoSuchMethodException: parameter type is null
                                                                                at java.lang.Class.getMethod(Class.java:2063)
                                                                                at java.lang.Class.getDeclaredMethod(Class.java:2050)
                                                                                at com.abc.app.bloodpressure.composables.PairScreenState.getPairedDevice(BloodPressurePairScreen.kt:176)
                                                                                at com.abc.app.bloodpressure.composables.PairScreenState.<init>(BloodPressurePairScreen.kt:156)
                                                                                at com.abc.app.bloodpressure.composables.BloodPressurePairScreenKt.rememberPairScreenState(BloodPressurePairScreen.kt:118)
                                                                                at com.abc.app.bloodpressure.composables.BloodPressurePairScreenKt.BluetoothPairContentStateful(BloodPressurePairScreen.kt:66)
                                                                                at com.abc.app.bloodpressure.composables.BloodPressurePairScreenKt.BluetoothPairContent(BloodPressurePairScreen.kt:52)
                                                                                at com.abc.app.bloodpressure.composables.BluetoothRequestScreenKt$BluetoothRequestContent$1.invoke(BluetoothRequestScreen.kt:39)
                                                                                at com.abc.app.bloodpressure.composables.BluetoothRequestScreenKt$BluetoothRequestContent$1.invoke(BluetoothRequestScreen.kt:35)
                                                                                at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)

Can you guys help me on this?


text:
Q: concatenate an html tag inside an asp.net control I need to concatenate an HTML tag like
 and   to the Text property of an ASP.Net TextBox.
I tried this:
txtMessage.Text + "
" + strgetlist;

But it is displaying the following:

TaskName
Project1,project2..

How cam I add a break/space between these two strings?

A: Here I am assuming that the output is to be shown in a TextBox.  First make the TextBox TEXTMODE as multiline.  Then on the TextBox where you have to show the output (say txtOutput), you write:
txtOutput = TextBox1.Text + "\n" + strgetlist;

A: Try using txtMessage.Text + "
" + strgetlist

A: You can use Environment.NewLine as long as you have set TextMode="MultiLine" for the TextBox. Just a plain space (i.e. " ") should work to get a space in the 'list'.
Is that what you meant?

A: you could try using string.Format

string.Format("{0}
{1}", txtMessage.Text, strgetlist);


text:
Q: MRJOB open JSON file - Python I am trying to load a json file as part of the mapper function but it returns "No such file in directory" although the file is existent.
I am already opening a file and parsing through its lines. But want to compare some of its values to a second JSON file.
from mrjob.job import MRJob
import json
import nltk
import re

WORD_RE = re.compile(r"\b[\w']+\b")
sentimentfile = open('sentiment_word_list_stemmed.json')

def mapper(self, _, line):
    stemmer = nltk.PorterStemmer()
    stems = json.loads(sentimentfile)

    line = line.strip()
    # each line is a json line
    data = json.loads(line)
    form = data.get('type', None)

    if form == 'review':
      bs_id = data.get('business_id', None)
      text = data['text']
      stars = data['stars']

      words = WORD_RE.findall(text)
      for word in words:
        w = stemmer.stem(word)
        senti = stems.get[w]

        if senti:
          yield (bs_id, (senti, 1))

A: You should not be opening a file in the mapper function at all.  You only need to pass the file in as STDIN or as the first argument for the mapper to pick it up. Do it like this:
python mrjob_program.py sentiment_word_list_stemmed.json > output

OR
python mrjob_program.py < sentiment_word_list_stemmed.json > output

Either one will work. It says that there is no such file or directory because these mappers are not able to see the file that you are specifying.  The mappers are designed to run on remote machines.  Even if you wanted to read from a file in the mapper you would need to copy the file that you are passing to all machines in the cluster which doesn't really make sense for this example.  You can actually specify a DEFAULT_INPUT_PROTOCOL so that the mapper know which type of input you are using as well.
Here is a talk on the subject that will help:
http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2011-mrjob-distributed-computing-for-everyone-4898987/

A: You are using the json.loads() function, while passing in an open file. Use json.load() instead (note, no s).
stems = json.load(sentimentfile)

You do need to re-open the file every time you call your mapper() function, better just store the filename globally:
sentimentfile = 'sentiment_word_list_stemmed.json'

def mapper(self, _, line):
    stemmer = nltk.PorterStemmer()
    stems = json.load(open(sentimentfile))

Last but not least, you should use a absolute path to the filename, and not rely on the current working directory being correct.


text:
Q: How do I add an image as my play in my game? I am not sure how to add an image to my player instead of
Here is what I got right now, it is a game where you
"teleport" to either of the sides to avoid obstacles.
import pygame

# Display
pygame.init()
win = pygame.display.set_mode((500, 1050))
pygame.display.set_caption("Fall")

player = pygame.Rect(230, 125, 40, 40)
vel = 500
gravity = 8
run = True
FPS = 30
fpsClock = pygame.time.Clock()
while run:
    fpsClock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

# Movement
    keys = pygame.key.get_pressed()
    player.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel
    if player.left < 0:
        player.left = 0
    if player.right > win.get_width():
        player.right = win.get_width()

    player.y += gravity
    if player.bottom > win.get_height():
        player.bottom = win.get_height()

    win.fill((0, 0, 0))
    pygame.draw.rect(win, (0, 130, 255), player)
    pygame.display.update()

pygame.quit()

Here is the player I was trying to put in the game,

I have tried to load the image into pygame and use the image as the "player" variable and run it, I thought it would run but it didnt work so I put it back to normal for now.


text:
Q: forma otimizada para recuperar último ID mysql Qual forma mais otimizada de recuperar o último id da tabela?
testei esses dois métodos e o orde by demorou muito. Existe algum além desses?
Obs: nãp será uma consulta após insert. Será uma consulta separada.
select max(campo_id) from tabela

select campo_id FROM tabela ORDER BY campo_id DESC LIMIT 1

A: Nenhuma dessas alternativas serve para recuperar o último ID.
Seu código é para recuperar o Maior ID. Geralmente o último e o maior coincidem, mas não é uma verdade absoluta.
Para saber o último ID inserido automaticamente, o código é esse:
SELECT LAST_INSERT_ID;

Lembrando ainda que nem precisa do SELECT na maior parte das situações, se estiver usando uma biblioteca de MySQL em outra linguagem, ou mesmo o conector em C, é comum ter função específica que já retorna o valor logo após o INSERT.
Mas tenha em mente que isto só funciona se você fez a última inserção na mesma conexão.
Nem tudo são flores: se a última inserção acrescentou 3 registros no DB, esta função retorna o primeiro deles, e não o último.
Como você disse que é uma consulta separada, o que pode ajudar é esta consulta que retorna o próximo ID automático que será usado:
SELECT AUTO_INCREMENT
FROM   information_schema.tables
WHERE  table_name = 'nome da sua tabela'
AND    table_schema = 'nome do seu DB' ;

Mas então, qual o problema do código da pergunta?
Se você quer realmente saber o último inserido, o único recurso seguro é recuperar o dado com LAST_INSERT_ID, ou exagerando, fazendo um trigger para isto.
Por exemplo, veja situações comuns em que o código da pergunta não vai retornar o último valor inserido:

*

*Se os últimos registros forem deletados, o LAST_INSERT_ID ainda vai conter o valor inserido, mas o código da pergunta recuperará os ID anteriores a estes (que não corresponderão aos das próximas inserções).

*Se for feita uma inserção especificando um ID manualmente, menor do que o inserido, não há jeito seguro de saber qual foi o último.
Agora, tem que pensar numa coisa importante: dependendo do uso que você for fazer, você não precisa realmente do último inserido, e sim do maior existente. Neste caso, o código da pergunta resolve.
Alternativamente, você pode usar a técnica do SELECT AUTOINCREMENT acima, e subtrair 1 para estimar qual era o anterior. Isto também não garante que realmente foi o último inserido, mas tem menos probabilidade de dar efeitos colaterais.
Outro cuidado a tomar: pode muito bem acontecer de ocorrer alguma outra transação no DB, e esse valor alterar antes de você usar, então qualquer coisa que fuja do LAST_INSERT_ID pode gerar uma race condition. O ideal é não usar o valor para nada que não seja realmente referenciar a última linha inserida.
Mais um alerta: (para complicar ainda mais a vida) você só deve usar o LAST_INSERT_ID se a última inserção não deu erro, senão pode estar pegando um ID de inserção anterior. Tem gente que testa se deu zero para saber se retornou um ID ou não, mas isto não é confiável se não conferir se o INSERT realmente teve sucesso.
Quanto à performance, o único jeito de se ter certeza, é fazendo benchmarks, pois depende de uma série de fatores.

A: No MySQL é bem fácil. Eu estava tentando fazer a mesma coisa no SQL Server e é um sacrifício.
No MySQL você só precisa usar LAST_INSERT_ID().
Exemplo: SELECT LAST_INSERT_ID() INTO @tabela


text:
Q: Turning off Secondary Replica in Always on availability group for maintenance We are planning to turn off the secondary synchronous replica in our always on availability group for few hours for maintenance . Once we are done with the maintenance then we will need to failover and do maintenance on the original  primary node.
Here is my question for example during the maintenance if there were around 5 gigs of log files that were not applied when we took the secondary node off , now when the secondary comes back online can we immediately failover and make the secondary the new primary or we will have to wait for the logs to be applied to the secondary first to make it synchronized and then failover to make it the new primary.

A: After the secondary replica comes back online, it will not immediately be available for fail over.
You will need to wait for the 5GB of logs to send to secondary and be redone. During which time Primary will have generated more logs that will need to sync and be redone. Once all logs are synched, you'll be able to fail over to secondary without incurring data loss.


text:
Q: Resolution changes once program is built I am creating a Unity project in the 1920x1080 resolution (the same as my monitor). Everything looks fine when testing the program in the Unity editor - however, once built the resolution changes to an unusable state.
I have an option to change the resolution, however, I don't think this is the problem as the resolution is messed up before even changing the setting.
Screenshots:
In Unity , Built
Here are some snippets of code which could be the cause of the problem if I've over looked something. The code is from this tutorial.
void Start ()
{
     resolutions = Screen.resolutions;
     currentResolutionIndex = PlayerPrefs.GetInt(RESOLUTION_PREF_KEY, 0);
     SetResolutionText(resolutions[currentResolutionIndex]);
}

private void SetAndApplyResolution(int newResolutionIndex)
{
     currentResolutionIndex = newResolutionIndex;
     ApplyCurrentResolution();
}

private void ApplyCurrentResolution()
{
     ApplyResolution(resolutions[currentResolutionIndex]);
}

private void ApplyResolution(Resolution resolution)
{
     SetResolutionText(resolution);
     Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
     PlayerPrefs.SetInt(RESOLUTION_PREF_KEY, currentResolutionIndex);
}

A: You need to set the resolution in the Resolution and Presentation section of the Standalone Player settings
You will be able to set how the window will display when opening up from a standalone build.

A: You can set the resolution via script in Start() and write this line
Screen.SetResolution(1920,1080,false);
that will be set you default resolution to 1920*1080.
try this one i hope this will help you.

A: To solve the problem, I've just used Unity's inbuilt 'display resolution dialogue'.
This may seem a little lazy, however, it's solved the problem perfectly and also offers graphics option changes.
Maybe in the future, I'll come back and incorporate resolution settings, but as of now the short popup before launching the game is fine.


text:
Q: Input impedance of a one stage voltage amplifier? This is not a school/university assignment; I'm a physicist trying to learn some electronics. I'd like to calculate the input impedance of the following circuit.

simulate this circuit – Schematic created using CircuitLab
We know that C1 has a reactance of \$X_{C1}=\frac{1}{2\pi f C1}\$, which must be taken into account. That's roughly all that I know! For example I don't know if R2, C2 and the impedance of the output device are important in the calculation of input impedance as well. Also, I'd like to know the equations which show that the input impedance increases by replacing Q with a Darlington pair.

A: For typical sensible design values, the input impedance is dominated by the transistor base, with some effect from the bias resistor(s). The coupling capacitor is typically chosen to have negligible impedance at the frequencies of interest, so you can usually ignore that.

If you use the hybrid-\$\pi\$ model for the transistor, the transconductance of the transistor gm is Ic/Vt or about Ic * 40 at room temperature.
Vt= kT/q where k is the familiar Boltzman constant, T is the temperature (Kelvin) and q is the charge on an electron. It's about 25mV at room temperature.
The value of r\$\pi\$ is \$\beta_0\$/gm, where beta is the current gain of the transistor at the operating point (it's a parameter of the transistor and can vary over a wide range for a given part number, often more than 2:1).
You should also take the effect of the bias resistor R2 into account, however it's not as simple as the resistor in parallel because it's affected by the dependent current sink in the transistor, so it's effectively reduced by the voltage gain of the amplifier. More detailed information in general here. Loading the amplifier output will reduce the voltage gain so the effect due to the bias resistor will be less. If you split the bias resistor into two and bypass it to ground you can get a more constant input impedance- just the r\$\pi\$ in parallel with the left part of R2 (with Xc1 in series, but usually that's negligible).
So to pick some reasonable values, if the collector current (a design parameter) is chosen to be 1.0mA, and beta is 300, then gm = 0.04A/V and the input resistance due to the base is 300/0.04 = 7.5K\$\Omega\$.
Higher beta (as a darlington would have) proportionally increases the input resistance due to the base. You can also increase the bias resistor value.

A: Due to the fact that the bipolar transistor is a highly nonlinear device to simplified the circuit analysis we are using the highly linearized BJT's small-signal model. True only for "small" AC signal only (10mV peak).
http://www.ittc.ku.edu/~jstiles/412/handouts/5.6%20Small%20Signal%20Operation%20and%20Models/section%205_6%20%20Small%20Signal%20Operation%20and%20Models%20lecture.pdf
If we replace the transistor in your circuit with the hybrid-π model, your circuit will look like this:

simulate this circuit – Schematic created using CircuitLab
Where:
\$r_{\pi} = \frac{\beta}{g_m}\$
\$g_m = \frac{I_C}{V_T} \approx \frac{I_C}{26mV}\$
\$I_C\$ - is a quiescent collector current (DC collector current).
In the hybrid-π model, we are treating the BJT as a voltage controlled (vbe) current source (Ic).
That means that the collector current Ic is determined and controlled by the  Vbe voltage, and not by the input current base Ib.
And if you plot \$I_C\$ vs \$V_{BE}\$

The \$g_m\$ is the slope of this curve
In general transconductance \$g_m\$ in simple term is a "gain" for any transconductance amplifier. And because transconductance amplifier is nothing more then a voltage controlled current source (VCCS) the gain expression is \$g_m = \frac{I_{out}}{V_{in}} = \frac{dI_C}{dV_{BE}}\$
And for example, to find the output voltage in you amplifier circuit we can use a nodal analysis and write for the output node:
$$ \frac{V_{OUT}}{R_1} + g_m \cdot V_{IN} + \frac{V_{OUT} - V_{IN}}{R_2} = 0$$
And find the voltage gain is:
$$A_V = \frac{V_{OUT}}{V_{IN}} = - \frac{g_m R_1 R_2 - R_1}{R_1 + R_2} = -\frac{g_m R_1 - \frac{R_1}{R_2}}{1 + \frac{R_1}{R_2}} \approx  - g_m R_1||R_2 $$
And to find the input resistance we can use the same approach and solve for
\$R_{IN} = \frac{V_{IN}}{I_{IN}}\$
But we also can use a Miller's Theorem
Miller's Theorem - Input Capacitance
And find \$R_{IN}\$ by inspection
$$R_{IN} = \left(\frac{R_2}{1 + |A_V|} \right)||\: r_{\pi} = \frac{R_2 r_{\pi}}{R_2 + (1 + |A_V|)r_{\pi}}$$


text:
Q: How to connect to list of servers using a loop in Jenkin pipeline? I'm trying to connect to couple of my Jenkins slaves and run simple command on each of them. This Jenkinsfile code works fine:
pipeline {
agent none
stages {
    stage('alexander') {
        agent { label 'alexanderPig' }
        steps {
            sh "uptime"
        }
    }
    stage('freddy') {
        agent { label 'freddyFox' }
        steps {
            sh "uptime"
         }
    }
}

}
But what if I had 20 slaves? Is there a way to define an array of agents and then simply run sh commands once inside ie. a loop?
Regards!

A: I think matrix may be exactly what you need. You can execute stages in parallel with unique parameter sets (like agent's label). Here's complete example:
pipeline {
    agent none
    stages {
        stage('call salves') {
            matrix {
                agent {
                    label "${SLAVE}"
                }
                axes {
                    axis {
                        name 'SLAVE'
                        values 'alexanderPig', 'freddyFox'
                    }
                }
                stages {
                    stage('do something') {
                        steps {
                            sh 'uptime'
                        }
                    }
                }
            }
        }
    }
}

Matrix is not limited to one dimension, you can provide multiple axes and Jenkins will make cartesian product for you.


text:
Q: mrjob configure_args() error: unrecognized arguments I can't figure out what the error is in my case when creating an argument via add_file_arg() for mrjob.  I'm trying to pass names from csv to my mapper and find attributes for each name in the mapper.
This is my code so far:
from mrjob.job import MRJob
from mrjob.step import MRStep

class MRFlight(MRJob):

    def configure_args(self):
        super(MRFlight,self).configure_args()
        self.add_file_arg('--airlines')
    def steps(self):
        return [
            MRStep(mapper=self.mapper,
                   reducer_init=self.reducer_init,
                   reducer=self.reducer)
        ]

    def mapper(self, _, line):
        (year, month, day, day_of_week, airline, flight_number, tail_number, origin_airport, destination_airport,
         scheduled_departure, departure_time, departure_delay, taxi_out, wheels_off, scheduled_time, elapsed_time,
         air_time, distance, wheels_on, taxi_in, scheduled_arrival, arrival_time, arrival_delay, diverted, cancelled,
         cancellation_reason, air_system_delay, security_delay, airline_delay, late_aircraft_delay,
         weather_delay) = line.split(',')
        yield airline, int(cancelled)

    def reducer_init(self):
        self.airlines_name = {}

        with open('airlines.csv', 'r') as file:
            for line in file:
                code, full_name = line.split(',')
                full_name = full_name[:-1]
                self.airlines_name[code]= full_name
    def reducer(self,key,values):
        total = 0
        num_rows = 0
        for value in values:
            total += value
            num_rows +=1
        yield key,total/num_rows
if __name__ == '__main__':
    MRFlight.run()`

I get such an error:
usage: 07_cancellation_rate_by_airilne.py [options] [input files]
07_cancellation_rate_by_airilne.py: error: unrecognized arguments: --airilines airlines.csv


text:
Q: Integral in vector form I have two vectors $x_{1}$ and $x_{2}$ and some function $f(x, k)$. So for example function $f$ can be evaluated at some point say $f(x_{1}, 10)$. Then I have an integral written $$\int_{x_{1}}^{x_{2}}f(x,k)\ dx$$. I don't know how to calculate an integral written in a such form. So for example if $x$ is $2$-dimensional vector will it be $$\int_{x_{1,2}}^{x_{2,2}}\int_{x_{1,1}}^{x_{2,1}}f(x,k)\ dx_{1}dx_{2}$$? Please, help me to understand this notation.
My question closely relates to notation in the end of first page here where CV calculated http://www.people.fas.harvard.edu/~zlai/teaching/MicroTheory_Note8_Welfare.pdf


text:
Q: Google Cloud Endpoint - How to create handler to call endpoints from cron UPDATED QUESTION
I can't find any sample or tutorial to call endpoints from cron via handler.
Don't have any experience with Backend services!!
Old description and code
I have a GCE module deployed on AppEngine via Android Studio for my Android App.
I am able to create and fetch info via endpoint client stubs in my Android app.
For cleaning data on app engine, there is a simple method that compares and delete any data older than 5 days.
This method is running fine if called through java code.
There is an issue with the cron that I have created. I am not sure if it is running at all or calling the right method inside my endpoint class. Need help in running it automatically.
I have different ways to declare method name and path along with url entry in cron, but no success yet.
Other solutions on stackoverflow are not clear to me.
Endpoint class method
@ApiMethod(name = "cron.cleanData", path="cron/cleanData")
    public void cleanData(@Nullable @Named("cursor") String cursorString,
                                @Nullable @Named("count") Integer count) throws NotFoundException {
        System.out.print("cleanData... called");
        CollectionResponse<Data> listData = listData(cursorString, count);
        for (Data data : listData.getItems()) {
            System.out.print("for..");
                if(isOld(data.getTime(), data.getDate())){
                    removeData(data.getId());
                    System.out.print("removed.."+data.getId());
                }
        }
    }

cron.xml inside WEB-INF
<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
    <cron>
        <url>/cleanData</url>
        <description>Clean Storage</description>
        <schedule>every 1 minutes</schedule>
        <timezone>America/Hawaii</timezone>
    </cron>
</cronentries>

web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
   <servlet>
        <servlet-name>SystemServiceServlet</servlet-name>
        <servlet-class>com.google.api.server.spi.SystemServiceServlet</servlet-class>
        <init-param>
            <param-name>services</param-name>
            <param-value><MY_PACKAGE>.MyEndpoint</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>SystemServiceServlet</servlet-name>
        <url-pattern>/_ah/spi/*</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>ObjectifyFilter</filter-name>
        <filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ObjectifyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>cron</web-resource-name>
            <url-pattern>/cron/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>admin</role-name>
        </auth-constraint>
    </security-constraint>
</web-app>

A:
You cannot call a Google Cloud Endpoint from a cron job. Instead, you
  should issue a request to a target that is served by a handler that's
  specified in your app's configuration file or in a dispatch file. That
  handler then calls the appropriate endpoint class and method.

You can find more details here.


text:
Q: Unity particle outline shader I wish to create an unlit shader for a particle system that emits cube meshes, such that each emitted mesh has a hard black outline around it.
Here is the pass for the outline (in Cg):
struct appdata {
    float4 vertex : POSITION;
    float3 normal : NORMAL;
};

struct v2f {
    float4 pos : POSITION;
    float4 color : COLOR;
};

uniform float _Outline;
uniform float4 _OutlineColor;

v2f vert(appdata v) {
    v2f o;

    v.vertex *= ( 1 + _Outline);

    o.pos = UnityObjectToClipPos(v.vertex);

    o.color = _OutlineColor;
    return o;
}

half4 frag(v2f i) :COLOR { return i.color; }

(And after this is a simple pass to render the unlit geometry of the mesh itself...)
As you can see, we are simply stretching the vertices outward... but from what?
For a single cube mesh, the shader works perfectly:

However, when applied to a particle system emitting cube meshes, the shader breaks down:

My suspicion is that the line v.vertex *= ( 1 + _Outline); stretches the vertices outward from the object center, not the mesh center.
Does anyone have a replacement shader or insight on how to fix this problem?
Thanks,
rbjacob

A: It turns out that I misconstrued the problem. When accessing the POSITION semantic of the vertices, you are getting the vertices of the emitted particles in world space; therefore, stretching the vertices by multiplying is actually just scaling them away from the world center.
To access the vertices relative to each particle, we must be able to access each particle's mesh center from within the shader. To do this, we enable "Custom Vertex Streams" inside the Renderer module of the particle system and press the + button to add the Center stream.

Now we can access TEXCOORD0 (or whatever is specified to the right of the Center stream in the particle renderer GUI) from the shader to get the mesh center in world space. Then we subtract the mesh center from each vertices position, scale outward, and add the mesh center back. And voila, each particle has an outline.
Here are the final vert and frag snippets for the outline pass:
        struct appdata {
            float3 vertex : POSITION;
            float4 color : COLOR;
            float3 center : TEXCOORD0;
        };

        struct v2f {
            float4 pos : POSITION;
            float4 color : COLOR;
            float3 center : TEXCOORD0;

        };

        uniform float _Outline;
        uniform float4 _OutlineColor;

        v2f vert(appdata v) {
            v2f o;
            o.center = v.center;
            float3 vert = v.vertex - v.center;
            vert *= ( 1 + _Outline);
            v.vertex = vert + v.center;
            o.pos = UnityObjectToClipPos(v.vertex);

            o.color = _OutlineColor;
            return o;
        }

        half4 frag(v2f i) :COLOR { return i.color; }

TLDR: Enable vertex streams, add a stream for the particle center, and access this value in the shader to scale individual vertices outward.

A:
My suspicion is that the line v.vertex *= ( 1 + _Outline); stretches the vertices outward from the object center, not the mesh center.

That would be correct. Or mostly correct (particle systems combine all the particles into one runtime mesh and that's what your shader is applied to, not the underlying individual particle mesh, which isn't obvious). Try your outline shader on a non-convex mesh (that is also not a particle): You'll find that the concave part won't have the desired outline, confirming your suspicion.
I wrote this shader a couple of years back because the only free shaders I could find that generated outlines were either (a) not free or (b) of the "just scale it bigger" variety. It still has problems (such as getting jagged and weird at large thickness values), but I was never able to resolve them satisfactorily. It uses a geometry pass to turn the source mesh's edges into camera-facing quads, then stencil magic to render only the outline portion.
However I am unsure if that shader will function when applied to particles. I doubt it will without modification, but you're free to give it a shot.


text:
Q: How to add random values into an empty vector repeatedly without knowing when it would stop? How to count average number of steps? Imagine the process of forming a vector v by starting with the empty vector and then repeatedly putting a randomly chosen number from 1 to 20 on the end of v. How could you use Matlab to investigate on average how many steps it takes before v contains all numbers from 1 to 20? You can define/use as many functions or scripts as you want in your answer.
v=[];
v=zeros(1,20);

for a = 1:length(v)
  v(a)=randi(20);
end

since v is now only a 1x20 vector, if there are two numbers equal, it definitely
does not have all 20 numbers from 1 to 20
for i = 1:length(v)
  for j = i+1:length(v)
    if v(i)==v(j)
      v=[v randi(20)];
      i=i+1;
      break;
    end
  end
end

for k = 1:length(v)
  for n = 1:20
    if v(k)==n
      v=v;
    elseif v(k)~=n
      a=randi(20);
      v=[v a];
    end
    if a~=n
      v=[v randi(20)];
      k=k+1;
      break;
    end
  end
end

disp('number of steps: ')
i*k

A: First of all, the loop generating the vector must be infinite. You can break out of the loop if your condition is met. This is how you can count how many steps you need. You cannot use a loop over 20 steps if you know you'll need more than that. I like using while true and break.
Next, your method of determining if all elements are present is a method of O(n2). This can be done in O(n log n) sorting the elements. This is what unique does. It works by sorting, which, in the general case, is O(n log n) (think QuickSort). So, drawing n elements and after each checking to see if you've got them all is an operation O(n2 log n). This is expensive!
But we're talking about a finite set of integers here. Integers can be sorted in O(n) (look up histogram sort or radix sort). But we can do even better, because we don't even need to physically create the vector or sort its values. We can instead simply keep track of the elements we have seen in an array of length 20: In the loop, generate the next vector element, set the corresponding value in your 20-element array, and when all elements of this array are set, you have seen all values at least once. This is when you break.
My implementation of these two methods is below. The unique method takes 11s to do 10,000 repetitions of this process, and the other one only 0.37s. After 10,000 repetitions, I saw that you need about 72 steps on average to see all 20 integers.
function test

k = 10000;

tic;
n1 = 0;
for ii=1:k
   n1 = n1 + method1;
end
n1 = n1 / k;
toc
disp(n1)

tic;
n2 = 0;
for ii=1:k
   n2 = n2 + method2;
end
n2 = n2 / k;
toc
disp(n2)

end

function n = method1
k = 20;
v = [];
n = 1;
while true
   v(end+1) = randi(k);
   if numel(unique(v))==k
      break;
   end
   n = n + 1;
end
end

function n = method2
k = 20;
h = zeros(20,1);
n = 1;
while true
   h(randi(k)) = 1;
   if all(h)
      break;
   end
   n = n + 1;
end
end

Note on the timings: I use tic/toc here, but it is usually better to use timeit instead. The time difference is large enough for this to not matter all that much. But do make sure that the code that uses tic/toc is inside a function, and not copy-pasted to the command line. Timings are not representative when using tic/toc on the command line because the JIT compiler will not be used.

A: I'm not sure if I understand your question correctly, but maybe have a look at the unique() function.
if
length(unique(v)) == 20

then you have all values from 1:20 in your vector
v = []
counter = 0;
while length(unique(v)) ~= 20
    a = randi(20);
    v=[v a];
    counter = counter +1
end

the value counter should give you the number of iterations needed until v contains all values.
If you want to get the average amount of iterations by trial and error just make a look around this code and test it 10000 times and average the results form counter.


text:
Q: Can Apps be side-loaded rather than uploaded to the iOS app store? If I create a simple App, would it be possible for me to install it in any other devices without having to upload it to the Apple Store and wait for the reviewing process?

A: Yes, there a couple of ways this could be achieved.

*

*With a Enterprise Developer Account, you'll be able to Archive your App for in-house distribution, being eligible any device. Bear in mind that openly distributing your App this way will infringe Apple's agreement and your account could be suspended, as it's meant to be used for a company to distribute an App among its employees.

*With a Regular developer account you could send an ad-Hoc
version of your App, which could be installed into any device
which has been previously registered in your Developer Account. You'll only be able to register 100 devices, though.

With either account, you'll be able to build a version of your App in any device.
Here's Apple's list of their different Developer Programs.

A: Yes, however you will need to set up a provisioning profile and add each device you are installing you app on (you are allowed to provision 100 devices).
You do need to join the iOS Developers program for this to work ($99 per year).
Once you join the developer program you can set up your provisioning profile from the provisioning portal (https://developer.apple.com/ios/manage/overview/index.action) there is an Assistant to walk you through the process (which IMO is a PITA).


text:
Q: Why isn't my function running on document load as expected? This code should set an elements height; however no style gets added. Am I missing something obvious?
function setGround() {
    document.getElementById('content').style.height = '40px';
}

document.onload = setGround;

The HTML is quite basic:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Template</title>
    <link rel="stylesheet" type="text/css" href="css/default.css"/>
    <link rel="stylesheet" type="text/css" href="css/orange.css"/>

sf

sf

Thank you for your help!

A: Don't use document.onload use window.onload instead.
See http://jsfiddle.net/mowglisanu/r6NzE/

A: you can use this:
function setGround() {
    document.getElementById('content').style.height = '40px';
}
document.onload = setGround;

but if you want see changes, you should create border on section tag by use this:

sf

A: You should use
window.onLoad = setGround;

instead of
document.onload = setGround;

A: Where have you placed the javascript-code? Is it in the detect-css.js?
This works:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Template</title>
<link rel="stylesheet" type="text/css" href="css/default.css"/>
<link rel="stylesheet" type="text/css" href="css/orange.css"/>

sf

sf


text:
Q: django - Connect an existing MySQL db to Django I have a database that i would like to use for an app in my new Django project.
I tried adding it to the setting.py by doing the following:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'Colta_create'),
        'USER': 'root',
        'PASSWORD': 'toor123',
        'HOST': '',
        'PORT': ''
    }
}

I have installed mysqlclient, but i get this error:
django.db.utils.OperationalError: (1049, "Unknown database 'colta_create'")


text:
Q: Bulk DELETE does not work on Azure Table Storage I try to delete multiply entities on Azure Table Storage using the code below. According to Microsoft bulk delete operations are allowed for Azure Table Storage. However when I try to execute this code, it returns 405 (Method not allowed) error code:
// replace those values
await TableStorage.BatchDelete("TABLENAME", "ACCOUNTNAME", "ACCOUNTKEY", "PARTITIONKEY", new[] {"RowKey1", "RowKey2"});

private static string CreateAuthorizationHeader(string canonicalizedString, string account, string accountKey)
{
    string signature;
    using (var hmacSha256 = new HMACSHA256(Convert.FromBase64String(accountKey)))
    {
        var dataToHmac = Encoding.UTF8.GetBytes(canonicalizedString);
        signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
    }
    return String.Format(CultureInfo.InvariantCulture, "SharedKey {0}:{1}", account, signature);
}

public static async Task BatchDelete(string table, string account, string accountKey, string partitionKey, IEnumerable<string> items)
{
    var batch = Guid.NewGuid().ToString();

    const string storageServiceVersion = "2013-08-15";
    var contentType = "multipart/mixed; boundary=batch_" + batch;

    var date = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
    var token = String.Format("{0}\n{1}\n{2}\n{3}\n{4}", "DELETE", String.Empty, contentType, date, String.Format("/{0}/$batch", account));
    var authorizationHeader = CreateAuthorizationHeader(token, account, accountKey);

    var builder = new StringBuilder();

    builder.AppendLine("--batch_" + batch);
    builder.AppendLine("Content-Type: multipart/mixed; boundary=changeset_" + batch);
    builder.AppendLine();

    foreach (var item in items)
    {
        var url = String.Format("https://{0}.table.core.windows.net/{1}(PartitionKey='{2}',RowKey='{3}')", account, table, HttpUtility.UrlPathEncode(partitionKey), HttpUtility.UrlPathEncode(item));

        builder.AppendLine("--changeset_" + batch);
        builder.AppendLine("Content-Type: application/http");
        builder.AppendLine("Content-Transfer-Encoding: binary");
        builder.AppendLine();

        builder.AppendLine("DELETE " + url + " HTTP/1.1");
        builder.AppendLine("Content-Type: application/json");
        builder.AppendLine("Accept: application/json;odata=nometadata");
        builder.AppendLine("Prefer: return-no-content");
        builder.AppendLine("DataServiceVersion: 3.0;");
        builder.AppendLine("MaxDataServiceVersion: 3.0;NetFx");
        builder.AppendLine("If-Match: *");
        builder.AppendLine();
        builder.AppendLine();
    }

    builder.AppendLine("--changeset_" + batch + "--");
    builder.AppendLine("--batch_" + batch + "--");

    var content = Encoding.UTF8.GetBytes(builder.ToString());

    using (var client = new WebClient())
    {
        client.Encoding = Encoding.UTF8;
        client.Headers.Add("x-ms-date", date);
        client.Headers.Add("x-ms-version", storageServiceVersion);
        client.Headers.Add("Authorization", authorizationHeader);
        client.Headers.Add("Accept-Charset", "UTF-8");
        client.Headers.Add("DataServiceVersion", "3.0");
        client.Headers.Add("MaxDataServiceVersion", "3.0;NetFx");
        client.Headers.Add("Content-Type", contentType);

        await client.UploadDataTaskAsync(String.Format("https://{0}.table.core.windows.net/$batch", account), "DELETE", content).ConfigureAwait(false);
    }
}

Why do Azure returns this error code and how can I avoid this?

A: It's because Entity Batch Transaction is a POST operation and in your code above you're passing DELETE as HTTP method.

Ref: http://msdn.microsoft.com/en-us/library/azure/dd894038.aspx


text:
Q: Solid conducting sphere, its material, electric field and electric potential I have tried reading multiple post from stackexchange google, but still cannot figure it out:
lets say if i wrote "A solid sphere has charge distributed uniformly throughout..."
can i conclude that sphere is not made up of metal?
in this statement, I find things to be paradoxical. out of all these statements, that i equally find it inaccurate?
for example "sphere is not made up of metal?" , charged can be distributed uniformly in any kind: like in charged conductor (excess charges go to the surface but non-excess/remaining one which was present initially still remains), uncharged conductor(can have uniform charged distribution, can also have non-uniform charge distribution) or non-conductor/insulator (because we know that unlike conducting sphere that has charge distributed only on the surface, non-conducting sphere tends to distribute charges throughout the volume of sphere), so not enough information for "sphere is not made up of metal?"
please let me know if any of my statement is wrong and help me approach this concept, and clear all my doubts, misunderstanding, knowledge gaps.

A: Your incorrect interpretation is in the following statement:

like in [a] charged conductor (excess charges go to the surface but non-excess one which was present initially still remains)

I'm not sure what you mean by "non-excess charge", but the general result is that there is no net charge in the interior of a conductor.  It's true that on a microscopic level there are equal amounts of positive and negative charges inside an electrically neutral piece of metal;  perhaps that's what you mean by "non-excess charge"?
But when the question asks about a "charge distributed uniformly throughout", it is referring to a "non-zero net charge distributed throughout".  And such a charge distribution cannot exist inside a conductor.

Edit: the quotes below were included in a previous version of the question, so I am leaving these answers here for posterity; but they are not relevant to the question as currently posed.
Beyond this, you have a few other misconceptions I can identify:

electric potential is not constant on the surface with respect to what? infinity(outside the sphere) ?, center? earth's ground?

Whether or not the electric potential is constant on some surface doesn't depend on your reference point.  If I redefine my reference point, that just adds a constant to all of my potential values everywhere in space.  That means that (for example) if $V = -3$ volts everywhere on the surface of the sphere in my old system, and I redefine my potential so that it adds $+5$ volts to all potential values everywhere in space, then we have $V' = +2$ volts everywhere on the surface in my new system and it's still constant.

V(at surface) is constant in uncharged conductor and not in charged conductor.

$V$ on the surface is constant for both charged and uncharged conductors.  This follows from the fact that the electric field inside the conductor must be zero.

i know electric field inside a metal conductor is always 0 because charges redistribute themselves to create internal electric field and oppose the external electric field to make E = 0 inside... but usually questions(like this for example) dont specify whether external electric field is present or not. what if external electric field is absent? how will they make E = 0? or will it won't be 0?

In electrostatics, the electric field inside a conductor (charged or neutral) is always zero, regardless of whether or not there is an external field.

there is another notion of symmetry. the question doesnt specify whether sphere is symmetric or not, because it can have non-symmetric but uniformly distributed charge. i think when charge is uniformly distributed, it is ALWAYS symmetric unlike non- uniform where both can be symmetric and non- symmetric. V IS constant in symmetric(uniform) but not in non-symmetric(uniform)

"Non-symmetric but uniformly distributed" is a contradiction.  "Uniformly distributed" means that the net charge density is the same everywhere inside the sphere.  If that's the case, then the charge distribution is automatically spherically symmetric, since rotating the sphere to any other orientation doesn't change the charge distribution—it's still the same everywhere.


text:
Q: How to convert time in c# How do i convert this date 1/6/2016 12:00:00 AM to 2016-01-06T00:00:00 in C#. I need to display it like that.
EstimatedDate.ToString("");

SOLVE:
string.Format("{0:s}", EstimatedDate)

A: You can use The "s" standard format specifier which is exactly generate the result you want.
EstimatedDate.ToString("s");

From documentation;

The pattern reflects a defined standard (ISO 8601), and the property
  is read-only. Therefore, it is always the same, regardless of the
  culture used or the format provider supplied. The custom format string
  is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".

A:
EstimatedDate.ToString("yyyy-MM-ddTHH:mm:ss"); sill give you the desired format
For a full example of:
DateTime date = DateTime.Parse("1/6/2016 12:00:00 AM");
string dateStr = date.ToString("yyyy-MM-ddTHH:mm:ss");

Update from @soner-gönül: - This method is Cultural dependent, where as "s" is not. CurrentCulture must be Gregorian Calendar for this to work.
cs timestamp time


text:
Q: How can I define the spacing following a paragraph in prawn pdf? I'm rendering texts in a prawn pdf report and would like to define the exact spacing after a paragraph.
I found :leading, which helps to define the line height, but nothing to define the spacing after a new paragraph (within the same cell or bounding box).

A: So far I have not found out how to define the spacing as such, but I still think I found the problem why the space was too large.
I add the statement
puts content.dump

to my class to print the content on the console.
In the cases where I had a paragraph in the content, the paragraph was replaced by \n\n.
Example:

Text

Text

is changed to
"Text\n\nText\n\n"

As I anyway use an html sanitizer method to remove undesired html tags, I could extend the method with the following:
res = content.gsub(/\n{2,2}/, "\n")
res = res.gsub(/\n{3,}/, "\n\n")

This solved the problem for me.


text:
Q: Ghostscript pdf2jpg - colours wrong? I'm using the Ghostscript API from c#, to convert multipage PDF's to jpgs.
My issue is with colour conversion.
When I open the Source PDF in photoshop, and export to jpeg, each colour in each jpeg matches the colours of the original PDF perfectly.
However, when I run the process through Ghostscript, the colour come out as different shades than the original. eg:
Original PDF colour: #8DBB3F;
Photoshop pdf to jpg colour: #8DBB3F;
Ghostscript pdf2jpg colour: #7DEE00;
This happens with all colours - all slightly to massively different shades.
These are the arguements passed to ghostscipt:
"pdf2jpg -dNOPAUSE -dBATCH -dSAFER -sDEVICE=jpeg -r150 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dMaxStripSize=8192 -sOutputFile=myfile-%d.jpg
Can anyone help?

A: try "-dUseCIEColor"

A: Add -dUseCIEColor (as sovo said) plus try adding -dJPEGQ=95 to set JPEG quality to 95%.
Also, you may want to try -sDEVICE=jpegcmyk to make the JPEG use the CMYK color space.
(-sDEVICE=jpeg uses RGB colors. If your PDF had used CMYK, conversion to RGB will probably cause more color deviations, especially in the absence of ICC profile usage.)

A: -dUseCIEColor worked for me, BUT then I tried using an updated DLL version, and that solved the issue without passing in the new flag, and it also resolved my font rendering issue with an embedded font. I replaced by older DLL with the version 9.16. I also was able to leave my jpeg quality at 100.

A: Try DPI parameter value 300+ (-r300) in ghostscript


text:
Q: Error in forestplot.default: You have provided 2 rows in your mean argument while the labels have 34 rows I am trying to make a forestplot in R.
Sample provided by this site: https://designdatadecisions.wordpress.com/2016/07/02/forest-plot-with-horizontal-bands/
Starting with reading the data in R.
Formatting so the column labels and columns match
subgps <- c(4,5,8,9,12,13,16,17,20,21,24,25,28,29,32,33)
data$Variable[subgps] <- paste("  ",data$Variable[subgps])
np <- ifelse(!is.na(data$Count), paste(data$Count," (",data$Percent,")",sep=""), NA)
tabletext <- cbind(c("Subgroup","\n",data$Variable),
                    c("No. of Patients (%)","\n",np),
                    c("4-Yr Cum. Event Rate\n PCI","\n",data$PCI.Group),
                    c("4-Yr Cum. Event Rate\n Medical Therapy","\n",data$Medical.Therapy.Group),
                    c("P Value","\n",data$P.Value))

So far no error.
After I try to do the second step, an error shows-up.
The second step is as following:
library(forestplot)
png(file.path(workdir,"Figures\\Forestplot.png"),width=960, height=640)
forestplot(labeltext=tabletext, graph.pos=3,
           mean=c(NA,NA,data$Point.Estimate),
           lower=c(NA,NA,data$Low), upper=c(NA,NA,data$High),
           title="Hazard Ratio",
           xlab="     <---PCI Better---    ---Medical Therapy Better--->",
           hrzl_lines=list("3" = gpar(lwd=1, col="#99999922"),
                          "7" = gpar(lwd=60, lineend="butt", columns=c(2:6), col="#99999922"),
                          "15" = gpar(lwd=60, lineend="butt", columns=c(2:6), col="#99999922"),
                          "23" = gpar(lwd=60, lineend="butt", columns=c(2:6), col="#99999922"),
                          "31" = gpar(lwd=60, lineend="butt", columns=c(2:6), col="#99999922")),
           txt_gp=fpTxtGp(label=gpar(cex=1.25),
                              ticks=gpar(cex=1.1),
                              xlab=gpar(cex = 1.2),
                              title=gpar(cex = 1.2)),
           col=fpColors(box="black", lines="black", zero = "gray50"),
           zero=1, cex=0.9, lineheight = "auto", boxsize=0.5, colgap=unit(6,"mm"),
           lwd.ci=2, ci.vertices=TRUE, ci.vertices.height = 0.4)
dev.off()

Error:

Error in forestplot.default(labeltext = tabletext, graph.pos = 3, mean
  = c(NA,  :    You have provided 2 rows in your mean argument while the labels have 34 rows

What does this even mean? How to solve This?

A: It means what it says. From the documentation for forestplot:

mean: A vector or a matrix with the averages. You can also provide a 2D/3D matrix that is automatically converted to the lower/upper parameters.

Did you check data to make sure you imported it correctly? If you downloaded it from the link on the blog, it's an .xlsx file.
what do you see, for example, when you try data$Point.Estimate?
If it's NULL (I suspect it is), then try downloading it with the openxlsx package:
install.packages("openxlsx")
library(openxlsx)
data <- read.xlsx("ForestPlotData.csv")
# Presuming you downloaded the file correctly from the url, and its
# in your working directory, and titled "ForestPlotData.csv"


text:
Q: Transcendental terms What does it mean for two curves parametrised about 0 (say the graph of two functions of real variable) to 'differ only by transcendentally small terms'? How does this relates to their Taylor expansion at 0?

A: After some research in the direction of asymptotic series expansions, I think the meaning of transcendentally small is that it vanishes faster than any polynomial order. For example, for a power series expansion of the curve's equation, transcendentally small terms could be terms that vanish faster than any monomial involved in the power series representing it. Hence the two curves will have the same power series expansion, without being the same curve, since the 'transcendentally small terms' elude the description via power series, being described by the null power series themselves.


text:
Q: Keep iconified JInternalFrames on top always I have 5 JInternalFrames in one JDesktopPane. I have to keep 4 JInternalFrames iconified and keep only 1 active. But when I maximize 1 JinternalFrame, other iconified JInternalFrames goes behind it, so I have to iconify the active JInternalFrame and then restore the required one.
Is there a way that I can keep all my Iconified JInternalFrames on top always?

A: Use JDesktopPane.setComponentZOrder(java.awt.Component, int) and ensure that the iconified frames are in a layer which is above the one that is not iconified.

A: Im not sure if this helps in your case, but if you want to have a specific ordering (e.g. one JInternalFrame should always be in front of others) then simply dont use a JDesktopPane. Simply use the DefaultPane:
Default:
setContentPane(new JDesktopPane());  // Will bring the currently activated JInternalFrame to top
add(frame_A);
add(frame_B);
add(frame_C);

Always on top:
// setContentPane(new JDesktopPane()); // Dont use the DesktopPane
add(frame_A); // Will always be on top
add(frame_B); // Will always be in front of frame c but behind frame a
add(frame_C);


text:
Q: JQueryUI - Slide divs left/right at the same time I'd like to slide two divs at the same time (left/right, right/left, up/down, down/up). Here's a JSFiddle where it does that, but when I hide the divs in this JSFiddle, it's not simultaneous on top of each other. I've tried using animate and more on direction, but have come to no avail.
This is some of the code I have written:
$( document ).ready(function() {
    $('#div2, #div3, #div4, #div5, #div6, #div7, #div8').hide();
    $('#div2').delay(2000).toggle('slide', {direction: 'left'}, 'slow');
    $('#div3').delay(3000).toggle('slide', {direction: 'up'}, 'slow');
    $('#div4').delay(4000).toggle('slide', {direction: 'down'}, 'slow');
    $('#div5').delay(5000).toggle('slide', {direction: 'left'}, 'slow');
    $('#div6').delay(6000).toggle('slide', {direction: 'right'}, 'slow');
    $('#div7').delay(7000).toggle('slide', {direction: 'down'}, 'slow');
    $('#div8').delay(8000).toggle('slide', {direction: 'up'}, 'slow');
});

A: If I understand correctly you want the left and right, or top and bottom to slide at the same time, if this is correct just change the delay to be the same
$('#div5').delay(1000).toggle('slide', {direction: 'left'}, 'slow');
$('#div6').delay(1000).toggle('slide', {direction: 'right'}, 'slow');

fiddle


text:
Q: How to handle C# large MSMQ data calls to SQL stored procedures efficiently? I have been searching extensively for solutions or alternatives to the following approach to handle large data processing:
We are currently using a C# Windows service (call it Listener) to listen to TCP ports and save incoming messages to the MSMQ (Message Queue) to make sure that no data is lost. At the same time, we have another C# Windows service (call it Decoder) that reads from the MSMQ, processes the data in multiple threads and calls SQL stored procedures to save the data and do additional data processing.
The rate of incoming messages is around 10,000 message/second and each message is processed individually by the Decoder and then send to the SQL SP, but recently we are facing some issues related to the performance and high Server resources usage (CPU and RAM).
We are currently investigating using SQL Server Integration Service (SSIS) as an alternative to read the messages from the message queue and do the processing and execute the stored procedures but it seems like it has some limitation when it comes to the Message queues.
Now my question is, what do you think are better alternatives to the current system design given that we have to use SQL Server to store data?

A: SSIS is intended for ETL-type workloads -- think batch processing files and synchronizing data across systems (especially rdbs).
Processing lots of messages which need a bit of massaging, Kafka (https://kafka.apache.org/) and hadoop might do better there.  Even if at the end of the process it pushes data to SQL server or you pull it in via ssis.
m


text:
Q: Error in generating dynamic table by fetching data from array in Angular I am trying to generate a dynamic table by getting data from array. Please check the attached image in which there is the array of result which I am getting from API. I am trying to use keys as table headers and values as table data.
I have tried with *ngFor loop and through key value loop but I am not getting anything from array.
Below is the code chunk I am using:
{{row}}

Moreover, I am getting data correctly in debugQueryData.
How can I write the correct loop to generate dynamic table?

A: you can use this code
{{key + ' : ' + debugQueryData[key]}}
what this code does is to get each key of your object individually then getting then value by passing key to object


text:
Q: gravity forms calculation jquery Is there a way to integrate a simple jquery function to gravity forms?
I have 3 fields that I need to use with.
2 number fields and 1 total field, total will be calculated based on the number fields.
Here is the script, I managed to make it work but there is no ajax and the total field is just showing the number and not the $price.
function calc_price()
    {
        var sr = parseInt($("#d_start_rating").val());
        if(!sr){
            sr = 0;
            $("#d_start_rating").val(sr);
        }
        var er = parseInt($("#d_end_rating").val());
        if(!er){
            er = 0;
            $("#d_end_rating").val(er);
        }

        if(er > 6000){er = 6000}
        var points = 0;

ranges = {"2500":0.09,"3000":0.11,"3500":0.15,"4000":0.21,"4500":0.27,"5000":0.35,"5500":0.45,"6000":0.8};
        //var ranges = {2500: 0.08, 3000: 0.11, 3500: 0.14, 4000: 0.20, 4500: 0.24, 5000: 0.30, 5500: 0.35, 6000: 0.6};
        for(var key in ranges){
            if(sr >= er){break;}
            if(key > er){
                points += (er-sr)*ranges[key];
                sr = er;
                break;
            }
            if(sr < key){
                points += (key - sr) * ranges[key];
                sr = key;
            }
        }
        points = Math.ceil(points);
        $(".a_points").html(points);
    }

    $(document).ready(function() {
        $('#d_start_rating').change(function() {
            calc_price();
        });
        $('#d_end_rating').change(function() {
            calc_price();
        });

        calc_price();
    });

A: you're looking for the gform_post_render JS event. You can bind your custom functionality to this event rather than the document ready event.
<script type="text/javascript">

$(document).bind('gform_post_render', function(){

    $('#d_start_rating').change(function() {
        calc_price();
    });

    $('#d_end_rating').change(function() {
        calc_price();
    });

    calc_price();

});

</script>


text:
Q: ChangeNotifier Not updating widget Im trying to update the listView below every time a new element (location) is added to the database but
it is updated only once I close and reopen the app but not when the user navigate to LocationHistory page
class LocationHistory extends StatefulWidget {

  @override
  _LocationHistoryState createState() => _LocationHistoryState();
}

class _LocationHistoryState extends State<LocationHistory> {

  Widget build(BuildContext context) {

            return Scaffold(

              appBar: AppBar(

                leading: new IconButton(
                  icon: Icon(Icons.arrow_back),
                  onPressed: () => Navigator.of(context).pop(),
                ),
                title: Text("Saved Locations"),

              ),

              body: Consumer<LocationHistoryModel>(
                  builder: (context, locationHistoryModel, child){
                  return ListView.builder(
                  itemCount: locationHistoryModel.currentUserLocations.length,
                  itemBuilder: (context, index) =>
                      Column(
                        children: <Widget>[
                          buildListTile(
                            address: locationHistoryModel
                                .currentUserLocations[index].address,
                            createdAt: locationHistoryModel
                                .currentUserLocations[index].createdAt,
                            inOut: locationHistoryModel
                                .currentUserLocations[index].inOut,
                          ),

                        ],
                      )

              );}

            ),);

  }
}

The locationHistoryModel where I use notifyListeners to notify the list to rebuild itself
class LocationHistoryModel extends ChangeNotifier{

  final locationHistory = LocationHistoryRep();
  List currentUserLocations =[];
  User _user;

  set user(User value) {
    _user = value;
  }

  User get user => _user;

  LocationHistoryModel () {

    getLocationHistory();

  }

  getLocationHistory() async{

    var locationsHistory = await locationHistory.getAllSavedLocations();

    List allUsersLocations = locationsHistory["data"] ;

    for(int i =0; i<allUsersLocations.length;i++){

           if(allUsersLocations[i]["userId"]==_user.id){
             currentUserLocations.add(LocationElement.fromJson(allUsersLocations[i]));
           }
    }
    notifyListeners();

    return currentUserLocations;

  }

  setLocation({String address, String inOut}) async{

     await locationHistory.addCurrentLocation(address: address,inOut: inOut,userId: _user.id);
    notifyListeners();

  }

Widget from where I try to update the list here when I navigate to the list no changement are found
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GoogleMapController mapController;

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  void initState() {
    super.initState();
    Provider.of<AuthModel>(context, listen: false).getUser();

  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    final location = Provider.of<Location>(context);
    final locationHistory = Provider.of<LocationHistoryModel>(context);

    return location.currentLocation == null ? Scaffold(body: CircularIndicator()): Scaffold(

      appBar: AppBar(
        centerTitle: true,
          backgroundColor: Colors.orange,
        title: Center(child: Text('Remote Tracker')),

      ),

      ),
      floatingActionButton: new FloatingActionButton(
        backgroundColor: Colors.orange,
        child: const Icon(Icons.location_on),
        onPressed: () async{

          showDialog(context: context,
              builder: (BuildContext context){
                return AdvanceCustomAlert(
                  location.address,
                      () async{
                    await locationHistory.setLocation(address: location.address,inOut: "out");
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => LocationHistory(),
                    // here when navigating to LocationHistory the list is not updating
                    ));
                    },
                      () async{
                    await locationHistory.setLocation(address: location.address,inOut: "in");
                    Navigator.of(context).pop();

                    },
                );
              }
          );// Add your onPressed code here!
        },
      ),
      floatingActionButtonLocation:
      FloatingActionButtonLocation.centerFloat,
      bottomNavigationBar: new BottomAppBar(
        color: Colors.white,

      ),
        body: Container(
          width: size.width,
          height: size.height,
          child: Stack(
            alignment: Alignment.centerRight,
            children: <Widget>[
              GoogleMap(
                onMapCreated: _onMapCreated,
                myLocationEnabled: true,
                initialCameraPosition: CameraPosition(
                  target: LatLng(location.currentLocation.latitude,location.currentLocation.longitude),
                  zoom: 14.0,
                ),
              ),

            ],
          ),
        ),

    );
  }
}


text:
Q: find not passing mtime into ImageMagick I have a terminal command
find "/Users/tcokimac/Desktop/find"  -size +2MB  -mtime +60 -exec convert "{}"  -resize 80% -quality 80%  /Users/tcokimac/Desktop/find/IMG_0096.JPG  -set filename:base "%[basename]" "/Users/tcokimac/Desktop/new/%[filename:base].jpg" \;

It is supposed to scan a directory of images more then 2MB and less then 60 days old and convert them into a new folder. But the scan results no images found
Solution found it was my coding, -mtime +60 is everything over 60 days, needed to change to -60 for all files under 60 days –
    find "/Users/tcokimac/Desktop/find"  -size +2MB  -mtime +60 -exec convert "{}"  -resize 80% -quality 80%  /Users/tcokimac/Desktop/find/IMG_0096.JPG  -set filename:base "%[basename]" "/Users/tcokimac/Desktop/new/%[filename:base].jpg" \;


text:
Q: Git: briefly go back by a few commits and then come back I am on branch myBranch and I have some unstaged, uncommitted changes in my working dir.
I want to briefly go back by a few commits on this branch to just peek at the code, so I do this:
git checkout <specific-commit-hash>
After I recompiled the checkouted code etc., I want to "undo everything", that is: retrieve my previously unstaged and uncommitted changes.
Perhaps git stash could find usage here?

A: Yup, git stash would be a good choice here. You would git stash on the branch you are currently in, then git checkout the branch you wish to work on. When you're finished, git stash pop to restore your stashed code.
Some good resources on git stash:

*

*https://www.atlassian.com/git/tutorials/saving-changes/git-stash

*https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning

A: Briefly, git stash.
git stash
git checkout <something>
// do stuff
git reset .  // maybe you want to discard edits
git checkout <back to the start>
git stash pop


text:
Q: How to add fallback or avoid geting error when api returns NULL for image src in REACT JS <img className="cast-card__avatar" style={{backgroundImage: `url(${person.image.medium})`}}/>

*

*person.image.medium is returning null value getting error due to this how to provide a fallback

*person is object returned from api call person.image.medium has images but some of them contain null  values getting error due to this

const addDefaultSrc = (ev) => {
 ev.target.src =
   "https://images.unsplash.com/photo-1555952517-2e8e729e0b44?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80";
};

3 i tried out this also but this too doesnt work

A: You have two options.
Option 1
Only render the image if person.image.medium exists:
{person.image.medium && }

Option 2
Render a default image if person.image.medium does not exist:

A: You can use multiple backgrounds, if first one is not available it will go for the second one and so on.
Try this:
<div
    className="cast-card__avatar"
    style={{backgroundImage: `url(${person.image.medium}), url(${fallback_image_1}), url(${fallback_image_2})`}}
/>

A: There are different ways to handle this, see below.
{person && person.image && person.image.medium && }

Image tag should have a src, so chnage img to div

You can also try like this