text:
Q: Error with nicescroll scrolling down I have a html document in which my chat is running. After receiving a new message i add it with .append. After that i want to scroll down to the bottom of the chat window. but due to some reason nicescroll wont scroll down completly.
my html element:

 // class chat is unique

              //messages

the jquery script:
  $('#new_messages').append(messagehtml);
  $('.chat').getNiceScroll(1).resize();
  $('.chat').getNiceScroll(1).doScrollTop($('#chat_body').height() - 1, 1);

nice scroll(1) because there is another nicescroll element on the site.
Using $('.chat').getNiceScroll(1).doScrollTop($('#chat_body').height() - 1, 1); in the chrome developer console works perfectly fine.
I'm wondering why. Maybe .append is to slow?

A: I face the same problem. The only way I overcome it, is by adding one
 at the last of the content.

A: make a change in the plugins,
replace the following
(q=!1,e.stopImmediatePropagation(),e.preventDefault())

with
(q=!1,e.stopImmediatePropagation())


text:
Q: How to call the Search bar from homepage to all other pages in Magento 1.9? My Search bar is currently on my Homepage
Code is:
<reference name="header">
    <block type="core/template" name="top.search" as="topSearch" template="catalogsearch/form.mini.phtml"/>
</reference>

I want to make the search bar appear on my New products Page

A: in your local.xml
<catalog_product_view>
   <reference name="product.info">
      <block type="core/template" name="product.view.search" as="productViewSearch" template="catalogsearch/form.mini.phtml"/>
   </reference>
</catalog_product_view>

then in app/design/frontend/rwd/default/template/catalog/product/view.phtml add call children
<?php echo $this->getChildHtml('productViewSearch') ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the advantages of Btrfs for end users? Btrfs has begun to gain some momentum in replacing ext4 as the default filesystem of choice for a few distributions such as Fedora Core 16. It is experimentally available in a number of other distributions (From Wikipedia: openSUSE 11.3, SLES 11 SP1, Ubuntu 10.10, Sabayon Linux, RHEL6,MeeGo, Debian 6.0, and Slackware 13.37). I'm certainly not ready to convert all my workplace servers over (my file system choice is generally conservative), I'm considering using it at home and on select non-mission critical production machines at work.
Btrfs brings a feature set that is similar to ZFS in many ways. I can understand why this would be desirable in an "enterprise" environment, especially with systems that focus on storage delivery. But how is this same feature set useful for end users? What advantages does Btrfs' feature list give me on machines whose primary function is not the presentation of storage? What advantages does it give me on my laptop?
Outside of enterprise storage, why should I bother switching to Btrfs from the tried and true Ext filesystem?

A: BTRFS has matured considerably over the years (since this question was asked). It's now pretty stable for most simple use cases, even for different RAID levels (e.g., RAID-1 - stable and easy to set up). Given the fact that BTRFS stores checksums, it's able to reliably detect corruption (unlike classic RAID systems where only parity is available).
Current versions are even able to fix typical errors in a BTRFS RAID-5 filesystem (for example by replacing a failed drive) (although raid56 still needs improvement, see update below).
If a repair/replace operation crashes, first update the kernel (which probably fixes this issue) - and if necessary, BTRFS has some recovery features. Even in the worst case (like multiple drive failures), you'll often be able to copy the files that are still ok and you'll know which files are damaged. So ignoring all those other features (like snapshotting, CoW copies, subvolumes), BTRFS could be used if detecting data/file corruption is a main priority.
Update: In June 2016, it was discovered that the RAID-5/6 implementation in BTRFS is flawed. BTRFS in general is stable - but the raid56 implementation is very new, has been considered experimental anyway and should now only be used for testing until it's been fixed. If you're using RAID-5/6, you might want to convert to RAID-1. It still offers advantages for end users like checksumming (other filesystems may not know about corrupted files at all) and protection if a drive fails.
Reference: BTRFS sometimes calculates wrong parity

A: From wiki:

Extent based file storage
2^64 byte == 16 EiB maximum file size
Space-efficient packing of small files
Space-efficient indexed directories
Dynamic inode allocation
Writable snapshots, read-only snapshots
Subvolumes (separate internal filesystem roots)
Checksums on data and metadata
Compression (gzip and LZO)
Integrated multiple device support
    RAID-0, RAID-1 and RAID-10 implementations
Efficient incremental backup
Background scrub process for finding and fixing errors on files with redundant copies
Online filesystem defragmentation

Explanation for desktop users:

*

*Space-efficient packing of small files: Important for desktops with tens of thousands of files (maildirs, repos with code, etc).

*Dynamic inode allocation: Avoid the limits of Ext2/3/4 in numbers of inodes. Btrfs inode limits is in a whole different league (whereas ext4's inodes are allocated at filesystem creation time and cannot be resized after creation, typically at 1-2 million, with a hard limit of 4 billion, btrfs's inodes are dynamically allocated as needed, and the hard limit is 2^64, around 18.4 quintillion, which is around 4.6 billion times the hard limit of ext4).

*Read-only snapshots: fast backups.

*Checksums on data and metadata: essential for data integrity. Ext4 only has metadata integrity.

*Compression: LZO compression is very fast.

*Background scrub process to find and to fix errors on files with redundant copies: data integrity.

*Online filesystem defragmentation: autodefrag in 3.0 will defrag some types of files like databases (e.g. firefox profiles or akonadi storage).

I recommend you the kernel 3.0. Also btrfs is a good FS for SSD.

A: For the benefits: I believe it will be mainly the backup and mirroring features.
But why would you be so hasty as to think of btrfs as a filesystem ready to replace any of your current ones? Both the wiki you refer to :
(...) it is currently possible to corrupt a filesystem irrecoverably if your
machine crashes or loses power on disks that don't handle flush requests
correctly. This will be fixed when the fsck tool is ready.

and the 3.0 kernel documentation
  Btrfs filesystem (EXPERIMENTAL) Unstable disk format
  (...)
  Btrfs is highly experimental, and THE DISK FORMAT IS NOT FINALIZED.
  You should say N here unless you are interested in testing Btrfs
  with non-critical data.

clearly discourage you from using btrfs for any other purpose than testing.
But when it comes to form, I believe for the end-user will only have value for private data like things in one's home directory. There will be no need for the safety net of moving things to trash - actually there will be a need of redefining the "trash" on desktop environments. Rest of the features will probably just end up (to the user) as feeling faster (if at all), but more quickly eating up the disk space.


text:
Q: Best way of showing subwebs in a list We have a root projects site, then we are planning to create a seperate project site for each project becaue of different permissions on each site.
Each project site will consist of few documents and just 1 list item, which will have information about the project, for example 21 custom columns.
Now I want to display a list of all projects on project root site with there statuses, status is in project site list column what is the best approach for this ?
this is office 365
as each project site will have only 1 list item, can i not just create a root site with a list of projects with 20 columns and give list item permission level to them ?
CN

A: In root site create a List which will store the Project information(lets call it "Project Information").Create a Library which will store the project documents(lets call it "Project Documents").Since Project Information list will have only 1 item per project you can do 2 approaches to display this data to only project members.

*

*Item level permission- Create item level permission .You can do this manually through UI or you can use SharePoint 2010 designer workflow impersonation step(This will work even for SP2013, just select SP 2010 workflow platform while creating designer workflow).See this Blog
Replace item permissions using designer

*Do not create item level permission, add a column project members which contains the project members (multi users) or the project SPGroup, filter the items in the view such that user can see only those items in which Project members=[Me] or user is present in the project members group of that item.

*Create a workflow which will be activated when item is added to Project Information list, which will create a folder with Project Name in Project Documents library and replace permissions.
Here is link to a blog to create folder in library through designer workflow.
Step 3 can also be done manually if you wish instead of automating through workflow.

A: Create Site Columns and Site COntent type for the list item that goes in each sub site.
In the root site, use a Content Search Web part to show all items in the site collection that have that content type. Search will automatically security-trimmed the items, so each user will only see the item(s) for which they have permission.

A: The one-item list seems like a hacky approach. Here's how I would do it:
Create a custom content type with your project-level metadata. Make it a child of the Web Part Page content type. Add that content type to your SitePages library and set your home pages to that content type.  Then you can add a CQWP to the root site and set it to look for your custom "Project Home Page" content type.  In your CQWP you can group by status or display your data any way you wish.
There are a couple of advantages to this approach: You eliminate the need for a one-item list, and you can also leverage your custom content type in a Search scenario if you so choose.


text:
Q: Is there any central repository in Azure APIM to save keep definitions, policy etc.? Does Azure API Managment provide a central repository to keep the definitions and refer them at runtime? I am looking for a central repo similar to Domain in Swagger.

A: No. There is no store option in APIM


text:
Q: .htaccess Redirect 301 Issue I am having an htaccess issue that I cannot seem to figure out.
On my site I have several pages that have /wiget/ in the url.
.com/wiget/
.com/wigeta/
.com/wigeb/
.com/wigetc/
.com/shop/wigeta/
.com/shop/wigetb/
In my htaccess file I am using the following:

*

*Redirect 301 /wiget/ http://www.site.com/content/wiget/

*Redirect 301 /wigeta/ http://www.site.com/content/wigeta/

*Redirect 301 /wigetb/ http://www.site.com/content/wigetb/

*Etc.

What is happening, is that every URL with /wiget/ /wigeta/ /wigetb/ in it is getting redirected incorrectly. For example, these urls:

*

*.com/shop/wiget/ is being sent to .com/shop/content/wiget/

*.com/shop/wigeta/ is being sent to .com/shop/content/wigeta/

*.com/shop/wigetb/ is being sent to .com/shop/content/wigetb/

What I want is only pages that have .com/wiget/ or .com/wigeta/ or .com/wigetb/ to be redirected to their .com/content/wiget{x}/ page
I am a rookie at htaccess and I cannot drum up the solution.

A: So basically you want to specify that your url have to start with /wiget/
RewriteRule ^/wiget/ /content/wiget/ [L,R=301]


text:
Q: how to interrupt a form submit to call some javascript? I'm using a form provided to me by PayPal in order to sell something on my website. Before the user hit "checkout" via the paypal form button, though, I want to track an event in google analytics. i have found this article via google analytics http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html that explains how to track the custom event, but i don't know how to add it before the form is submitted such that the form submission is also not interrupted.
i imagine it's some basic javascript?
thanks!

A: You can either attach to button's click event or form's submit event. The latter is better, because submits may happen on hitting the ENTER key in a textbox as well. In which case a button click would not detect such a submit.
So button click:
$("buttonID").click(function(){...});

or form submit:
$("formID").submit(function(){...});

In your function you should do what's required by the analytics and submission will auto-continue afterwards (as long as there're no errors that would stop javascript execution).

A: You can add this to your form tag
<form onsubmit="return do_something()" >

Then write the do_something function and make it always return TRUE (as anything else will stop the form from submitting). You could also bind submit event to your form from the javascript using:
element.submit = do_something (note the fact that we're using a callback here
                               not the function itself)


text: Q: View both table and chart on Tableau on 1 screen IS there a way to view both table of data and it's chart in one place, i.e on one screen (instead of switching view via "show me" or using dashboard interactively) on Tableau?


text:
Q: Hide database from a role in Snowflake I tried REVOKE ALL ON DATABASE ABC FROM ROLE XYZ under ACCOUNTADMIN and got a success message.
When I switch to role XYZ I still see the ABC database but it appears empty. The database is also still in the list when running show databases under this role.
How do I make it so that this role cannot see the database at all?
By the way, this issue prevents our Mode connection to Snowflake from listing the available tables in the UI.

A: Create two databases : db1 and db2, for example, using the ACCOUNTADMIN role:
create database db1;
create database db2;
Then create two roles,one for database db1 and another for database db2
create role db1;
create role db2;
Now, grant usage on database db1 to role db1, similarly with role db2.
grant usage on database db1 to role db1;
grant usage on database db2 to role db2;
When you switch to role db2, you wont see db1 database and vice versa.
Also, when you run :
show databases;
say, while you set your role to db1,
you will not see database db2 in the result.
Hope this helps.

A: In my case, I also had usage monitoring and thus had to do revoke MONITOR USAGE on account from role XYZ. I suspect this is a very corner case not affecting many people. :(


text:
Q: How to show that it holds $|z|<2\max_{0\le kLet $z\in\mathbb{C}$ be a root of the complex polynomial $$f=X^n+\sum_{k=0}^{n-1}a_kX^k$$
I want to show that it holds $$|z|<2\max_{0\le k<n}|a_k|^{\frac{1}{n-k}}$$
Proof: For $s>1$, consider $$f_s:=\frac{1}{s^n}f(sX)=X^n+\sum_{k=0}^{n-1}\frac{a_k}{s^{n-k}}X^k$$ Evaluation of $f_s$ at $z$ yields
\begin{equation}
\begin{split}
f_s(z) &= \sum_{k=0}^{n-1}\frac{a_k}{s^{n-k}}z^k-\sum_{k=0}^{n-1}a_kz^k \\
&=\sum_{k=0}^{n-1}\left(\frac{1}{s^{n-k}}-1\right)a_kz^k
\end{split}
\end{equation}
Since $\sqrt[n-k]{2}\in (1,2]$ and $s>1$ it holds $$\frac{1}{\sqrt[n-k]{2}}<s\;\;\;\Leftrightarrow\;\;\;\frac{1}{2}<s^{n-k}\;\;\;\Leftrightarrow\;\;\;\frac{1}{s^{n-k}}-1<1$$
Thus,
\begin{equation}
\begin{split}
|f_s(z)| &\le \sum_{k=0}^{n-1}\left|\frac{1}{s^{n-k}}-1\right||a_k||z|^k \\
&\le \sum_{k=0}^{n-1}|a_k||z|^k \\
&< \sum_{k=0}^{n-1}|a_k|M^k
\end{split}
\end{equation}
where $$M:=1+\max_{0\le k<n}|a_k|$$ is an upper bound for the length of any root of $f$ by Cauchy's theorem. Now there comes the point where I'm unsure how I should proceed. I would be really thankful if someone could help me out.

A: By the triangle inequality we have
$$
|f(z)| \geq |z|^n - \sum_{k=0}^{n-1} |a_k| |z|^k,
$$
so if $z$ is a root of $f$ then $|z| \leq r$, where $r$ is the unique positive root of the equation
$$
x^n - \sum_{k=0}^{n-1} |a_k| x^k = 0.
$$
(Note that Descartes' rule of signs implies that the equation does indeed have a unique positive root.)  Let
$$
M := 2 \max_{0 \le k < n} |a_k|^{1/(n-k)}.
$$
For all $k$ we have
$$
2^{n-k} |a_k| \leq M^{n-k},
$$
so
$$
\sum_{k=0}^{n-1} |a_k| M^k \leq M^n \sum_{k=0}^{n-1} 2^{k-n} = M^n (1-2^{-n}) < M^n.
$$
Thus $M > r$, from which the result follows.


text:
Q: Highchart - how to control gap between series In Highcharts, how do I control the gaps between categories?
I've highlighted the area I am talking about in blue below:

I want to make my highchart chart gaps look like this powerpoint version on the left below. The bars in PowerPoint go all the way to the end of the plot area, but highcharts have this big gap.

https://jsfiddle.net/15u0r64s/
    Highcharts.chart('container', {
        chart: {
            type: 'bar'
        },
        title: {
            text: 'Historic World Population by Region'
        },
        subtitle: {
            text: 'Source: Wikipedia.org'
        },
        xAxis: {
            categories: ['Total', 'Male', 'Female', 'Other'],
            title: {
                text: null
            }
        },
        yAxis: {
            min: 0,
            title: {
                text: 'Population (millions)',
                align: 'high'
            },
            labels: {
                overflow: 'justify'
            }
        },
        tooltip: {
            valueSuffix: ' millions'
        },
        plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true
                }
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            x: -40,
            y: 80,
            floating: true,
            borderWidth: 1,
            backgroundColor:
                Highcharts.defaultOptions.legend.backgroundColor || '#FFFFFF',
            shadow: true
        },
        credits: {
            enabled: false
        },
        series: [{
            name: 'Total',
            data: [10, 20, 31, '']
        }, {
            name: 'Male',
            data: [10, 20, 60, 2]
        }, {
            name: 'Female',
            data: [10, 20, 61, '']
        }, {
            name: 'Other',
            data: [10, 20, 65, 4]
        }]
    });

A: You need to edit groupPadding and pointPadding properties:
plotOptions: {
  bar: {
    groupPadding: 0.05,
    pointPadding: 0
  }
}

Live demo: https://jsfiddle.net/BlackLabel/oqpxmL18/
API Reference:
https://api.highcharts.com/highcharts/series.bar.groupPadding
https://api.highcharts.com/highcharts/series.bar.pointPadding


text:
Q: Why does a ValidationError 422 occur when sending a POST request to a FastAPI app through Postman? I cannot seem to send a POST request to a FastAPI app through Postman.

*

*FastAPI version 0.89.1

*Python version 3.10.9

from fastapi import FastAPI
from fastapi.params import Body
from pydantic import BaseModel

app = FastAPI()

class Post(BaseModel):
    title : str
    content : str

@app.get("/")
async def root():
    return {"message": "Hello."}

@app.post("/createposts/")
def create_posts(new_post:Post):
    print(new_post.title)
    return  {"new_post":f"title:"[new_post.title]}

I got the following error
INFO:     Finished server process [44982]
INFO:     Started server process [45121]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     127.0.0.1:64722 - "POST /createposts/ HTTP/1.1" 422 Unprocessable Entity

I'm following a tutorial and I cannot seem to find answers from other users.
I tried using the dict: Body(...) input argument instead.
I am also using Postman and this is the error:
{
    "detail": [
        {
            "loc": [
                "body"
            ],
            "msg": "value is not a valid dict",
            "type": "type_error.dict"
        }
    ]
}

Here's a screenshot of my request on Postman.

I made a POST request to the URL with the POST endpoint:
{
 "title":"a",
 "content":"b"
}

A: In Postman, you need to set the Body to be of type JSON.
In your screenshot, you have it set to Text:

It should be set to JSON:

And it should work as expectedNote 1, as shown in the screenshot.
As MatsLindh said in the comments, you can open the panel for the Code Snippet section to check how exactly Postman converts your request:

It should show
--header 'Content-Type: application/json'

for JSON. You probably have it as
--header 'Content-Type: text/plain'

for text, which FastAPI cannot parse properly.

Note 1
It's unrelated to the validation error, but you have a typo in the f-string on your endpoint. The closing double-quote on the value is misplaced.
This:
return  {"new_post":f"title:"[new_post.title]}

should be:
return  {"new_post": f"title:[{new_post.title}]"}


text:
Q: Save image in database using file path vb10 I am doing a program which save and retrieve image from database.. I was instructed to used varchar as data type of the IMAGE field and we need to use file path for saving and retrieving image.. I am done retrieving the image but i am still working on saving it..
can someone help me in saving the image using the file path..
here is my code in retrieving image:
Dim pathpic As String

   pathpic = TextBox5.Text

   PictureBox1.Image = Image.FromFile(pathpic)
   PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage

A: There are basically 2 ways to save images.
1) Store the Path Location of the image into the database and save the actual picture into a folder.
2) Convert the actual image into binary form and save it into the database. Retrieving the image from the databases requires you to convert binary data back into the image file so it can be viewed.

You just can't save the actual image directly into the database. Method 1) is better as it's faster.
This website should get you started for method 2)
http://www.dreamincode.net/forums/topic/182113-converting-imagelist-picture-to-binary-data/


text:
Q: I want to change direction of Swiper to vertical. I added a direction prop to Swiper but it didn't work. What am I doing wrong? I'm using style-components for css and using NextJS for SSR(also using NextJS Image component) and I have a component to slide images like that:
const CustomImageSlider = () => {
  return (
    <CustomImageSliderContainer>
      <SwiperWrapper className="swiper-container">
        <Swiper
          modules={[Navigation]}
          navigation
          effect="slide"
          speed={300}
          slidesPerView={9}
          spaceBetween={8}
          loop
          preloadImages={true}
          direction="vertical"
          className="swiper">
          {mockData.map((image: any, index: any) => (
            <SwiperSlide key={index}>
              <Image
                alt=""
                src={image}
                width="50px"
                height="76px"
                key={index}
              />
            </SwiperSlide>
          ))}
        </Swiper>
      </SwiperWrapper>
    </CustomImageSliderContainer>
  );
};


text:
Q: Check if Report is fully formatted We have Order DB in Access where we collect and send Order confirmation to Clients. In Order Form I click button to open Confirmation Report in Normal view. I have "Send Report" button on opened report to send it to Client in PDF format.
All works grate with small reports. Problem arrise when report has 15-20 or more pages. After some investigation I found out that at time of report load user press Send button and report simply not being fully formated and sending action just fails.
I cannot find correct event to check if report is finished formatting. It would help me to make Send button enabled true/false based on that status.

A: May be you can use 'OnPrint' event of the report footer's section: "event occurs after data in a report section is formatted for printing, but before the section is printed"

A: I solved it at last.

*

*switched on docmd.Hourglass before button which opens the Report (button is located on Order Form) and switched off docmd.Hourglass on exit sub.

*in OnClick event of "Send" button at the top did the check for MousePointer
If Screen.MousePointer = 11 Then Exit Sub
Now User is not able to start sending until all process of button on Order Form is finished. That is actualy strange but somehow it solved the issue. Thank you all for help!


text:
Q: Is it possible to build a WSO2 distribution with ESB and api gateway? I want to deploy only one carbon product (one JVM) containing the ESB component and the api gateway component.
Is it possible to build this kind of application ? Is there any reference documentation explaining how to do that ?
Thanks.

A: Every Carbon-based product comprise of a set of installable/uninstallable features. You can get an ESB pack and install API manager features on it (can do this via the management console UI). However you won't be able to put together mismatching versions of the features (features released for different carbon platform versions/components) so this is subject to availability of matching components. This documentation on feature management will give you some insights on how to do it. (There can be cases where components may be in total conflict though)
But if your requirement is just running two products on the same machine, you can consider running them with port offsets, which is easier.


text:
Q: How do I get the local port my WCF service runs on? I'm using multiple self-hosted WCF services on the same machine. I need to open each of them on a different port (obviously), so I used "net:tcp://localhost:0" as address since I figured it would assign a free port this way.
Now I need to know which port was assigned actually. This code runs on the server, so I need the local port. How do I do that?

A: You can use OperationContext.Channel.LocalAddress.Uri.Port to know the port used in the call to a service

A: Then you need another place to store all service's ports to read them from outside the server. If it's another service, then it needs a constant port. It also can be a xml file over http or something modified on each of service's startup.
More on WCF Discovery

A: Found something that works, even though it is a bit dirty. Instead of automatically assigning a port, a free port is explicitly requested and used to create the service:
Address = "net.tcp://localhost:" + FindFreeTcpPort ();

private static int FindFreeTcpPort ()
{
    TcpListener l = new TcpListener (IPAddress.Parse ("127.0.0.1"), 0);
    l.Start ();
    int port = ((IPEndPoint) l.LocalEndpoint).Port;
    l.Stop ();
    return port;
}

(the method code is from here)


text:
Q: Apache AddType directive for .js files does not work I run YSlow in a couple of sites of mine and it reports that one .js file is not compressed. mod_deflate is enabled of course (other html and text files are compressed):
AddOutputFilterByType DEFLATE text/html text/plain text/css text/xml application/javascript application/ecmascript text/javascript text/x-javascript
DeflateCompressionLevel 6
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png)$ no-gzip dont-vary

# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary

I used Firebug to see the html headers sent by Apache when directly requesting this .js file and it seems that Apache does not send any Content-type header directive. I suppose this is the reason it does not go through the deflate filter for compression. Then, I added
AddType application/javascript .js

in the corresponding config file in Apache, restarted it and it still does not work. No Content-Type header is sent when requesting the file.
Apache runs in Linux, with PHP enabled (if this helps). mod_mime module is also enabled.

A: Apparently, the file was served from the browser's cache, I did not see the 304 status response in the Firebug window. After emptying the cache, the js file was indeed returned with the application/javascript content type and was gzipped.


text:
Q: Why OS with deadlock are not that good? I started learning OS and understanding it's concept but can somebody explain as to why is it bad for an operating system to have a deadlock system?

A: According to what I gathered it's not bad for a system to have a deadlock prevention system, but if an OS has a deadlock prevention system then it may slow down the system as whenever a process or thread will request for a resource then first the system will check if there's any possibility to have a deadlock situation and also such system might be expensive. So, that's why most systems ignore deadlock.


text:
Q: How do I use "series"? All of the examples I found either used the word with an article (That's the series you talked about?) or with an adjective (a comedy series, TV series).

*

*Can I say "What series do you watch?" instead of "What TV series do you watch?"

*Do English speakers usually understand TV series to be any show, not just one made for the literal television?

A: This is tricky, because "TV series" means different things in different countries.
In the USA, it refers to every episode of a given show.  But in other countries, it refers to the year of a show.  Example:
USA:
"I am watching season two of the show Seinfeld."
Others:
"I am watching series two of the show Seinfeld."
Your best option in the different situations is to phrase it as, "What TV shows do you watch?"  Or in the USA you can just say, "What shows do you watch," and TV will be assumed.


text:
Q: Spring Sleuth and Zipkin:Could not find artifact io.zipkin.brave:brave-bom:pom:4.16.3-SNAPSHOT I have a Spring Boot 2.0.0 REST service where I'm trying to enable Sleuth and Zipkin to send traces to my localhost Zipkin server.
The app worked fine unti I add the two dependencies spring-cloud-starter-sleuth and spring-cloud-sleuth-zipkin to my pom.xml. Once I did that, I'm now getting a compilation error:

Project build error: Non-resolvable import POM: Could not find artifact io.zipkin.brave:brave-bom:pom:4.16.3-SNAPSHOT

I've ensured it's not a corrupt Maven package issue by deleting my .m2 folder and updating (twice).
Why am I getting this error and how can I fix it?
This is my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.urig</groupId>
    <artifactId>inventory</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>inventory</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.M8</spring-cloud.version>
        <sleuth.version>2.0.0.M8</sleuth.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
        </dependency>
        <!-- Sleuth automatically adds trace interceptors when in the classpath -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-sleuth</artifactId>
        </dependency>
        <!-- Sends trace data to zipkin over http (defaults to http://localhost:9411/api/v2/spans) -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-sleuth-zipkin</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-sleuth</artifactId>
                <version>${sleuth.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

A: This is really strange because you are using latest relase and in the GitHub spring-cloud-sleuth depends to <brave.version>4.17.2</brave.version>. And I think 4.16.3-SNAPSHOT version is not exists in the maven repo. (just checked 2.0.0.M8 depends to this version)
If you change to <sleuth.version>2.0.0.M7</sleuth.version> it does find the required dependencies.
https://github.com/spring-cloud/spring-cloud-sleuth/blob/master/pom.xml

A: The M8 for sleuth was broken. That issue will be fixed in M9.
You can use M8 but you have to explicitly change the brave version to some release one.


text:
Q: Reactjs rendeing of component after parse find query I am trying to do is when the page is being loaded it should bring all the data from the parse.com database and display it on the page and I want to render my component after my find request is done.
Below you can see my code
var Ap = React.createClass({

    render: function(){
      Parse.initialize("mSWrLtmIHQdh8CNGk14fLbnK4gaVDbgvjw1zTeCT", "qKDkELvVpvgkuDDZzGK2pdP5o69LBDjWaRI2XfUb");
      var GameScore = Parse.Object.extend("TestObject");

      var query = new Parse.Query(GameScore);
      var x;
      query.find({
      success: function(results) {
          //debugger;
         var cells = [];
         for (var i in results) {
            cells.push(
"foo"	{i.attributes.foo}
);}
        return (

              {cells}

          )

      },

      error: function(error) {
        return(

)

      }
});
    }

  }
  );

  React.renderComponent(<Ap/>,  document.body);

</script>

But i get the error below because i am returning render inside the done method of my find query.

Uncaught Error: Invariant Violation: Ap.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.

Is there a way to wait for my find query to end before start rendering
and I'm also having another which I was not able to understand

Uncaught TypeError: Cannot read property 'foo' of undefined

Since I'm new to reactjs and parse so any help would be appreciated

A: *

*The problem is you returned undefined from your render(). Because after an ajax call there is no more code and render() had to return undefined that caused the error. You could put the query into componentDidMount() or some methods running earlier or some parent components/outer code and pass props to <Ap /> or set its state.

*{i.attributes.foo} may cause the Uncaught TypeError: Cannot read property 'foo' of undefined. Thus your i.attributes was undefined instead of some meaningful object such as results[i].attributes.

A: Perform a request in component's componentDidMount method and assign the results to component's state. This will cause component's rendering.
In render method read the data from the state.
var Ap = React.createClass({
    getInitialState: function(){
        return {
            data: []
        }
    },
    componentDidMount: function(){
        var that = this;
        Parse.initialize("mSWrLtmIHQdh8CNGk14fLbnK4gaVDbgvjw1zTeCT", "qKDkELvVpvgkuDDZzGK2pdP5o69LBDjWaRI2XfUb");
        var GameScore = Parse.Object.extend("TestObject");

        var query = new Parse.Query(GameScore);

        query.find({
            success: function(results) {
                that.setState({
                    data: results
                });
            },
            error: function(error) {
                that.setState({
                    data: []
                });

            }
        });
    },
    render: function(){
        var cells = [];
        for (var i in this.state.data) {
            cells.push(
"foo"	{this.state.data[i].attributes.foo}
);
        }
        return (

              {cells}

          )
    }
});

React.renderComponent(<Ap/>,  document.body);


text:
Q: Accessing Parent Class' Property From Derived Class I'm new to python and GAE and I thought python will act as any other OO language, but apparently not. How does __init__(self):  function gives me different results in the following code?
class BaseHandler(webapp.RequestHandler):
    @property
    def current_user(self):
        if not hasattr(self, "_current_user"):
            self._current_user = None
            cookie = facebook.get_user_from_cookie(self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
            user = User.get_by_key_name(cookie["uid"])

        return self._current_user

class SubmitHandler(BaseHandler):
    template_values = dict(facebook_app_id=FACEBOOK_APP_ID)

    def __init__(self):
        #throws error : AttributeError: 'SubmitHandler' object has no attribute 'request'
        self.template_values['current_user'] = self.current_user

    def get(self):
        #this one function is error free
        self.template_values['current_user'] = self.current_user

How do I access the class' parent property?

A: If you look at your SubmitHandler class you'll notice that it indeed does not have a request attribute -- at least, none you set, and none you give the parent class a chance to set. Perhaps what you need to do is call the parentclass __init__ method before you try to access self.current_user.
As a side note, you should realize that the template_values dict you define inside the SubmitHandler class there is a class attribute, and thus shared between all instances of the class. Since you assign it something instance-specific in your __init__, you probably mean for it to be an instance attribute instead. Assign it to self.template_values in your __init__ method.

A: There's nothing particularly different about Python's object inheritance.
By defining __init__, you have told Python that this is all that needs to be done to initialize the object. You're therefore denying it the chance to run the superclass's initialization code. You need to call super:
def __init__(self, *args, **kwargs):
    super(SubmitHandler, self).__init__(*args, **kwargs)
    self.template_values['current_user'] = self.current_user

This might however not solve your problem - you're failing to take into account the possibility that self.request is initialized at another point in the program, which is why it works by the time get is called.

A: self.request and self.response are not set by the class constructor in webapp. They're set later, when the framework calls the handler's initialize method. You can override this, just make sure you call the parent class's initialize before doing anything else.


text:
Q: Unity Shaderlab- transform from screen space to world space I'm making a post-processing shader (in unity) that requires world-space coordinates. I have access to the depth information of a certain pixel, as well as the onscreen location of that pixel. How can I find the world position that that pixel corresponds to, much like the function ViewportToWorldPos()?

A: It's been three years! I was working on this recently, and an older engineer help me solved the problem. Here is the code.

*

*We need to firstly give a camera transform matrix to the shader in script:
void OnRenderImage(RenderTexture src, RenderTexture dst)
{
    Camera curruntCamera = Camera.main;
    Matrix4x4 matrixCameraToWorld = currentCamera.cameraToWorldMatrix;
    Matrix4x4 matrixProjectionInverse = GL.GetGPUProjectionMatrix(currentCamera.projectionMatrix, false).inverse;
    Matrix4x4 matrixHClipToWorld = matrixCameraToWorld * matrixProjectionInverse;

    Shader.SetGlobalMatrix("_MatrixHClipToWorld", matrixHClipToWorld);
    Graphics.Blit(src, dst, _material);
}

*Then we need the depth information to transform the clip pos. Like this:
inline half3 TransformUVToWorldPos(half2 uv)
{
    half depth = tex2D(_CameraDepthTexture, uv).r;
    #ifndef SHADER_API_GLCORE
        half4 positionCS = half4(uv * 2 - 1, depth, 1) * LinearEyeDepth(depth);
    #else
        half4 positionCS = half4(uv * 2 - 1, depth * 2 - 1, 1) * LinearEyeDepth(depth);
    #endif
    return mul(_MatrixHClipToWorld, positionCS).xyz;
}

That's all.

A: have a look at this tutorial: http://flafla2.github.io/2016/10/01/raymarching.html
essentially:

*

*store one vector per corner of the screen, passed as constants, that goes from the camera position to said corner.

*interpolate the vectors based on the screen space position, or the uvs of your screenspace quad

*compute final position as cameraPosition + interpolatedVector * depth


text:
Q: Can I combine a release and debug build of a static library into one binary? I want to allow a third party to use our static library in debug mode with assertions while they are developing their app but I also want to allow them to use our static library in release mode so they don't have to submit their app to the App Store with assertions. Is there a way to do this without having two separate binaries or is there a best practice for this situation?

A: No, you can't. The reason is you would get duplicate symbols. A universal library is also no option, since the OS selects different binaries depending on the current architecture.
You can however build two libraries distinguished by name, e.g.:
libFoo.a and  libFoo_debug.a
and ship those two to your clients. Then, the client application will simply link against the respective library (per build settings in "Other Linker Flags") in the Debug and Release Configuration. This setup needs to be made just once.


text:
Q: Positioning QHBoxLayout vertically I am in the early stages of learning PYQT and have ran into of problem with creating a layout I have in mind.
I want to create a layout for a login screen which looks like the following:

*

*I have tried using a GridLayout to get the desired look

*Have also tried setting buddy to username/textfield and password/textfield then putting everything in a HBox then nesting it inside of a VBox which I thought would work but it didnt.

I have looked online and have found out about the use of relative layouts which I think might be the best way to achieve this layout but cant find out the syntax for it. ANy help would be appreciated
EDIT:
So, I have managed to get the desired layout by creating 3 HBoxes:

*

*one containing the username label and textfield

*A second to store the password label and textfield

*The third to store the push button.

I have then placed them all inside a VBoxLayout. Is this an okay way of achieving this or or there a better way of going about it?


text:
Q: Can I increase the gameplay speed? Is there any way to increase the speed of gameplay in Plants vs. Zombies? It's a great game, but it can get a bit slow.

A: Try Game Speed Adjuster.

A: There is one mini game that speeds the game up. It is called "Zombie Nimble Zombie Quick" but this is only for one level and there is no way to slow it down when needed, so you may get overwhelmed very easily. Otherwise, the answer is no.

A: The game offers no such option.

A: If using PC, install Cheat Engine and use its Speedhack feature.
If using rooted Android, use SB Game Hacker's speedhack feature.
If not rooted, install VMOS through their website, and enable the "virtual root" feature. That way, you don't have to root your actual phone. Then install SB Game Hacker.
If on iOS, can't help, sorry. You'd probably need to jailbreak.


text:
Q: Why does a new terminal get automatically closed? Every time I open a new terminal it gets automatically closed. I'm running Arch Linux, and Xforce4 terminal.
$ terminal --execute sudo arpspoof -i $(cat var.log|awk '{print $1}') \
           -t $(cat var.log|awk '{print $4}') $(cat var.log|awk '{print $3}')

or
# terminal --execute arpspoof -i $(cat var.log|awk '{print $1}') \
           -t $(cat var.log|awk '{print $4}') $(cat var.log|awk '{print $3}')

Error printed upon execution of either of the above commands:
Unable to register terminal service: Did not receive a reply. Possible causes
include: the remote application did not send a reply, the message bus security
policy blocked the reply, the reply timeout expired, or the network connection
was broken.

A: The "default" behavior for a terminal is to terminate when the program it has been instructed to run is finished. It does this because this is the most practical thing to do. If you wish to read the output before it disappears, consider adding a command at the end like so:
urxvt -e sh -c 'cowsay howdy?; sleep 1337'

Some terminals, such as rxvt-unicode have an option to hang around until closed by the window manager:
-hold|+hold
    Turn on/off hold window after exit support. If enabled, urxvt will
    not immediately destroy its window when the program executed within
    it exits.  Instead, it will wait till it is being killed or closed by
    the user; resource hold.


text:
Q: Order the rows by date AND maximum number of hours per day - groupby function in Python I have a below df.

Now I need to produce the below result that displays the number of rows in the order of the maximum number of hours groupby date.

SELECT column_name(s) FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

With the above SQL, this can be achieved. However, I would like to know how to write this code in python.


text:
Q: Vertical Table displaying a star relevant to the size of each int I am writing a program for my c++ course where I need to display a vertical table that holds a length depending on each array size. The array size changes every run since it is 100 randomly generated numbers categorized under five different ints.
Here are my ints:
        int sizeA=0, sizeB=0, sizeC=0, sizeD=0, sizeF=0, arraySize=100,
biggest=0, aB=0, cD=0;
        int grades[arraySize];
        std::vector<int> gradeA, gradeB, gradeC, gradeD, gradeF;

In my code, I took the 100 random numbers and sorted them into 5 new arrays using vectors; respectfully categorized as gradeA, gradeB, .. grade F;
I then used .size(); to get the size of each array and then found the biggest array size to use as my int biggest to declare the size of my table. Which is where I am stuck. I can't figure out how to display the columns and/or tables properly.
for(int row = biggest; row > 0; row--){
    for(int column = 0; column < 6; column++){
        cout << row << " ";
        if()
    } cout << endl;
}

My tables gotta look something like this, assuming sizeA = 3, sizeb=2, 3, 1, 2 respectfully:
3 *   *
2 * * *   *
1 * * * * *
  A B C D F

Any help will be much appreciated, thank you

A: if(gradeA.size() >= row)
   cout<<"* "; // One space at the end to separate from next star
else
   cout<<"  "; // Two spaces here to keep aligned your table

same with gradeB, gradeC...
EDIT: The columns loop then can be removed
for(int row = biggest; row > 0; row--)
{
    cout << row << " ";
    if(gradeA.size() >= row)
        cout<<"* "; // One space at the end to separate from next star
    else
        cout<<"  "; // Two spaces here to keep aligned your table
    if(gradeB.size() >= row)
        cout<<"* "; // One space at the end to separate from next star
    else
        cout<<"  "; // Two spaces here to keep aligned your table
    // Same for gradeC, D, E and F
    cout << endl;
}


text:
Q: Limit Shiny unbindAll and bindAll only to and HTML element In the Shiny site they say that before making changes to the DOM, that is to say, add or remove inputs and outpus, you need to tell Shiny by calling unbindAll and bindAll:
function modifyDom()
{
    Shiny.unbindAll()
    insertInputsAndOutputs()
    removeOtherInputsAndOutputs()
    Shiny.bindAll()
}

The thing is that my web app has 2 parts: a select on a sidebar and a main container that displays information depending on what the user chooses. And the problem is this:

*

*Suppose, User has already chosen item 1, so structure 1 is displayed on the container

*When user chooses item 2, structure 1 is deleted when modifyDom is called and the very last line Shiny.bindAll() causes that even the select of the sidebar to reinitialize, so it selects item 1 and the structre 1 is displayed again.

Therefore my question: Is there a way in Shiny not to unbind all objects but only the ones that exist within a certain HTML element.

A: I've never work with Shiny before, but according to this link and searching on its Github repo, both unbindall and bindall functions can be used in the following way too:
unbindall(element)
bindall(element)
Where element seems to be a DOM element (returned value from document.getElementById function or jQuery equivalent $('#element')[0]).
So you can write another function like this:
function modifyDomByElement (element) {
  Shiny.unbindAll(element);
  insertInputsAndOutputs();
  removeOtherInputsAndOutputs();
  Shiny.bindAll(element);
}

And preserve modifyDom function working as you post (don't forget Single responsibility principle).


text:
Q: The longest word in Weyl group and positive roots. How to write down a reduced decomposition of the longest word in a Weyl group? For example, how to write down a reduced decomposition of the longest word in type B3 Weyl group? For a decomposition of the longest word, how can we write down an ordering of positive roots? I am asking these questions because I am trying to understand Section 2.4 of http://arxiv.org/abs/math/0202148. Thank you very much.

A: Here's an algorithm for finding such a reduced word decomposition.

*

*Start with $w=e$ (=the empty word) and $\lambda=-\rho=-\sum_i\lambda_i$, where the $\lambda_i$ are the fundamental dominant weights determined by
$\langle \lambda_i,\check{\alpha_j}\rangle=\delta_{ij}$. Here $\alpha_1,\ldots,\alpha_n$ are simple positive roots.

*If there exists an index $i$ such that $\langle\lambda,\alpha_i\rangle <0$, let $i_0$ be one of those (for example the smallest index, so you don't need to check too many). If no such $i$ exists, then exit with output $w$.

*Replace $w$ with $s_{i_0}w$ and $\lambda$ with $s_{i_0}(\lambda)$. Go back to step 2.

Here initially $\lambda$ is in the negative of the dominant Weyl chamber. Each iteration brings it one simple reflection closer to the dominant chamber, and in the end it will reach it. The number of simple reflections will be equal to the number of positive roots, so you can use that as a stopping condition as well.

Let's do an example run with $B_3$. Here $\alpha_3$ is the short simple root.
$$
\begin{array}{c|l}
\lambda& w\\
\hline
(-1,-1,-1) &e\\
(1,-2,-1) &s_1\\
(-1,2,-5) &s_2s_1\\
(1,1,-5) &s_1s_2s_1\\
(1,-4,5) &s_3s_1s_2s_1\\
(-3,4,-3) &s_2s_3s_1s_2s_1\\
(3,1,-3) &s_1s_2s_3s_1s_2s_1\\
(3,-2,3) &s_3s_1s_2s_3s_1s_2s_1\\
(1,2,-1) &s_2s_3s_1s_2s_3s_1s_2s_1\\
(1,1,1) &s_3s_2s_3s_1s_2s_3s_1s_2s_1
\end{array}
$$
We knew in advance that the root system of type $B_3$ has nine positive roots, so predictably we get a weight in the fundamental Weyl chamber after nine simple reflections.
This presentation as a product of simple reflections is not unique (we could have used another simple reflection at multiple points). Undoubtedly you knew about that already.

I am not positive about the meaning of ordering of positive roots. I suspect (an educated guess based on the context) that it is the order in which the partial words building up the longest element map the positive roots to negative ones.  Let $w_i$ be the element of the Weyl group that is the product of $i$ first simple reflections in our decomposition of the longest element. To such an element of the Weyl group we can associate the set $\Phi_i$ of those positive roots $\beta$ such that $w_i(\beta)$ is a negative root.
It is known that $|\Phi_i|=i$. It is also known that if $w_{i+1}=s_{i+1}w_i$, then
$\Phi_i\subset \Phi_{i+1}$ and that the positive root in $\Phi_{i+1}$ "missing" from
$\Phi_i$ is then $\beta_{i+1}:=w_i^{-1}(\alpha_{i+1})$. Thus we get a vaguely natural ordering related to the decomposition: $\beta_1<\beta_2<\beta_3<\cdots$. With 2-dimensional
root systems you then get all the positive roots "in a rotational order" (which is why I am guessing that this is what it means). For example in type $A_2$ you get first one of the simple roots, then the highest root (=the one between the simple roots), and the other simple root is the last to join in.
I am not too confident about this, because it is also possible to use partial words clipped from the other end of the decomposition, and build a slightly different interpretation but analogous ordering. If the paper you cited has worked out examples, then it should be possible to reverse engineer this. I don't have the time to delve deeper into this today. Does this fit at all?


text:
Q: RegEx Starts withs / Ends With I'm trying to preg_match the "INCIDENT DETAILS" block and piecing different regex snippets isn't getting me anywhere. Thanks for any help.
>>ID Number: 0
>>
>>Employee Detail:
>>
>>Vehicle: 0    , #
>>
>>Incident Details: Sample incident details. It may span any number of lines
>>and is always followed by a newline with '>>'
>>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
>>Praesent vitae dignissim diam. Phasellus a vestibulum enim. Morbi dictum
>>
>>Comments: ADDITIONAL COMMENTS HERE
>>

A: (Incident\s*Details.*?)(?=>>\n)

Try this.Use flags g and s.See demo.
http://regex101.com/r/nA6hN9/37

A: One possible regex is:
/>>incident details:[\s\S]+?\n>>\n/i

This will match everything from ">>Incident Details" up to the next "blank" (save for the >>) line.
However I would probably prefer explodeing on newlines and scanning through them, building the blocks as I go. This would be a bit more complicated, but in theory more robust.

A: Might work -
 # '~(?sm-)^Incident Details:\K(?:(?!>>(?:\r?\n|$)).)*~'

 (?xsm-)
 ^ Incident\ Details: \K
 (?:
      (?!
           >>
           (?: \r? \n | $ )
      )
      .
 )*


text:
Q: Raw socket bind() in python 3.4.3 on Windows I'm having a bit of trouble with the following Python code:
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('icmp'))
s.bind((interface_ip_address, 0))

I'm trying to send an ICMP packet through a user selected interface, but I keep getting SocketError when using the bind() function. I have no idea what am I doing wrong. Thanks in advance.
Update:
When user selects loopback interface (interface_ip_address = 127.0.0.1) than
s.bind((interface_ip_address, 0))

works like a charm! But why does it raise SoccektError when user selects any of the reamining interfaces?


text:
Q: Java Swing JFrame disable mouse hovering for an overlay I am trying to make an overlay for csgo using swing(JFrame)
I've accomplished everything I need for it but there is 1 small bug I can't fix. I've looked everywhere on how to fix it and I can't figure it out!
Whenever I hover my mouse over anything that is being rendered it will give my mouse "focus" and tab me out of the game!
package com.rigadrinksbleach.csgo.external.overlay;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

import com.rigadrinksbleach.csgo.external.Start;
import com.rigadrinksbleach.csgo.external.hack.Hack;

public class ExternalOverlay extends JFrame {

public ExternalOverlay() {
    super("Overlay");
    this.setUndecorated(true);
    this.setBackground(new Color(0, 0, 0, 0));
    this.setBounds(0, 0, 1920, 1080);
    this.setAlwaysOnTop(true);
    this.getContentPane().setLayout(new java.awt.FlowLayout());
    this.setVisible(true);
}

public void loop() {
    this.repaint();
}

public void draw(Graphics g) {
    for(Hack hack : Start.getHacks().getHacks()) {
        hack.draw2d(g);
    }
}

@Override
public void paint(Graphics g) {
    super.paint(g);
    //g.setColor(new Color(255, 0, 0));
    //g.drawRect(0, 0, this.getBounds().width - 1 - this.getBounds().x, this.getBounds().height - 1 - this.getBounds().y); //debug border
    this.draw(g);
}

}

Any help would be appreciated.

A: I know a fix for this.
Just change setVisible to False.


text:
Q: How to extend winforms tooltip text width size? private void toolTip1_Popup(object sender, PopupEventArgs e)
        {
            if (e.ToolTipSize.Width > 10)
            {
                Size s = TextRenderer.MeasureText(toolTip1.GetToolTip((sender as System.Windows.Forms.ToolTip).Tag as Control), SystemFonts.SmallCaptionFont);
                e.ToolTipSize = new Size(4560, s.Height);
            }
        }

I tried 4560 just for testing because with 456 width it didn't change anything i still need many time to add \n or to add environment.newline.
I changed the ownerdraw to true.
I also use the draw event :
private void toolTip1_Draw(object sender, DrawToolTipEventArgs e)
        {
            using (StringFormat sf = new StringFormat())
            {
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
                sf.FormatFlags = StringFormatFlags.NoWrap;
                using (Font f = new Font("Tahoma", 10))
                {
                    e.Graphics.Clear(BackColor);
                    e.Graphics.DrawString(e.ToolTipText, f,
                        SystemBrushes.ActiveCaptionText, e.Bounds, sf);
                }
            }
        }


text:
Q: Android ConnectivityManager is not seeing permission ACCESS_NETWORK_STATE I have simple code that wants to read the state of network connection. I've added permission to the AndroidManifest.xml:
<user-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

My code that tries to access network state:
    ConnectivityManager conmgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ninfo = conmgr.getActiveNetworkInfo();

And the error that is thrown:
 E/AndroidRuntime(7650): java.lang.SecurityException: ConnectivityService: Neither user 10080 nor current process has android.permission.ACCESS_NETWORK_STATE.

I've long tried to find any error, but everything seems to be spelled correctly. It seems like the new version of AndroidManifest is not deployed to device. I've tried to clean project in Eclipse, uninstall app from phone, but nothing is working, I get the same communicate again. What I'm doing wrong?

A: I think it is
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

instead of
<user-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

A: Delete the imports of all kinds that has to do with NetworkInfo like Java.net packages or any other.. Re-import


text:
Q: How to format only certain cells using vba? I want to change the background color for columns A and B starting from Row 4 and upto the row that contains data. The following code doesn't seem to work. Please review.
Sub GeneralColorForAllPopulatedCells()

Dim wb As Workbook
Dim ws As Worksheet
Dim g As Long, h As Long
Dim lastRow As Long
Dim rng As Range

Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")

g = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
h = ws.Range("B" & ws.Rows.Count).End(xlUp).Row

If g > h Then
    lastRow = g
Else
    lastRow = h
End If

Set rng = ws.Range("A4:B" & lastRow)
rng.Interior.Color = RGB(204, 229, 255)

End Sub

Thanks,
Hema


text:
Q: RegisterPerWebRequest is obsolete, can I use Lifestyle.Scoped? I am just checking for my sanity. This is my code that uses simpleinjector 3.3.2
Container.RegisterPerWebRequest<HttpContextBase>(() =>
{
  var context = HttpContext.Current;
  if (context == null && Container.IsVerifying) return new FakeHttpContext();
    return new HttpContextWrapper(context);
});

Container.Verify();

...
    public class FakeHttpContext : HttpContextBase { }

However the RegisterPerWebRequest is now marked as obsolete, I am not 100% sure whether this is the correct way of changing the code to reflect the new code base.
Container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

//So we can inject HttpContextBase into any class
Container.Register<HttpContextBase>( () =>
{
  var context = HttpContext.Current;
  if (context == null && Container.IsVerifying)
    return new FakeHttpContext();

  return new HttpContextWrapper(context);
}, Lifestyle.Scoped);

so my question is "Should I use Lifestyle.Scoped to replace RegisterPerWebRequest and can I still use the code as is?

Judging by the docs I should be doing it right

A: The code you shown is correct. Container.Register<T>(Func<T>, Lifestyle.Scoped) replaces Container.RegisterPerWebRequest<T>(Func<T>).


text:
Q: Origin of "Everybody is smarter than anybody"? Who said this:

Everybody is smarter than anybody.

I have been trying to find the origin of this phrase with no success. I think I first heard it from a speaker on an IT subject (but I am not sure if its origin is from a person with a technology background).
I would like to use this quote but won't use it if I can't give a proper attribution.

A: This dates back to at least 1949, where it is referenced in these conference proceedings with attribution to Carl Sandburg (1878 – 1967):

I've also heard it as "all of us are better than one of us", which dates at from the late nineties.

Edit: Carl Sandburg's original line is "Everybody is cleverer than anybody", published in 1936's The People, Yes. (You can read a bit more of it in this book.)

Edit 2: And "everybody is cleverer than anybody" goes to back 1877, where it is referenced by several Westminster publications as an "epigram of Talleyrand" or "Talleyrand's famous sentence". This is the French diplomat Charles Maurice de Talleyrand-Périgord (1754 – 1838). I've not found the original French, but it has also been translated as:

"There is one body that knows more than anybody, and that is everybody"


text:
Q: FusionAuth email subject not supporting special language characters Is there any way to pass special language characters such as 'ąęćń' in the subject of an email template in fusionauth ?

A: The solution is to encode the string subject as MIME header using javax.mail.internet.MimeUtility
MimeUtility.encodeText(subject, "utf-8", "B")


text:
Q: Scrapy startproject not working with git-bash I'm working on win7 on a system with git-bash. I've installed Miniconda and loaded scrapy using:
conda install -c scrapinghub scrapy

I've set the environmental variables to contain:
C:\Miniconda2;C:\Miniconda2\Scripts

Now within the scrapy vitualenv, when I do :
(scrapy)
$ scrapy startproject scrapytest
sh: scrapy: command not found

How do I use the scrapy command line tool here?

A: I don't know how git-bash has effect on this, but installing scrapy registers one entry point, a console script, calling scrapy.cmdline:execute. See this page for more info on entry points.
You can invoke the same using the python interpreter with -m like this:
python -m scrapy.cmdline startproject scrapytest

A: There seemed to be a problem with using the anaconda install command above. I created a new virtualenv using python 2.7.11 and installed scrapy using pip and it worked. Part of the problem earlier may have been that pip was not updated to the latest version , so do this first. here is a list of packages I ended up installing in my virtual env:
$ pip list
attrs (15.2.0)
backports-abc (0.4)
backports.shutil-get-terminal-size (1.0.0)
backports.ssl-match-hostname (3.5.0.1)
certifi (2016.2.28)
cffi (1.6.0)
configparser (3.5.0)
cryptography (1.3.2)
cssselect (0.9.1)
decorator (4.0.9)
entrypoints (0.2.2)
enum34 (1.1.6)
functools32 (3.2.3.post2)
idna (2.1)
ipaddress (1.0.16)
ipykernel (4.3.1)
ipython (4.2.0)
ipython-genutils (0.1.0)
ipywidgets (5.1.4)
Jinja2 (2.8)
jsonschema (2.5.1)
jupyter (1.0.0)
jupyter-client (4.2.2)
jupyter-console (4.1.1)
jupyter-core (4.1.0)
lxml (3.6.0)
MarkupSafe (0.23)
mistune (0.7.2)
nbconvert (4.2.0)
nbformat (4.0.1)
notebook (4.2.0)
parsel (1.0.2)
pathlib2 (2.1.0)
pickleshare (0.7.2)
pip (8.1.2)
psycopg2 (2.6.1)
ptyprocess (0.5.1)
pyasn1 (0.1.9)
pyasn1-modules (0.0.8)
pycparser (2.14)
PyDispatcher (2.0.5)
Pygments (2.1.3)
pyOpenSSL (16.0.0)
pyreadline (2.1)
pywin32 (220)
pyzmq (15.2.0)
qtconsole (4.2.1)
queuelib (1.4.2)
Scrapy (1.1.0)
service-identity (16.0.0)
setuptools (21.1.0)
simplegeneric (0.8.1)
singledispatch (3.4.0.3)
six (1.10.0)
SQLAlchemy (1.0.13)
terminado (0.6)
tornado (4.3)
traitlets (4.2.1)
Twisted (16.2.0)
w3lib (1.14.2)
widgetsnbextension (1.2.2)
zope.interface (4.1.3)


text:
Q: Include raw tab literal character in doctest I can't figure out how to avoid this doctest error:
Failed example:
    print(test())
Expected:
        output
    <BLANKLINE>
Got:
        output
    <BLANKLINE>

For this code
def test():
    r'''Produce string according to specification.

    >>> print(test())
        output
    <BLANKLINE>
    '''
    return '\toutput\n'

I have put a tab literal into the source code, line 5 in front of output.
It looks like doctest (or python docstrings?) ignores that tab literal and converts it to four spaces.
The so-called "Expected" value is literally not what my source specifies it to be.
What's a solution for this?
I don't want to replace the print statement with
>>> test()
'\toutput\n'

Because a huge part of why I usually like doctests is because they demonstrate examples, and the most important part of this function I am writing is the shape  of the output.

A: The tabs in the docstring get expanded to 8 spaces, but the tabs in the output are not expanded.
From the doctest documentation (emphasis added):

All hard tab characters are expanded to spaces, using 8-column tab stops. Tabs in output generated by the tested code are not modified. Because any hard tabs in the sample output are expanded, this means that if the code output includes hard tabs, the only way the doctest can pass is if the NORMALIZE_WHITESPACE option or directive is in effect. Alternatively, the test can be rewritten to capture the output and compare it to an expected value as part of the test. This handling of tabs in the source was arrived at through trial and error, and has proven to be the least error prone way of handling them. It is possible to use a different algorithm for handling tabs by writing a custom DocTestParser class.

Unfortunately, all examples of directive use in the doctest docs have been mangled by Sphinx. Here's how you would use NORMALIZE_WHITESPACE:
def test():
    r'''Produce string according to specification.

    >>> print(test()) # doctest: +NORMALIZE_WHITESPACE
        output
    <BLANKLINE>
    '''
    return '\toutput\n'

Note that this treats all runs of whitespace as equal, rather than disabling the tab processing. Disabling the tab processing is absurdly cumbersome, and it's impossible through the usual doctest interface - you would need to subclass DocTestParser, manually reimplement doctest parsing, then construct instances of DocTestFinder, DocTestRunner, and your DocTestParser subclass and call their methods manually.


text:
Q: How to get the value of an expression I have this function that uses Linq expressions:
private Expression GetFieldValueExpression(ParameterExpression parameter, string fieldName)
{
  Expression properyIndexExpression = System.Linq.Expressions.Expression.Constant (fieldName, typeof(string));
  IndexExpression fieldValueExpression = System.Linq.Expressions.Expression.Property(parameter, "Item", new Expression[] { properyIndexExpression });
  return Expression.Property(fieldValueExpression, "Value");
}

The value returned by Expression.Property(fieldValueExpression, "Value") is of type string.
I don't know how to get it. I know that i must create a lambda and compile it, but i don't know how.
Thank you for your time.

A: Perhaps you are looking for code like this:
    public void EvaluateAnExpression()
    {
        //Make the parameter
        var parm = Expression.Parameter(typeof(TestClass),"parm");

        //Use your method to build the expression
        var exp = GetFieldValueExpression(parm, "testField");

        //Build a lambda for the expression
        var lambda = Expression.Lambda(exp, parm);

        //Compile the lamda and cast the result to a Func<>
        var compiled = (Func<TestClass, string>)lambda.Compile();

        //We'll make up some object to test on
        var obj = new TestClass();

        //Get the result (it will be TESTFIELD)
        var result = compiled(obj);
    }

that code assumes some test classes that look like this (basically the indexer property just returns the input but in upper case - a trivial example but works for testing):
    public class TestClass
    {
        public InnerClass this[string indexParameter]
        {
            get
            {
                return new InnerClass { Value = indexParameter.ToUpper() };
            }
        }
    }

    public class InnerClass
    {
        public string Value { get; set; }
    }


text:
Q: How does an SSH connection become inactive? I have setup an SSH connection to run a program on a remote server. The program prints debug information on the terminal every 10 seconds. If I leave the SSH windows open for a long time (say 10 hours), does the SSH connection become inactive? How is activity defined in an SSH session? Should I type/run command every x seconds to keep the session alive?

A: You should not have to do anything special, SSH does not terminate a connection because of inactivity. So there is no inactivity period defined within SSH.
However one of the devices on the network route between you and your server might lose the route and for that activity from one side usually is enough, but not always (there are "arrival confirmation packages", acknowledgements, going back to the server from the client when using TCP).
Traffic from both sides is no guarantee for continued connectivity, if you have a DSL modem and your provider decides that you get a new IP address every day, the connection will be broken.
You can have your client sent some packets on a regular basis by inserting
ServerAliveInterval 5

in /etc/ssh/ssh_config or your ~/.ssh/config to have some client to server traffic every 5 seconds in addition to the traffic coming from the server every 10 seconds.
The simpler "solution" to DSL modem resetting a connection is running your server side software in tmux or screen: if the connection is broken, you just SSH into the server again, issue tmux attach or screen -r and you can continue to view the uninterrupted server program.
Using tmux/screen is especially useful if you are not so much worried about losing the connection, but of the consequence that the server program stops if you do. For that you can also redirect the output of the original program to file and use tail -f, but that doesn't allow you to easily interact with the server program (if that would be necessary). tmux and screen (in their basic forms) are easy to use, but there are some side-effects like not being able to scroll back using the sliders on your graphical terminal (you have to use keyboard shortcuts to have the server scroll back in its buffer for that).
A more flexible solution around devices breaking your connection is to use mosh. This uses SSH to exchange some secret info and then allows for reattachment even if one or both of the IP addresses changes. This is however more difficult to set up and get to work.
In your case I would start with using tmux and manually reattach when the connection indeed deactivates.

A: also, really helpful to use SCREEN command. With that you can run any command and don't worry about your ssh connection.


text:
Q: VS Code flags System.out.print I'm a beginner programmer and It bothers me - why VS Code continues to flag my System.out.print statements and suggests using logger when in most places and tutorials they tell you to use out.print as a basic output stream?
Problem with System
out problem

A: You can surely use System.out although a logger has so much more capabilities and is therefore better for a bigger project. If you just plan to make some small things, you don't need to use a logger if you don't want to, otherwise I'd highly recommend using one


text:
Q: show footer row by default though no records in the grid view in asp.net all. May this question again added here , so please forgive me . i wanted to express the scenario.
well!
I have an asp.net web application that having the grid view control binding with database to show the records. but. as usual by nature of the grid view control , if there is no records in the database / table then i would show me blank grid. where as i facilitate to user,m he can add, edit,update the record through this grid view. I placed all the text boxes in footer row. but since no records in table it rendering blank grid.
where as i am giving as datasource to grod view is List of users (List<User>).
I want to show this footer row , though there is no records in the database.

A: You can do one thing. as you said you are using here List
then in the function where you are filling the grid check that is your List having any object ? by its count property. if there is zero count the add a object in list. but extend this object with some property with some default value which does not belong from database but belongs from application level. now in your row data bound command check certain constraints against this extended property for current row object.also check type of the row. except footer make visible false the row which satisfy the condition.  thats all you will get only footer row there though your database is empty.
And if you are using the datatable as datasource then add a blank datarow in your datatable. but keep certain constraint to check this is blank row.

A: Here you can read how you can subclass GridView to add the functionality you need: http://mattberseth.com/blog/2007/07/how_to_show_header_and_footer.html


text:
Q: Returning a value to a text box with JavaScript I need to add a time stamp to a text box triggered by and event. The text box also has a date picker. The JavaScripts are,
$(function() {
    $( "#CCEDate" ).datepicker();
});

And
function GetCCEDate() {
    $.get('timestamp.php', {},
        function (output) {
            $('#CCEDate').html(output).show();
        }
    );
}

The html is:
<input name="CCEngaged" id="CCEDate" type="text" style="width: 180px">

Or
<textarea name="CCEngaged" id="CCEDate" style="overflow: hidden; width: 200px;" rows="1"></textarea>

If I use a simple text box, the datepicker works but the GetCCEDate does not.  However, if I use a text area, the GetCCEDate inserts the time stamp fine but the datepicker does not work on a text area.
What I would like to do is use a simple text box and insert the timestamp.

A: Use .val() for input elements:
$('#CCEDate').val(output)


text:
Q: Process listening which Port on Windows How can you find out which process is listening upon which port on Windows and Linux?
Are there some Applications explicitly monitoring?

A: Some great tools for this are made by Sysinternals, now owned by Microsoft.
The one you want is Tcpview and it will show you the ports and which application has them opened, as well as the PID and other nice things. Tcpview is windows based but they have a command line version as well. All these tools are free.
This is the link Microsoft's sysinternals downloads

A: Both Windows and Linux has the netstat-command built-in, although they are used differently.
On Windows: netstat -a -b (lists both listening and connected ports)
On Linux: netstat -l -p (lists only listening ports)

A: Not sure that stackoverflow is the right place for this question, maybe http://www.superuser.com would be a better choice.
Although from the top of my head:

*

*Linux has lsof and netstat commands that will provide this information.

*Windows has ProcessExplorer that should give this information.

A: In Linux you can use the ss command to dump the socket information. It gives information about active port numbers in the client side also. More details can be found here
http://linux.die.net/man/8/ss

A: On windows 7, you can use
netstat -b -a

netstat /?

-b      Displays the executable involved in creating each connection or
          listening port. In some cases well-known executables host
          multiple independent components, and in these cases the
          sequence of components involved in creating the connection
          or listening port is displayed. In this case the executable
          name is in [] at the bottom, on top is the component it called,
          and so forth until TCP/IP was reached. Note that this option
          can be time-consuming and will fail unless you have sufficient
          permissions.
-o      Displays the owning process ID associated with each connection.

On Linux use, -p needs root privileges.
#netstat -p

#netstat -h
-p, --programs           display PID/Program name for sockets


text:
Q: How can I remove white spaces in a psql insert? I have a text input:
<label for="pt"><b style="color:white"> Company name </b></label>
        <input type="text" name="company" maxlength="100" required>

And I want to insert into a psql database:
$comp= $_POST["company"];
$comptr = trim($comp);

When I have inserted it nothing happened. The data in the table remained the same with multiple whitespaces
here is the insert:
$queryres = "insert into company (v1, v2, ...) VALUES ('$comptr ','$v2', ...)";
$resultsel = pg_query($con, $queryres);

Example:
I wrote this in the input:
  "     TEST     COMP.  "

in the table stayed this:
"     TEST     COMP.  "

and I want to change to this:
"TEST COMP."

A: You can delete multiple whitespaces within a text not with trim() but quite well with preg_replace(). Make a combination of trim() and preg_replace().
$comp = $_POST["company"];
echo trim(preg_replace('/\s+/', ' ', $comp));

// putput: TEST COMP.

preg_replace() https://www.php.net/manual/de/function.preg-replace.php
trim() https://www.php.net/manual/de/function.trim.php

A: I prefer shorter form for this solution, make a combination of ltrim() and rtrim
$comp = ltrim(rtrim($_POST["company"]));
var_dump($comp);
// output: TEST COMP.

rtrim() - Strip whitespace (or other characters) from the end of a string
ltrim() - Strip whitespace (or other characters) from the beginning of a string.


text:
Q: How to get request and response size in gatling In Postman I can see  request and response size

How do I get this in gatling ?
I need to validate the size.

A: You can validate size via check and bodyLength where pass expected size in bytes.
val request = http("request")
    .get("localhost")
    .check(
      bodyLength.is(221)
    )


text:
Q: ListView height android I have a FrameLayout and a Listview inside the FrameLayout.
I populate the Listview with another Layout.
The problem is if I set the layout_height to wrap_content my getview is getting called multiple time for a single record and if I set the layout_height to fill_parent or wrap_content my getview is being called 3 times for a single record. If I set the layout_height to some dp value it is working fine. I mean I dont have any issues with performance and my getview is getting called only once for a record.
So I get the screen height and width programmatically using
Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();

But if I set the width and height of my Listview with the value measured using the above code the last record of my Listview is partially not visible.
I guess this should be because the obtained screen height includes the title bar height, status bar height and notification bar height.
So if that is the prob can someone help me with calculating the available screen height? That is screen height-titlebar height-statusbar height-notification bar height?
else What is the problem? why my last record in my ListView is not fully visible?
XML File
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listview"
android:background="#ffffff"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ListView android:id="@+id/android:list"
android:background="#ffffff"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="300dp"
android:clickable="true"
android:fastScrollEnabled="true"
android:smoothScrollbar="true"
/>
</FrameLayout>

Then I set the layout_height and layout_width of the list view in my java code as
Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
FrameLayout.LayoutParams parameters = new FrameLayout.LayoutParams((int)(width),(int)(height));
ListView listview=(ListView) getListView();
listview.setLayoutParams(parameters );

A: Hi all thanks for your help
I changed my code as below and now its working :)
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height=0;
int width = display.getWidth();
switch (metrics.densityDpi)
{
case DisplayMetrics.DENSITY_HIGH:
height = display.getHeight() - (48*2);
break;
case DisplayMetrics.DENSITY_MEDIUM:
height = display.getHeight() - (32*2);
break;
case DisplayMetrics.DENSITY_LOW:
height = display.getHeight() - (24*2);
break;
default:
height = display.getHeight() - (48*2);
}
FrameLayout.LayoutParams parameters = new FrameLayout.LayoutParams((int)(width),(int)(height));
ListView listview=(ListView) getListView();
listview.setLayoutParams(parameters );

A: in java:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int s_width,s_height;
s_width = metrics.widthPixels;
s_height = metrics.heightPixels/3;
TableRow.LayoutParams parameters = new TableRow.LayoutParams(s_width,s_height);
LinearLayout b_list_table=(LinearLayout) findViewById(R.id.b_list_table);
b_list_table.setLayoutParams(parameters);

in xml:
<?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >

   <LinearLayout
       android:orientation="vertical"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_alignParentBottom="false"
       >

       <TableRow
           android:layout_width="match_parent"
           android:layout_height="180dip"
           android:id="@+id/b_list_table"
           >
           <ListView android:id="@+id/list"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_weight="1"
               android:drawSelectorOnTop="false"/>
       </TableRow>

       <TableRow
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           >
           <ListView android:id="@+id/listf"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"

               android:layout_weight="1"
               android:drawSelectorOnTop="false"/>
       </TableRow>

   </LinearLayout>


text:
Q: Retrieving the first element from data snapshot I'm trying to pull out the first record from the code below.
exports.sendBuyerNotification = functions.database.ref('/Bids/{uid}').onWrite((async(change,context)=>{

 const bid= change.after.val();
 const prodid = bid.prodID;
 const new_price = bid.price;
 const biddata= admin.database().ref('/Bids');
 biddata.orderByChild('prodID').equalTo(prodid).limitToLast(2).once('value',function(snapshot){
    var old_data = [];
    old_data.push(snapshot.val());
    var mystring = JSON.parse(snapshot.val())
    return console.log("Old price" + mystring[0].price);

Result : undefined

A: Looks like you probably will get back an array of up to 2 items from the database because of limitToLast(2). But you need to check if you're actually getting data back from the database before anything else - see the console.log statements below - I have made some other suggestions also.
Try this and see if it solves you issue:
exports.sendBuyerNotification = functions.database.ref('/Bids/{uid}').onWrite((async(change,context) => {

 const bid = change.after.val();
 console.log(bid) // are you getting a value from this?
 const prodid = bid.prodID;
 const new_price = bid.price;
 const biddata= admin.database().ref('/Bids');
 biddata.orderByChild('prodID')
            .equalTo(prodid)
            .limitToLast(2)
            .once('value', function(snapshot){
                console.log(snapshot.val()) // check you are getting a value?

                const myString = snapshot.val();
                console.log("Old price" + myString[0].price);

                return {
                        message: "Old price $" + myString[0].price,
                        values: snapshot.val()
                };
            })
})


text:
Q: Where and how to search for resources (minerals, crystals, etc.) Different resources are used to produce components and enhancements. Though, these resources are hardly met. Few times I've found some ore flying around in the space on missions.
Is there any rule where resources are met the most often?

A: Resources are found near objects and asteroids and from killing enemies. If you want basic items search in sectors nearest the active faction base, for more advanced items look in sectors rank 10+. Sectors in the middle between the 3 factions is where you'll find the best items.


text:
Q: Only one item get's displayed in x axis d3 - ordinal using tickvalues I have a pen here, that shows my problem. As you can see there is only one value in the x axis. I get all the values if I remove tickvalues, but that will cause problem with other data as there will be a huge set of data. I am using the tickvalues to limit the number of items to 20. This works for my other charts, but not for this chart. The scale is ordinal and in the console I am getting a NaN when calling xaxis. Which, I think is interfering with the tickvalues. If someone can look at the pen and provide any suggestions, it will be much appreciated. Here is the code parts. For full code, see the pen.
function plotVerticallyStacked(data) {

  checkLength(dataset);
  var x = d3.scale.ordinal()
    .rangeRoundBands([0, WIDTH], .1);

  var y = d3.scale.linear()
    .rangeRound([HEIGHT, 0]);

  // Color range - add your favorites here
  var color = d3.scale.ordinal()
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

  var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .tickValues(_arr.map(function(d) {
      return d["state"];
    }));

  var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .tickFormat(d3.format(".2s"));

  appendResponsiveSvg();

  svg.append("g")
    .attr("transform", "translate(" + MARGINS.left + "," + MARGINS.top + ")");

  var domain = ["sum(quantity)"];

  data.forEach(function(_data) {
    var y0 = 0;
    _data.groupedItem = [];
    _data.values.map(function(d, index) {
      _data.groupedItem.push(domain.map(function(name) {
        return {
          label: "quantity" + (index + 1),
          name: name,
          y0: y0,
          y1: y0 += +d[name]
        };
      })[0]);
      _data.total = _data.groupedItem[_data.groupedItem.length - 1].y1;
    });

  });

  data.sort(function(a, b) {
    return b.total - a.total;
  });

  x.domain(data.map(function(d) {
    return d.values[0]["sum(quantity)"];
  }));
  y.domain([0, d3.max(data, function(d) {
    return d.total;
  })]);

  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + HEIGHT + ")")
    .call(xAxis);

  svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

  var state = svg.selectAll(".state")
    .data(data)
    .enter().append("g")
    .attr("class", "g")
    .attr("transform", function(d) {
      return "translate(" + x((d.values[0])["sum(quantity)"]) + ",0)";
    });

  state.selectAll("rect")
    .data(function(d) {
      return d.groupedItem;
    })
    .enter().append("rect")
    .attr("width", x.rangeBand())
    .attr("y", function(d) {
      return y(d.y1);
    })
    .attr("height", function(d) {
      return y(d.y0) - y(d.y1);
    })
    .style("fill", function(d) {
      return color(d.label);
    });
}
plotVerticallyStacked(verticalStackedData);

A: I hope this is what you want : https://jsfiddle.net/reko91/yg0rs4xc/17/
I find it easier to use fiddle :)
Insteadof tickValues I used tickFormat :
 .tickFormat(function(d, i) {
      return d;
    });

Let me know if that's ok :)


text:
Q: Auto scroll image inside element from top to bottom I have long image that i want to display it inside a div element that has specific dimensions. The image inside is in absolute position.
The image has a "Start" and "Finish" text inside so i can check if the scrolling is done.
Here is the code that i have tried to move the image up so i can see the whole image while it's scrolling.
TweenLite.to($(".pa-video-container-mobile img"), 20, {transform: "translate3d(0,100vh,0)", yPercent: -100});

I have created a jsfiddle. Try to hit the "Run" button more than 2 times. Sometimes the code works.
https://jsfiddle.net/0xu476vp/1/
I have tried to transform the image through tweenlite library but the code does not show the bottom of the image.
Sometimes the image is shown near the end (without showing the "Finish" text) and sometimes the image is far away from the "Finish" text.


text:
Q: Saving custom object as core data property I am trying to save a custom class as a property of a core data object.
The Core Data object:
@objc(Safer)
class Safer: NSObject
{
@NSManaged var perakimFiles: [prayer]? //This line gives me an error saying that it cannot save a type that is not Obj. C
@NSManaged var titleEnglish: String?
@NSManaged var titleHebrew: String?
@NSManaged var parshaPerakim: [Int]?
@NSManaged var saferCode: String?
var titles: [[String]]
{
    get
    {
        var ret = [[String]]()
        var i = 0
        for file in perakimFiles!
        {
            ret.append([file.title, "\(i+1)"])
            i++
        }
        return ret
    }
}

init(_ _saferCode: SefarimCodes)
{
    super.init()
    self.saferCode = _saferCode.rawValue
}

init(_perakimFiles: [prayer], _titleEnglish: String, _titleHebrew: String)
{
    super.init()
    self.perakimFiles = _perakimFiles
    self.titleEnglish = _titleEnglish
    self.titleHebrew = _titleHebrew
}
init(_perakimFiles: [prayer], _titleEnglish: String, _titleHebrew: String, _parshaPerakim: [Int])
{
    super.init()
    self.perakimFiles = _perakimFiles
    self.titleEnglish = _titleEnglish
    self.titleHebrew = _titleHebrew
    self.parshaPerakim = _parshaPerakim
    self.saferCode = setTorahSaferCode()!.rawValue
    let config = self.configFromCode()
    self.perakimFiles = config.perakimFiles
}
}

Here is the prayer class that I am trying to save in the core data object:
class prayer
{
var url: NSURL
var title: String
var detail: String?

init(initURL: NSURL, initTitle: String)
{
    print("1")
    print("2")
    self.title = initTitle
    print("3")
    self.url = initURL
    print("4")
}

init(initURL: NSURL, initTitle: String, initDetail: String)
{
    self.url = initURL
    self.title = initTitle
    self.detail = initTitle
}
}

So what can I do to the prayer class to make it savable by the core data object? I need to also be able to use instances of the prayer class in other places of the code.

A: As mentioned, have your prayer class subclass NSObject and conform to NSCoding which requires two methods : -initWithCoder: and encodeWithCoder:
Once those are implemented, you can use NSKeyedArchiver/NSKeyedUnarchiver class methods to transform your objects into NSData objects and back, thus allowing you to store your objects as CoreData properties under the supported NSData type.

A: Let class prayer conforms to NSObject and NSCoding and see whether that addresses the error.