text:
Q: Php high memory usage We have an old facebook app, running smoothly written in native php.
This month we decided to rewrite it in zend-framework 2. Yesterday, after switching to new app it crashed our server with lots of out of memory errors. So we turned back to old app.
I installed xdebug to profile the app. Using memory_get_peak_usage() function i noticed high memory usage.
In the old app, a static page uses only 1 mb memory. But the new one using 7-8 mb approximately on the same page.
Here's the top two rows from webgrind:
   Function                                     Invocation Count    Total Self Cost    Total Inclusive Cost
   Composer\Autoload\ClassLoader->loadClass     224                 23.31       47.20
   Composer\Autoload\ClassLoader->findFile      224                 9.57        10.23

Also tried tha apache's ab tool
   ab -n 50 -c 5 -C PHPSESSID=SESSIONID http://myhost.com

Result is:
   Percentage of the requests served within a certain time (ms)
   50%    368
   66%    506
   75%    601
   80%    666
   90%   1073
   95%   1812
   98%   2278
   99%   2278
   100%   2278 (longest request)

All these results from the production server not localhost.
Is 7-8 mb for a single page normal? If not, how can i reduce it? Should i look for it in zf2 or composer?
I can give code samples if you need. Thank you.

A: When you migrate a solution from native to Zend, you must be aware of the way Zend works.
Zend is composed of lot of classes, and the memory used increase while you use Objects instead of native/light structures.
To improve memory use, review your code and do the following :

*

*wrap some code in functions, it helps Garbage collector to remove unused objects from memory.

*Don't store large lists of object in arrays before printing them, juste print on the fly.

*Limit the creation of objects (calls to 'new') in loops.

Hop this helps.

A: I spent a day to figure out problem. Tried xdebug, xhprof. There was no problem in the code.
We switched back to 2.0.0 and problem solved. I don't know what is wrong with new versions, for now stick with the 2.0.0.
Overall memory usage is around 4mb, no crashes.
composer.json:
"zendframework/zendframework": "2.0.0",


text:
Q: Remove Query string from website url i want to remove query string from my url using htaccess but i cant find any proper solutions
www.mysite.net/index.php?title=Category:Public_Companies&redirect=no&pagefrom=GET+UP
I Want
www.mysite.net/Category:Public_Companies/GET+UP
How can i do this. Any help will be appreciated.

A: The fast and easy way
.htaccess
RewriteEngine On
RewriteRule ^(.*)/(.*) index.php?title=$1&pagefrom=$2&redirect=no [L]

I create for all characters you need define what character you will be use.
Php file for test .htaccess frendly url
<?php print_r($_GET); ?>

A: put this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+index\.php\?title=([^\s&]+)&redirect=no&pagefrom=([^\s&]+) [NC]
RewriteRule ^ /%1/%2? [R=301,NE,L]

RewriteRule ^([^/.]+)/([^/.]+)/?$ /index.php?title=$1&redirect=no&pagefrom=$2 [L,QSA]

redpajama_set_name: RedPajamaStackExchange


text:
Q: my program A PHP Error was encountered. Message: Undefined index: jenis_kelamin and Undefined index: tanggal_lahir Filename: controllers/siswa.php
Undefined index: jenis_kelamin

$_POST['jenis_kelamin'] = strtoupper($data['siswa']['jenis_kelamin']);

ndefined index: tanggal_lahir

$data['siswa']['tanggal_lahir'] = date('d-m-Y',strtotime($data['siswa']['tanggal_lahir']));

full code
function update($id=1)
        {
            //set common properties
            $data['title'] = 'Update siswa';
            $this->load->library('form_validation');
            //set validation properties
                $this->_set_rules();
                $data['action']=('siswa/update/'.$id);

                //run validation
                if ($this->form_validation->run() === FALSE) {
                    $data['message']='';

                    $data['siswa'] = $this->siswa_model->get_by_id($id)->row_array();
                    $_POST['jenis_kelamin'] = strtoupper($data['siswa']['jenis_kelamin']);
                    $data['siswa']['tanggal_lahir'] = date('d-m-Y',strtotime($data['siswa']['tanggal_lahir']));

                    //set common properties
                    $data['title']='Update siswa';
                    $data['message']='';

                }
                else
                {
                    //save data
                    $id = $this->input->post('id');
                    $siswa=array('nama'=>$this->input->post('nama'),
                        'alamat'=>$this->input->post('alamat'),
                        'jenis_kelamin'=>$this->input->post('jenis_kelamin'),
                        'tanggal_lahir'=>date('Y-m-d', strtotime($this->input->post('tanggal_lahir'))));
                    $this->siswa_model->update($id,$siswa);
                    $data['siswa'] = $this->siswa_model->get_by_id($id)->row_array;

                    //set user message;
                    $data['message']='update siswa success';
                }
                $data['link_back']= anchor('siswa/index/','Lihat Daftar Siswa',array('class'=>'back'));

                //load view
                $this->load->view('siswaEdit',$data);
        }

A: Always make use of the isset construct (whether a value is assigned to your variable or not) to check for the variables before assigning data.
if(isset($_POST['jenis_kelamin']))
{
$_POST['jenis_kelamin']= strtoupper($data['siswa']['jenis_kelamin']);
}

Similarly do it for your other variables.
EDIT :
Change your $siswa array like this... Add the id param.
$siswa=array('id'=>$id,'nama'=>$this->input->post('nama'),
                        'alamat'=>$this->input->post('alamat'),
                        'jenis_kelamin'=>$this->input->post('jenis_kelamin'),
                        'tanggal_lahir'=>date('Y-m-d', strtotime($this->input->post('tanggal_lahir'))));


text:
Q: how to use boolean expression in switch in C++ I need to convert the if else into switch statement, please help:
if (XMLString::compareString(xmlch_Title, XMLString::transcode("abc")) == 0 ) {
    out_Config.abc = XMLString::transcode(xmlch_Value);
} else if (XMLString::compareString(xmlch_Title, XMLString::transcode("def")) == 0 ) {
    out_Config.def = XMLString::transcode(xmlch_Value);
} .......

A:
Note: Using a boolean expression as the condition of a switch would, in your case, be of little use since you then could only have two possible outcomes of the switch-statement:
Going to "case true: ", or "case false: "

Introduction
As stated in the Standard (n3797), the condition used with a switch must be implicitly convertiable to either integral, or enumeration, type.

6.4.2p2 The switch statement [stmt.switch]

The condition shall be of integral type, enumeration type, or class type. If of class type, the condition is contextually implicitly converted (Clause 4) to an integral or enumeration type**.  Integral promotions are performed. Any statement within the switch statement can be labeled with one or more case labels as follows:
case constant-expression:

where the constant-expression shall be a converted constant expression (5.19) of the promoted type of the switch condition. No two of the case constans in the same switch shall have the same value after conversion to the promoted type of the switch condition.

What this means is that the theoretical implementation below is ill-formed, since std::string can't implicitly be converted to an integral or enumeration type (1), and neither is it usable in a constant-expression (2).
std::string get_string ();

switch (get_string ()) {            //          (1)
  case std::string ("stack"): ...;  // <----.
  case std::string ( "over"): ...;  // <----|-- (2)
  case std::string ( "flow"): ...;  // <----'
}

Am I completely out of luck?
Not really, if you were to use a hashing function to generate a hash for the strings involved, you can theoretically use a switch; just be careful about potential collisions of said hashes.
Also note that there must be an implementation usable in constant-expressions for the case-labels.
Is it worth writing such complex code to solve this kind of problem? Probably not.

A: if you want to factor out the common part, you'll probably need to use an array of struct containing the transcoded string constant and a lambda doing the then operation. Something along the lines of:
#include <functional>

struct check_case {
  const XMLString code;
  const std::function <void (Config &, const XMLString &)> handler;
};

check_case check_list[2] = {
  {XMLString::transcode("abc"), [](Config &out_Config, const XMLString &code) { out_Config.abc = code;}},
  {XMLString::transcode("def"), [](Config &out_Config, const XMLString &code) { out_Config.def = code;}},
};

for (auto c : check_list) {
   if (XMLString::compareString(xmlch_Title,c.code) == 0){
     c.handler(out_Config, XMLString::transcode(xmlch_Value));
     break;
   }
}

It's still quite verbose though, and I'm not sure you'd find it more easily readable. Besides, you don't get to cascade your handlers as you could with a normal switch (which was perhaps the original reason for your question).
Alternatively, you could embed all that in a dedicated class, where it's easier to build a context (the class instance member fields). There it would be easier to cascade methods manually. As above, the readability isn't quite up to par either.

A: Look at it from a different point of view. Do it in two stages...
Stage 1: Extract the text in the quotes "abc" or "def"
Stage 2: switch (based on variable from stage 1) and case will provide implementation


text:
Q: How should I exactly mix refracted and reflected color, fresnel I am building a raytracer in C for the school. Yesterday I successfully implemented my first recursive refraction, however I am not very satisfied with the result. a picture of my raytracer with 2 reflective spheres
I find that the water ball doesn't look like a water ball so if you have some advice on what I should do next tell me please, from what I had read:
Beer law
Making the darkness of the shadow depend on how long a ray light traveled trough a refractive material (I guess I can use beer law for that)
I suspect this could come from my implementation, here is what I did:
first I set a material like that:
-DIFFUSE 1
-SPECULAR 10
-REFLEXION 0.1
-REFRACTION 0.9
-IOR 1.33

This are the characteristics of my water material.
Since I am using fresnel to calculate how much transmitted and refracted colore I should take to compute my final colore I am wondering if my reflection and refraction coef shouldn't be simply Boolean. Right now I am using them to ponderate how much reflection and refraction colore I should use, but isn't it too much since I am also using fresnel? I am a bit confused about this part and red a lot of PDF from a lot a university but the precise mix isn't cover by them, they just tell us to use fresnel to choose how much reflected or transmitted light we should use but when they put pseudo code you can read that they call recursively them function: if (material->is_reflective)
if (material->is_refractive)


text:
Q: MySQL Connecting with Blank User Name & Password I'm having serious trouble for the last few days, please have empathy with my question.
After a series of server crashes and hackings, today I've found out that my mysql can be connected via a web interface without a username and password. Is this even possible? I think i'm close to losing my sanity.
Please help me some one.

A: I have found the answer. I had set skip-grant-tables in my.cnf while trying to perform some user management work which had caused this. Phew. The panic, the sanity. I hope this helps someone.


text:
Q: Qual framework devo utilizar em Testes Funcionais no .net? Gostaria de saber as opções de framework que simula testes unitários para o .net.
Conheço um pouco de Ruby e sei que nele existe o Cucumber que por sinal é muito bom, porém para .net fiz uma pesquisa e percebi que existem várias opções. Estou na dúvida, qual utilizar?

A: Minhas opções
Você pode usar o MSTest juntamente com um framework de Mock como o Moq, e algum framework de inversão de controle, tal como o SimpleInjector... dessa forma seu sistema poderá ser testado facilmente.
Existem outras opções, mas eu pessoalmente uso esta configuração.
Outras opções
Testes:

*

*NUnit (já usei, acho muito bom)

*MSTest (Microsoft, já usei, bom também)

Mocks:

*

*Rhino mocks (já testei)

*Moq (já usei... muito bom, muito símples)

Inversão de controle:

*

*SimpleInjector (já usei, muito bom... é o mais rápido)

*Unity (Microsoft)

*Ninject (já usei, muito bom)

Integração continua:

*

*Jenkins (já usei, achei bom)

*Team City - JetBrains: a JetBrains é a produtora de ReSharper... precisa falar mais?
Testes de interface:

*

*Selenium, com .Net binding (já usei faz tempo, achava bastante fácil)

*Selenium Toolkit for .Net

*PhantomJs: existe um pacote do nuget. O PhantomJS permite fazer testes sem precisar ter um browser instalado, e sem necessidade de mostrar janelas.

A: Para testes de interface, tambem acrescentaria o Coded UI Tests do Visual Studio.
Pessoalmente para testes unitários eu tenho usado o NUNIT com o resharper e estou bastante satisfeito.
Indico-te mais uns quantos IOC containers que podes usar com .NET. No passado usei o Ninject, mas é bastante "pesado" mudei a minha escolha para o AutoFac. Podes ate' escrever o teu próprio IOC com poucas linhas de código se não estiveres satisfeito com o que existe.


text:
Q: BeautifulSoup get nearest tag with class, not a sibling and nested in unknown sibling

    Headline #1

    Headline #2

    Headline #3

This is my structure. I am enumerating over the table tags and want to retrieve the text value of the span tags with a class of 'headline' which is nearest to my table. By "nearest" I mean that if you were to flatten out the html, I want to target the span with a class 'headline' that you would come across first if you started up from the point of the table
Sometimes those spans are nested inside an h3, sometimes an h4, sometimes a p tag. Sometimes the table tag is on the same level as the h3/h4/p and sometimes it is itself nested inside a center tag. And sometimes the h3/h4/p tag is an immediate sibling of the table and sometimes it isn't.
How can I use BeautifulSoup to find nearest span.headline regardless of nesting level and whether it is nested inside a parent or sibling?
So far I've got this code
tables = soup.findAll("table", {"class": ["striped"]})

for index, table in enumerate(tables):
    headline = table.find_previous('h3').("span", {"class" : ["headline"]}).text

A: I was able to use the find_previous method on each table to find the previous headline for the sample html you provided. I added an additional idx attribute to each table to use when checking if the headline belongs to that table. I also added two tables to the beginning and end of the html that have no previous headline.
html = '''

    Headline #1

    Headline #2

    Headline #3

'''.replace('\n', '')

soup = BeautifulSoup(html, 'lxml')
table_query = ('table', {'class': 'striped'})
headline_query = ('span', {'class': 'headline'})

for idx, table in enumerate(soup.find_all(*table_query)):
    table.attrs['idx'] = idx
    previous_headline = table.find_previous(*headline_query)
    if (previous_headline and
        previous_headline.find_next(*table_query).attrs['idx'] == idx):
        print(previous_headline.text)
    else:
        print('No headline found.')

Output:
No headline found.
Headline #1
Headline #2
Headline #3
No headline found.


text:
Q: How to connect view button / label to controller file in Xcode 11? Hey guys I have an strange problem. I recently updated to Xcode 11 and when I want to open the view controller file beside my storyboard file to connect IBAction for a button there is no button in Xcode to do so. There used to be a double circle button (similar to AUB picture) but I can't find it now.
I searched the web but couldn't find any solution either.

A: In Xcode 11 you will have open the ViewController.xib first, then hold OPTION (ALT) and click on the related ViewController.swift

A: You can also add a new tab by clicking the button i circled in the image:


text:
Q: Can I set a delay on startup programs that are shown on Windows 8 Task Manager? Microsoft created a new feature on Windows 8 that allow users to manage startup programs on Windows Task Manager:

We can Disable or Enable programs that Windows show us that are having "High" impact on Windows 8 startup time. There is a way to disable it, but assuming that I don't want to completelly disable it from automatic startup, I just want to set a delay time on this program startup, as already happends on Windows services:

Automatic (Delayed) is a new startup type introduced in Windows Vista,
  that starts the service a short while after the system has finished
  its booting and initial busy operations, so that the system boots up
  faster.

There is any way to do that? Even being with Windows register, vbs, powershell or whaterver..?

A: Soluto should do the trick - Its an application meant for measuring and optimising start up times. You can select the 'pause' option to load a startup item when needed, and the delay option to delay a startup entry.
This article seems to state its a registry hack, but dosen't actually say what entries need editing - so this may be another option.

A: This article discusses "3 Small Windows Tools To Delay any Program(s) At Startup".  The recommendations are:

*

*Startup Delayer.  I found this to be a small but full featured program.  There are free and premium versions to choose from.

*LaunchLater. Open source, but out of date (last updated Aug 30, 2011).  I didn't try this one.

*WinPatrol.  Well-designed Autoruns-like program. Frequently updated. Free and "Plus" versions.

Soluto is a strange cloud-/web-based solution, and it seems to require you to create an account.  Not on my list of programs to try.


text:
Q: Manually delete object tree in entity-Framework If I want to delete manually an object and all it's children,
How can I do it (I don't want to use cascade-delete)
When I'm trying to iterate over the children list - I get an exception because I'm changing the collection inside foreach - and that's a problem... any other way to do it ?
(I'm setting each time state to deleted).
var myAssignemnt = (from s in context.Assignments.Include("ActivityInAssignments").Where(s => s.AssignmentID == AssignmentID) select s).FirstOrDefault();

foreach (ActivityInAssignment acc in myAssignemnt.ActivityInAssignments)
{
  context.ObjectStateManager.ChangeObjectState(acc, System.Data.EntityState.Deleted);
}
context.ObjectStateManager.ChangeObjectState(myAssignemnt, System.Data.EntityState.Deleted);
context.SaveChanges();

A: Maybe try ... in myAssignemnt.ActivityInAssignments.ToList()


text:
Q: Specific Datatype for this situation? I want to pull data from a database. Name, Age, Sex, Location.(maybe more fields)
I want to hold the data in an object similar to how I would expect it to look in a JSON object.
Like:
 myData{
        row1[name:beavis, age:48, sex:male, location:Joburg]
        row2[name:quintus, age:43, sex:, location:Helsinki]
        ...up to say 500 rows
    }

So i'd like to be able to do tempName = row(i).name and so on in java.
Any suggestions.

A: // Defines a Person datatype
public class Person {
  // fields
  private String name;
  private int age;
  private String location;

  // gets the value of a field
  public String getName() {
     return name;
  }

  // sets the value of a field
  public void setName(aName) {
     this.name = aName;
  }

}

What I did here was define a Person type with a number of fields. Also I give here an example of a setter and getter for the name field. You can put them in an array or collection. For example:
Person people[] = new Person[2];
people[0] = new Person();
people[0].setName("Alice");

You can also dispense with the setters and getters by making the fields public, but I wouldn't recommend it.

A: A straight translation of that data structure would be along the lines of
List<Map<String, Object>> myData

so you'd be able to call
tempName = (String) myData.get(i).get("name");

Like the JSON array, this doesn't enforce typing (which you'll have to deal with explicitly in Java) and doesn't limit the fields to only those from the database.
If all the database values are strings, things get cleaner as no casts are necessary.
List<Map<String, String>> myData
tempName = myData.get(i).get("name");


text:
Q: Why the function sparse.model.matrix() ignored the columns? Can somebody help me please? I want to prepare data for XGBoost prediction so I need edit factor datas. I use sparse.model.matrix() but there is a problem. I don't know, why function ignored some of the columns. I'll try to explain. I have dataset dataset with many variables, but now these 3 are important:

*

*Tsunami.Event.Validity - Factor with 6 classes: -1,0,1,2,3,4

*Tsunami.Cause.Code - Factor with 6 classes: 0,1,2,3,4,5

*Total.Death.Description - Factor with 5 classes: 0,1,2,3,4

But when I use sparse.model.matrix() I get matrix only with 15 columns not 6+6+5=17 as expected. Can somebody give ma an advice?
sp_matrix = sparse.model.matrix(Deadly ~ Tsunami.Event.Validity + Tsunami.Cause.Code + Total.Death.Description -1, data = datas)

str(sp_matrix)

Output:
Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:2510] 0 1 2 3 4 5 6 7 8 9 ...
  ..@ p       : int [1:16] 0 749 757 779 823 892 1495 2191 2239 2241 ...
  ..@ Dim     : int [1:2] 749 15
  ..@ Dimnames:List of 2
  .. ..$ : chr [1:749] "1" "2" "3" "4" ...
  .. ..$ : chr [1:15] "Tsunami.Event.Validity-1" "Tsunami.Event.Validity0" "Tsunami.Event.Validity1" "Tsunami.Event.Validity2" ...
  ..@ x       : num [1:2510] 1 1 1 1 1 1 1 1 1 1 ...
  ..@ factors : list()
  ..$ assign   : int [1:15] 0 1 1 1 1 1 2 2 2 2 ...
  ..$ contrasts:List of 3
  .. ..$ Tsunami.Event.Validity : chr "contr.treatment"
  .. ..$ Tsunami.Cause.Code     : chr "contr.treatment"
  .. ..$ Total.Death.Description: chr "contr.treatment"

A: This question is a duplicate of In R, for categorical data with N unique categories, why does sparse.model.matrix() not produce a one-hot encoding with N columns? ... but that question was never answered.
The answers to this question explain how you could get the full model matrix you're looking for, but don't explain why you might not want to. (For what it's worth, unlike regular linear models regression trees are robust to multicollinearity, so a full model matrix would actually work in this case, but it's worth understanding why R gives you the answer it does, and why this won't hurt your predictive accuracy ...)
This is a fundamental property of the way that linear models based (additively) on more than one categorical predictor work (and hence the way that R constructs model matrices). When you construct a model matrix based on factors f1, ..., fn with numbers of levels n1, ..., nn the number of predictor variables is 1 + sum(ni-1), not sum(ni). Let's see how this works with a slightly simpler example:
xx <- expand.grid(A=factor(1:2), B = factor(1:2), C = factor(1:2))
model.matrix(~A+B+C-1, xx)
  A1 A2 B2 C2
1  1  0  0  0
2  0  1  0  0
3  1  0  1  0
4  0  1  1  0
5  1  0  0  1
6  0  1  0  1
7  1  0  1  1
8  0  1  1  1

We have a total of (1 + 3*(2-1) =) 4 parameters.
The first parameter (A1) describes the expected mean in the baseline level of all parameters (A=1, B=1, C=1). The second parameter describes the expected difference between an observation with A=1 and one with A=2 (independent of the other factors). Parameters 3 and 4 (B2, C2) describe analogous differences between B1 and B2.
You might be thinking "but I want predictor variables for all the levels of all the factors, e.g.
m <- do.call(cbind, lapply(xx, \(x) t(fac2sparse(x))))
dim(m)
## [1] 8 6

This has all six columns expected, not just 4.  But if you examine this matrix, or call rankMatrix(m) or caret::findLinearCombos(m), you'll discover that it is multicollinear. In a typical (fixed-effect) additive linear model, you can only estimate an intercept plus the differences between levels, not values associated with every level. In a regression tree model, the multicollinearity will make your computations slightly less efficient, and will make results about variable importance confusing, but shouldn't hurt your predictions.


text:
Q: New function constructor that returns another function in TypeScript I have this function in JavaScript:

function test()
{
  this.list = {};
  return (id) =>
  {
    if (!(id in this.list))
      this.list[id] = {default: 123};

    return this.list[id]
  }
}

const blah = new test();
blah("ok").mykey = "ok";
console.log(blah("ok").mykey);
console.log(blah("ok"));

And I'm trying convert it into TypeScript format. I understand I'd have to use class, however how do I return a function from the class constructor?
I don't want have an additional property, myfunc, as a function new test().myfunc("ok"):
interface simpleObject
{
  [key:string]: string|number|object;
}

class Test
{
  private list:simpleObject;

  public myfunc(id:string)
  {
    if (!(id in this.list))
      this.list[id] = {default: 123};

    return this.list[id] as simpleObject;
  }

  constructor()
  {
    this.list = {};
  }

}

const blah = new Test();
blah.myfunc("test").mykey = "ok";
console.log(blah.myfunc("test").mykey);
console.log(blah.myfunc("test"))

On TS Playground

A: Why do you want to use new on something that returns a function? Just call the function without new.
You can achieve that by keeping your state in closures instead of using this;
function test() {
  const list: {[id: string]: any} = {};
  return (id: string) =>  {
    if (!(id in list)) {
      list[id] = {default: 123};
    }
    return list[id]
  }
}

const blah = test();

See Live Example
I think this is what you should use. Having said that, the ability to specify what a constructor returns is not yet available but could be in the future.
I could suggest a workaround (from the linked issue above) or this answer but I don't see why you'd want to use that for your case since what I suggested is simpler and there is no need for classes here.

A: The constructor of a class will return the instance of said class, and that is the intended behaviour. Your use case doesn't really necessitate usage of a class. You can still have your function and use this inside. To tell TypeScript what type this is, you can use a reserved parameter:
type ReturnedFunction = (id: string) => string | number | object;
type TestFunction = () => ReturnedFunction;

function test(this: TestFunction): ReturnedFunction {
  // same code as before
}


text:
Q: My font loads on Chrome but not in Firefox or any other mobile browser I'm rebuilding my website and I'm using a font called 'KlartextMono-Light'. It loads on Chrome but not in Firefox (v45.0.2) or any other mobile browser. I've tried looking at a bunch of forums but the fixes I've seen haven't worked
I have a 'fonts.css' file in my css folder, this is the code:
@font-face {
  font-family: 'klartext_monolight';
  src: url('../fonts/KlartextMono-Light-webfont.eot');
  src: local('☺'),
    url('../fonts/KlartextMono-Light-webfont.eot?#iefix') format('embedded-opentype'),
    url('../fonts/KlartextMono-Light-webfont.woff2') format('woff2'),
    url('../fonts/KlartextMono-Light-webfont.woff') format('woff'),
    url('../fonts/KlartextMono-Light-webfont.ttf') format('truetype'),
    url('../fonts/KlartextMono-Light-webfont.svg#klartext_monolight') format('svg');
  font-weight: normal;
  font-style: normal;
}

I have a separate fonts folder with all those versions of the type.
My main 'style.css' calls for the font this way:
h1, h2, h3, h4, h5, h6, p{
  font-family: KlartextMono-Light;
  margin: 0;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
}

And the part of my html header that loads the fonts looks like this:
<!-- Fonts
------------------------------------------- -->
<link rel="stylesheet" href="css/fonts.css">

<!-- Css
------------------------------------------- -->
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">

<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">

The fonts render perfectly on Chrome but they don't work on firefox or any of my mobile devices. What am I doing wrong?

A: Looks like you're using the wrong font name when you're calling the font-family property. When you declare the font, you call it klartext_monolight, but in your CSS, it's called KlartextMono-Light. Use the same name as the one you originally declared:
h1, h2, h3, h4, h5, h6 {
  font-family: 'klartext_monolight';
}

A: I think is because you are referring to your web font wrong...
in your css you are calling
font-family: "KlartextMono-Light"

When you font is actually called klartext_monolight
See what happens if you make that change


text:
Q: How can I download a file using the WebHDFS knox groovy library? The WebHDFS examples shows how to list files and folders in hdfs, make a directory and upload a file using BigInsights WebHDFS?
How can I adapt the examples to download a file for BigInsights WebHDFS?

A: The knox api documentation provides many more examples, e.g.
import groovy.json.JsonSlurper
import org.apache.hadoop.gateway.shell.Hadoop
import org.apache.hadoop.gateway.shell.hdfs.Hdfs

gateway = "https://localhost:8443/gateway/sample"
username = "bob"
password = "bob-password"
dataFile = "README"

session = Hadoop.login( gateway, username, password )
text = Hdfs.get( session ).from( "/tmp/example/README" ).now().string
file = new File('README')
file << text
session.shutdown()


text:
Q: Database name in where clause I'm trying to create a query to compare the lenght of the database name in where clause.
For example if the database is named 'test1' the query must return all users with id '1234' but doesn't work.
Somebody knows how to do? This is the query:
select * from users where id='1234' AND 5=(select length(database()))

A: This works perfect:
select * from users where id='1234' AND 10=(select length(database()));

See this this Fiddle. The database name is db_2_b7100.


text:
Q: iTextSharp: Split pages size equals file size Here is how I split a large PDF (144 mb):
public int SplitAndSave(string inputPath, string outputPath)
{
    FileInfo file = new FileInfo(inputPath);
    string name = file.Name.Substring(0, file.Name.LastIndexOf("."));

    using (PdfReader reader = new PdfReader(inputPath))
    {
        for (int pagenumber = 1; pagenumber <= reader.NumberOfPages; pagenumber++)
        {
            string filename = pagenumber.ToString() + ".pdf";

            Document document = new Document();
            PdfCopy copy = new PdfCopy(document, new FileStream(outputPath + "\\" + filename, FileMode.Create));

            document.Open();

            copy.AddPage(copy.GetImportedPage(reader, pagenumber));

            document.Close();
        }
        return reader.NumberOfPages;
    }
}

For most PDFs (small size, and I guess old format), all works fine. But for a bigger one (that perhaps are using something like refstreams for better compression), the split pages open as one page, but its size is equal to the original PDF's size. What can I do?

A: In case of your document Top_Gear_Magazine_2012_09.pdf the reason is indeed the one I mentioned: All pages refer to object 2 0 R as their /Resources, and the dictionary in 2 0 obj in turn references all images in the PDF.
To split that document into partial documents containing only the images required, you should preprocess the document by first finding out which images belong to which pages and then creating individual /Resources dictionaries for all pages.
As you already use iText in this context, you can also use it to find out which images are required for which pages. Use the iText parser package to initially parse the PDF page by page using a RenderListener implementation whose RenderImage method simply remembers which image objects are used on the current page. (As a special twist, iText hides the name of the image XObject in question; you get the indirect object, though, and can query its object and generation number which suffices for the next step.)
In a second step, you open the document in a PdfStamperand iterate over the pages. For each page you retrieve the /Resources dictionary and copy it, but only copy those XObjects references referencing one of the image objects whose object number and generation you remembered for the respective page during the first step. Finally you set the diminished copy as the /Resources dictionary of the page in question.
The resulting PDF should split just fine.
PS A very similar issue recently came up on the iText mailing list. In that thread the solution recipe given here has been improved, to get around the difficulties caused by iText hiding the xobject name, I now would propose to intervene before the name is lost by using a different ContentOperator for "Do", here the Java version:
class Do implements ContentOperator
{
    public void invoke(PdfContentStreamProcessor processor, PdfLiteral operator, ArrayList<PdfObject> operands) throws IOException
    {
        PdfName xobjectName = (PdfName)operands.get(0);
        names.add(xobjectName);
    }

    final List<PdfName> names = new ArrayList<PdfName>();
}

This content operator simply collects the names of the used xobjects, i.e. the xobject resources to keep for the given page.


text:
Q: How do I kill unresponsive threads I've been trying to find a way to kill the threads that are unresponsive at the end of this program:
Most of the time the code works, but on certain domains some of the threads will hang, not allowing the program to complete.
Any help would be much appreciated.
    #!/usr/bin/python

from socket import gethostbyaddr
import dns.resolver
import sys
import Queue
import threading
import subprocess
import time

exitFlag = 0
lines = ''

class myThread (threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q
    def run(self):
        process_data(self.name, self.q)

class Timer():
   def __enter__(self): self.start = time.time()
   def __exit__(self, *args):
        taken = time.time() - self.start
        print " [*] Time elapsed " + str(round(taken,1)) + " seconds at " + str(round(len(subdomains) / taken)) + " lookups per second."

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            host = data.strip() + '.' + domain.strip()
            try:
                answers = resolver.query(host)
                try:
                    output = gethostbyaddr(host)
                    if len(host) < 16:
                        print str(host) + "\t\t" +  str(output[0]) + " " + str(output[2])
                        found.append(str(host) + "\t\t" +  str(output[0]) + " " + str(output[2]))
                    else:
                        print str(host) + "\t" +  str(output[0]) + " " + str(output[2])
                        found.append(str(host) + "\t" +  str(output[0]) + " " + str(output[2]))
                except:
                    print str(host)
                    found.append(str(host))
            except:
                pass
        else:
            queueLock.release()

if len(sys.argv) < 3:
    print
    print 'Usage: dnsbrute.py <target.com> <subdomains.txt> (threads)'
    exit()

if len(sys.argv) >= 4:
    maxthreads = int(sys.argv[3])
else:
    maxthreads = int(40)

domain = sys.argv[1]
maked = "mkdir -p logs"
process = subprocess.Popen(maked.split(), stdout=subprocess.PIPE)
poutput = process.communicate()[0]
found = []
subdomains = [line.strip() for line in open(sys.argv[2], 'r')]
dnsservers = ["8.8.8.8", "8.8.4.4", "4.2.2.1", "4.2.2.2", "4.2.2.3", "4.2.2.4", "4.2.2.5", "4.2.2.6", "209.244.0.3", "209.244.0.4" ]
threadList = []
numthreads = 1
resolver = dns.resolver.Resolver()
resolver.nameservers = dnsservers
logfile = open("logs/" + domain + ".log", 'w')

while numthreads <= maxthreads:
    threadList.append(str("Thread-") + str(numthreads))
    numthreads += 1

print " [*] Starting " + str(maxthreads) + " threads to process " + str(len(subdomains)) + " subdomains."
print

queueLock = threading.Lock()
workQueue = Queue.Queue(len(subdomains))
threads = []
threadID = 1

with Timer():
    for tName in threadList:
        thread = myThread(threadID, tName, workQueue)
        thread.start()
        threads.append(thread)
        threadID += 1

    queueLock.acquire()
    for work in subdomains:
        workQueue.put(work)
    queueLock.release()

    while not workQueue.empty():
        pass

    exitFlag = 1

    for t in threads:
        t.join()

    for item in found:
      logfile.write("%s\n" % item)

    print
    print " [*] All threads complete, " + str(len(found)) + " subdomains found."
    print " [*] Results saved to logs/" + domain + ".log"

A: Please bear in mind that it is a bad approach to kill threads in whatever language, becuase the resources can be left in an unconsistent state. If you can, try to redesign your program such that the threads will close themselves by checking a boolean value. Anyway, a very good answer from a fellow here on SO:
Is there any way to kill a Thread in Python?


text:
Q: Precise Semantics of START_STICKY flag for Android Service Somehow I am having a hard time parsing the official description of the START_STICKY flag:

Constant to return from onStartCommand(Intent, int, int): if this
  service's process is killed while it is started (after returning from
  onStartCommand(Intent, int, int)), then leave it in the started state
  but don't retain this delivered intent. Later the system will try to
  re-create the service. Because it is in the started state, it will
  guarantee to call onStartCommand(Intent, int, int) after creating the
  new service instance; if there are not any pending start commands to
  be delivered to the service, it will be called with a null intent
  object, so you must take care to check for this.
This mode makes sense for things that will be explicitly started and
  stopped to run for arbitrary periods of time, such as a service
  performing background music playback.

Specifically, the following four parts do not make technical sense (aka make me go WTF):

*

*"if this service's process is killed ..., then leave it in the started state" [how do you leave something that is killed in the started state?]

*"Later the system will try to re-create the service. Because it is in the started state, ..." [why is it in the started state if the system is trying to re-create the service?]

*"Because it is in the started state, it will guarantee to call onStartCommand(...) ..." ["it will guarantee to call"? sorry, can't parse that phrase linguistically]

*"This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, ..." ["and stopped to run"??]

Does anybody have a better spec of this flag? And, to any Googlers reading this: wtf? Can you get it fixed internally pronto?

A: START_STICKY and START_NOT_STICKY

START_STICKY tells the OS to recreate the service after it has enough memory and call onStartCommand() again with a null intent

A: As you know, there are two forms a service can have in Android:

*

*Started service

*Bound service
The key point to understanding the description is that a Started service must manage its own lifecycle, i.e. the ONLY components that can stop the service is the service itself by calling stopSelf() or another component by calling stopService(). Once a Started service has been started (onStartCommand() returns) it's in a started state and it won't stop unless either stopSelf() or stopService() is called. So, if the system prematurely kills the service (neither stopSelf() or stopService() has been called), the service still is considered to be in a started state. And it's up to you to tell (signal to) the system how to proceed with the service after killing it by returning a flag in onStartCommand().
Probably the description of the START_STICKY flag given at the end of Extending the Service class will be more clear for you.
P.S. Regarding the "and stopped to run??" confusion, try reading it as "...explicitly started and stopped in order to run..."
EDIT:
Also take a look at this question.


text:
Q: Cannot create instance of ViewModel with Hilt It looks like I have problems with using Hilt.
I get the following error.
Maybe I need to add something to AppModule or something. I'm not sure...

I use the following dependencies:
implementation "com.google.dagger:hilt-android:2.43.2"
annotationProcessor  "com.google.dagger:hilt-android-compiler:2.43.2"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
annotationProcessor  "androidx.hilt:hilt-compiler:1.0.0"

My ViewModel class looks like this:
@HiltViewModel
class CurrencyViewModel  @Inject constructor(
    private val repository: CurrencyConverterImpl,
    private val dispatchers:DispatcherProvider
): ViewModel(){

The activity is like this:
@AndroidEntryPoint
class CurrencyActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val viewModel: CurrencyViewModel by viewModels()

AppModule:
@Module
@InstallIn(SingletonComponent ::class)
object AppModule {
    @Singleton
    @Provides
    fun provideCurrencyApi(): CurrencyApi = Retrofit.Builder()
        .baseUrl(Utils.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(CurrencyApi::class.java)

    @Singleton
    @Provides
    fun provideCurrencyConverter(api: CurrencyApi): CurrencyConverter = CurrencyConverterImpl(api)

    @Singleton
    @Provides
    fun provideDispatchers(): DispatcherProvider = object : DispatcherProvider {
        override val main: CoroutineDispatcher
            get() = Dispatchers.Main
        override val io: CoroutineDispatcher
            get() = Dispatchers.IO
        override val default: CoroutineDispatcher
            get() = Dispatchers.Default
        override val unconfined: CoroutineDispatcher
            get() = Dispatchers.Unconfined

    }
}

UPDATE:
It looks like Hilt didn't like that I put something to the constructor. It needed a constructor without parameters.
But the question is how do I pass the CurrencyConverter repository and DispatcherProvider to ViewModel?

If I pass any parameter I also get this exception:

A: In your CurrencyViewModel constructor, try replacing:
private val repository: CurrencyConverterImpl

with:
private val repository: CurrencyConverter

Your @Provides function is providing the interface, so you need to inject the interface. Besides, that improves testability of the viewmodel, as you can supply a test double (e.g., mock or fake) in unit tests.


text:
Q: Download JSON in Informatica Application Integration I am new to and ICAI, and i have a requirement

*

*a. create a service

*b. the user will upload a json file using this
webservice

*c. the json file will be downloaded and saved locally.

The solution path i was taking is:
create a process which will accept 2 inputs (some generic text and the json file)

which generated the below url

I tested the same in POSTMAN and it is working fine, but i am not able to download the json into informatica server on any location,

A: Final solution based on the feedback from Maciejg
Steps taken:

*

*create a filewriter app connection and set it up only for
"eventtarget"

*create a process

*in start - create a input field of type - attachment

*in start - create a temp field of type - filewriter connection

*add a assignment task

*in assignment task add a filed temp->content format of type content
-> attachment

*in the same assignment task add another field temp->file name of
type formula

Above steps are enough to save the uploaded file, if required, other steps (check file type, authentication etc) can be added.

A: It seems you need to use a FileWriter Service. Check out this knowledgebase article for details.


text:
Q: Laravel Call to undefined method I'm trying to update my data in the DB, but I keep getting a error.

Call to undefined method Illuminate\Database\Query\Builder::save()

Here is my code:
public function postTodo( Request $request ){
    if ( $request->input('action') == 'set_as_done' ){
        $thing = DB::Table('todo')->where('id', $request->input('id'));
        if ( $thing ){
            $thing->done = $request->input('set_as_done');
            $thing->save();
        }
        return redirect(route('admin.todo'));
    }
}

A: To do $thing->save(), $thing must be instance of model that extends Model or Ardent.
When you do $thing = DB::Table('todo')->where('id', $request->input('id')); the $thing variable is a collection, not related to a model.
You must make a model for Thing.php then you can do this:
$thing = Thing::where('id', $request->input('id'));
if ( $thing ){
    $thing->done = $request->input('set_as_done');
    $thing->save();
 }

A: save method works on Eloquent model not on builder so your code needs to fire update query instead of save
i would suggest create Eloquent model todo and then write code with save() method which makes more sense than using builder
public function postTodo( Request $request ){
    if ( $request->input('action') == 'set_as_done' ){
        $thing = DB::table('todo')->where('id', $request->input('id'))->first();
        if ( $thing ){
            DB::table('todo')->where('id', $request->input('id'))->update([
                'set_as_done' => $request->input('set_as_done')
            ]);
        }
        return redirect(route('admin.todo'));
    }
}

A: I would suggest you to create model for table todo using php artisan make:model TodoModel.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Todo extends Model{ protected $table = 'todo'; }

After that you can use Todo to save your data.
public function postTodo( Request $request ){
if ( $request->input('action') == 'set_as_done' ){
    $thing = Todo->find('id', $request->input('id'));
    if ( $thing ){
        $thing->set_as_done = $request->input('set_as_done')
        $thing->save();
    }
    return redirect(route('admin.todo'));
}

}


text:
Q: MATE not showing up after install I just used Synaptic to install MATE Desktop Environment on my Ubuntu 14.04 computer.  It installed successfully, but after rebooting, it's not showing up on the login screen.  My only options are to choose from Ubuntu (Default) or XFCE.  Does anyone know why and how do I get MATE to work?

A: Open a terminal and run:
sudo apt-get remove --purge mate-desktop

sudo apt-get autoremove

now add the MATE Official repo, press y when prompted.
sudo apt-add-repository "deb http://repo.mate-desktop.org/archive/1.8/ubuntu trusty main"

sudo apt-get update

then install it:
sudo apt-get install mate-core

sudo apt-get install mate-desktop-environment

sudo apt-get install mate-desktop-environment-extra

sudo reboot

Done.
Now you should be able to see MATE at the login screen.

A: Previous answer is not totally correct. It installs Vanilla MATE, not Ubuntu MATE.
Follow the instructions on install page of MATE desktop project:
sudo apt-add-repository ppa:ubuntu-mate-dev/ppa
sudo apt-add-repository ppa:ubuntu-mate-dev/trusty-mate

sudo apt-get install ubuntu-mate-core ubuntu-mate-desktop

For Ubuntu versions later than 14.04 just simply install these packages, not adding reps (they are already in ubuntu reps).


text:
Q: C# - 2 struct questions I know structs are value types but then I do not understand why this works:
EDIT: I mean, why this.Size.Height does not work then?
struct A
{
    int height;

    public int Height
    {
        get
        {
            return height;
        }

        set
        {
            height = value;
        }
    }
}

//... class Main
{
    A a = A();
    a.Height = 5;  //works. Why? I thought it should say "cannot modify as it is not variable". I think the properties should return copy of this struct...?
}

Second question - I have read I do not need to use "new" with structs but it does not work without it for me.

A: Let me break that down into several questions:

What is a variable?

A variable is a storage location that contains a value.

Why are value types called value types?

The value of a variable of value type is a value, and is copied by value. The value of a variable of reference type is a reference and is copied by reference. That is why value types are called value types and reference types are called reference types.

Why does a.Height = 10 work?

To change the value stored in a variable of reference type, you've got to have a variable to begin with. In this case, you do: you have the variable "a". The compiler compiles that as "pass the managed address of the variable 'a' to the Height setter with the argument 10".  Therefore the Height property setter knows how to find the location of the value stored in 'a' and mutate it.

Why does a.Size.Height = 10 not work?

To change the value stored in a variable of reference type, you've got to have a variable to begin with. The expression "a.Size" is not a variable; it is a value. a.Size does not give you the variable that backs the property -- in fact, there might not be one. Instead, it gives you the value of the property. Value types are copied by value; this is a copy of the value of the property. This means that the compiler has two choices: it can copy the value into a temporary variable and then mutate that variable, tricking you into thinking that you've mutated the backing store of a.Size. Or, it can give you an error indicating that you're doing something foolish. It does the latter.

Isn't this confusing and vexing?

Yes. The moral of the story is do not make mutable value types. Only make immutable value types. Never have a setter on a value type in the first place; only do the assignment in the constructor. If the thing has to be mutable, make it a reference type.

Do I have to use "new" to make a new instance of a value type?

No. You can also use "default":
Foo f = default(Foo);

If Foo is a value type then this fills in the contents of storage location f with the Foo which has all its fields set to their default values.
Or, if the value type is mutable, you can simply set the values of all the fields. However, you have to set all of them if you do not use a constructor or the default initializer. You have to set all of them including private fields.

But if a struct has all public fields doesn't that violate best practices guidelines in two ways? First, because it has public fields, and second, because it is a mutable value type?

Yes. Don't do that.

A: I think you are confusing value types with immutability. I think this SO question will help you.

A: It is very normal. And why you think that it must not let you to set value for  Height ?
It is very normal behavior how properties should work.
Concerning calling new, yes it is not mandatory for value types. For value types it just calls default constructor which just initializes fields with default values.

A: "this.Size.Height = 5" does not work because when a value type is used as the type of a property, the above line of code would actually mean "this.get_Size().set_Height(5)", and the result of the get_Size() call is a copy of the original, being a value type.
Thus, were it allowed by C#, setting the property value to 5 would change the copy's value rather than the original property value, which is highly undesirable.
Of course, this does not apply when the value type property of a class is changed via a local variable, so this scenario can be safely be supported.

A: A property will return the value that its "get" method returns. It's the same for structs and classes. If you provider a "set" method, it will do whatever the "set" indicates. The only way that Height could not be modified would be either to use a private "set", or not provide a "set" at all.


text:
Q: How to convert a set to a list? 'list object is not callable I'm trying to create a list that contains all the values in the 1st list that aren't in the 2nd list. I looked online and found this solution:
list_1=[1,2,3,4,5]
list_2=[2,3]
list_3 = list(set(list_1) - set(list_2))
TypeError: 'list' object is not callable

If I try this without wrapping in in list(), it does return the correct set, but if I try to convert that set to list I get the same type error. How can I convert this set to a list? Or is there another way to accomplish what I'm trying to do?


text:
Q: cropping image on distances using cv2 I'm new to deep learning and image processing but I've implemented the following code for splitting Arabic characters, but my code does not recognize characters and it only finds the whole word.
this is the whole word that is detected by the code
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline

image = cv.imread('hamd.png')
height, width, depth = image.shape
print(image.shape)

image = cv.resize(image, dsize=(width*5, height*4), interpolation=cv.INTER_CUBIC)
print(image.shape)

gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
ret,thresh = cv.threshold(gray,127,255,cv.THRESH_BINARY_INV)

kernel = np.ones((5,5), np.uint8)
img_dilation = cv.dilate(thresh, kernel, iterations=1)

gsblur=cv.GaussianBlur(img_dilation,(5,5),0)

ctrs, hier = cv.findContours(gsblur.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
m = list()
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv.boundingRect(ctr)[0])
pchl = list()
dp = image.copy()
for i, ctr in enumerate(sorted_ctrs):
    x, y, w, h = cv.boundingRect(ctr)
    cv.rectangle(dp,(x-10,y-10),( x + w + 10, y + h + 10 ),(90,0,255),9)
plt.imshow(dp)

now i wondered how can i split the character on the distances between two chars? what i mean looks like the image below:
this is what i want


text:
Q: android: extend the listitem click range I have implemented a ExpanddableListView in my android application, but I'm not happy with the click range of the child items.
The OnCLickListener only gets triggered when I click excactly on the String that is my list item.
How can I extend the click range of the listitem to the whole row?
Here is my layout-xml "selectreasonlist_item.xml":
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:orientation="vertical" android:weightSum="1">

<TextView
        android:id="@+id/lblListItem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="17dip"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
        android:clickable="false" android:focusable="false"/>

</LinearLayout>

In my Activity I have:
@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.selectreason);
    final Context context = this;

    //Get the ListView
    expListView = (ExpandableListView) findViewById(R.id.xlvSelectReason);

    //Preparing list data
    prepareListData();

    listAdapter = new ExpandableListAdapter(this, listDataHeader,listDataChild);

    //Setting list adapter
    expListView.setAdapter(listAdapter);

    //Setting OnClickListener to child item
    expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
                                    int groupPosition, int childPosition, long id) {

       //My Code

            return false;
        }
    });
}

Thanks for your help
Cheers Nik

A: You can attach listener to the list using setOnGroupClickListener and setOnChildClickListener to handle its events to the listeners OnGroupClickListener and OnChildClickListener.

A: I found out that I have to configure android:padding in order to extend the click range.
I added
android:paddingRight="130dp"

to my list_item.xml layout. Solved. ;)


text:
Q: Zsh: remove # - comment when pasting to terminal? I use clipmenu to choose something to paste into terminal that running zsh as shell.
Problem is that zsh will echo error when for example I paste a shell function that contains some # for comments inside that function. I have to manually go back and clear all lines contain #.
System: archlinux/zsh/clipmenu
EDIT: example of function:
test() {
    # must remove this line manually after paste into zsh's shell
    <do something>
}

A: Perhaps you just need to setopt interactivecomments?


text:
Q: How to access storage of a damaged Android phone So appparently Google or my Phone Company decided to change my firmware and my cellphone is there trying to boot but won't do so.
It loads the boot splash screen but it reboots again.
I would like to try to dd it and put Ubuntu Touch but I'm still not into Phone Dev ops. And I'm scared to install Ubuntu SDK phone eeulator along with Intel Microcode.
My phone model is Alcatel Idol 3 4.7"


text: Q: Switching between iframes is not showing me html content I have a site that embeds an iFrame with a sage Pay credit card section.  I am not able to see anything within the iframe via Selenium.  I have tried switching to the actual iframe (using index, web element and name) and then even trying to navigate to its iframe, but I am simply not able to see any of the html within the iframe itself using Selenium.  I can see it within devTools.  I assume Selenium cannot see it because it is secure?  How can I get to the contents of this iframe?


text:
Q: Calculating function time in nanoseconds I need to know how can I calculate the time of a function in C code in nanoseconds.
I tried to repeat the function until consume some microseconds. Are there any other functions in time.h that can be used to calculate the time in nanoseconds?

A: Regardless of how you approach this or what type of system/OS you are using, you are getting an approximate answer at best, with considerable variance due to the nature of the problem.
Second, you need a system that supports this kind of call. It's pretty easy if you're using QNX Neutrino:
http://www.qnx.com/developers/docs/6.3.0SP3/neutrino/lib_ref/c/clock_gettime.html
/*
 * This program calculates the time required to
 * execute the program specified as its first argument.
 * The time is printed in seconds, on standard out.
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

#define BILLION  1000000000L;

int main( int argc, char** argv )
  {
    struct timespec start, stop;
    double accum;

    if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
      perror( "clock gettime" );
      return EXIT_FAILURE;
    }

    system( argv[1] );

    if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
      perror( "clock gettime" );
      return EXIT_FAILURE;
    }

    accum = ( stop.tv_sec - start.tv_sec )
             + (double)( stop.tv_nsec - start.tv_nsec )
               / (double)BILLION;
    printf( "%lf\n", accum );
    return EXIT_SUCCESS;
  }

A: You are never going to get nanosecond accuracy. Think about what you are asking: on a 1 GHz CPU 1 nanosecond is a clock cycle. No matter what you attempt to call, you will never get that kind of accuracy, you are better off sticking to microseconds. A similar question with many examples is here: C++ Cross-Platform High-Resolution Timer.
For c only: on windows you want to use the QueryPerformanceCounter. And here is more on QPC. Here is a related question on how to use QueryPerformanceCounter.

A: The clock function in standard C is not useful for this. It usually has horrible resolution and it's inconsistent (between platforms) whether it measures elapsed wall time or cpu time consumed. You should use the POSIX-standard clock_gettime function (which has nanosecond resolution and lets you specify which clock you want to measure against) and emulate it with whatever system-specific clock operations are available on platforms that lack the POSIX function.

A: Call the function enough times that you get total time in the seconds, and use any method to measure (even plain C clock()).  Measuring in micro/nanoseconds is inherently too imprecise.
For benchmarking, you want QueryPerformanceCounter.  It is the best stopwatch available on Windows.  See: How to use QueryPerformanceCounter?  However using this to measure (for example) a single function call will still be inherently very imprecise; I think you need to time on the order of a second total to get good signal-to-noise ratio for your measurements.  Take multiple measurements of whatever duration you want and compare their value to their standard deviation to make sure you are measuring sufficiently accurately.
Multimedia Timers are probably the best clock (note the difference between clock and stopwatch: one measures absolute time, the other time intervals only) available on Windows.  You should be able to get near-millisecond resolution and precision with timeGetTime().


text:
Q: How to extract yaw pitch roll from glm::quat and glm::mat4 Is it possible to extract the yaw, pitch and roll information from the glm::mat4?
(That is a  world transformation matrix with the translation, rotation and scale already applied)
Here is some code that I'm experimenting with:
    float yawDeg = 0;
    float pitchDeg = 20;
    float rollDeg = 80;

    glm::mat4 transform = glm::eulerAngleYXZ(glm::radians(yawDeg), glm::radians(pitchDeg), glm::radians(rollDeg));

    glm::quat rotation(transform); // Is this a correct way?
 // glm::quat rotation(glm::quat_cast(transform)); // Gives the same results.

    printf("pitch: %f\n", glm::degrees(glm::pitch(rotation))); // Output:   3.616443
    printf("yaw:   %f\n", glm::degrees(glm::yaw(rotation)));   // Output: -19.683496
    printf("roll:  %f\n", glm::degrees(glm::roll(rotation)));  // Output:  79.372414

But I'm getting some strange results, here are some values:
yawDeg=92, pitchDeg=0, rollDeg=0 results yaw: 88.0, pitch: 180.0, roll: 180.0
yawDeg=0, pitchDeg=92, rollDeg=0 results  yaw: 0.0, pitch: 92.0, roll: 0.0 - Looks ok.
yawDeg=0, pitchDeg=0, rollDeg=92 results  yaw: 0.0, pitch: 0.0, roll: 92.0 - Looks ok.
yawDeg=0, pitchDeg=10, rollDeg=92 results  yaw: -9.993845, pitch: -0.352578, roll: 92.030830
I think maybe my glm::mat4 to glm::quat conversion is incorrect?

A: There is one thing I'd like to add. Yaw degree from GLM is actually between −90°~90°. It's because GLM get the yaw angle from arcsine, and −90°~90° is the range of usual principal value you can get from that.
Here you can see a snippet of the code from the github of GLM,
https://github.com/g-truc/glm/blob/master/glm/gtc/quaternion.inl#L41

A: The reason why I was getting those unexpected values was because in certain angles GLM is internally applying it's own angles. I.e for:
Input yawDeg=60, pitchDeg=0, rollDeg=0 we'll get yaw: 60.0, pitch: 0.0, roll: 0.0 - as expected.
And for:
Input yawDeg=92, pitchDeg=0, rollDeg=0 we'll get yaw: 88.0, pitch: 180.0, roll: 180.0 - modified!
If you would look visually at the 3D object with those transformations applied - all rotations should look ok even if GLM have modified the values internally.
Another thing I've noticed is that Euler angles returned by GLM are always in the range of -180, 180 degrees for all axis.
Regarding the glm::mat4 to glm::quat conversion. I was doing everyting ~ok. The important thing to note here is that if you're using scaling in your transformation matrix, you need to normalize your quaternion!
glm::quat rotation = glm::normalize(glm::quat_cast(matrix));

Another thing I found was that GLM has a function called glm::extractEulerAngleXYZ. So if you just want to extract Euler angles from your transformation matrix, you don't really need to do any conversion to the quaternion.
I'm still not fully satisfied, because I did not find any way to convert GLM's Euler angle values back to the original values that were provided by the user.


text:
Q: How can I set process.env from main process inside of an NPM package? I am writing an NPM package that sets environment variables using process.env. Here is the code from the NPM package:
Object.keys(parsedObj).forEach((key) => {
  process.env[key] = parsedObj[key];
});

In this file within the package I console.log process.env and see the variables set correctly. However, when I call this function in my code that imports this function, I console.log process.env and the variables are missing.
For context, here is the entire file: https://github.com/arsood/Cooler-Env/blob/master/loadEnv.js#L33
Does anyone have thoughts as to why these global variables are not available in the main code after running this function? Do modules run their own process? If so, is there a way to write environment variables to the main process from the package?

A: Looks like your function is async and your module exports the function so I would advice you to import the file once in the file when your start your app, and call it and wait for its execution and only then start the rest of your app, otherwise there is no warranty because the code is async.
loadEnv()
     .then(() => {
          initApp(); // Some function that starts rest of the app.
     })


text:
Q: Getting the css id of an element on mouse hover from an extension I'm developing a plugin (extension) that is able to web scrape given a URL and the id of the element. I was wondering if there is a way to get the CSS id of an element from a tab on chrome on hovering the mouse over it. Most of the docs and tutorials show document.getElementById('name'); but here you have to provide the Id so I was wondering if there was any dynamic way of getting it on mouseover.
Any suggestions and reference docs would be of great help. Thanks.


text:
Q: How to add themes? I just picked up python recently and I've been working on a project called "ToDoList.py".It's finished but I want to add a button to change the theme of the GUI using tkinter / ttk but its not working.
This is the error:
Traceback (most recent call last):
  File "todolist.py", line 64, in <module>
    lbl_title = Label(root, text="ToDoList", bg="white")
  File "C:\Users\Sam\AppData\Local\Programs\Python\Python37-32\lib\tkinter\ttk.py", line 761, in __init__
    Widget.__init__(self, master, "ttk::label", kw)
  File "C:\Users\Sam\AppData\Local\Programs\Python\Python37-32\lib\tkinter\ttk.py", line 559, in __init__
    tkinter.Widget.__init__(self, master, widgetname, kw=kw)
  File "C:\Users\Sam\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2296, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: unknown option "-bg"

I don't understand why this error is possible since i haven't adjusted the widgets yet
from tkinter import *

from tkinter import ttk

from tkinter.ttk import *

from ttkthemes import themed_tk as tk

import random

import tkinter.messagebox

#--------root style
root = Tk()
#--------root backgroud
root.configure(bg="white")
#--------root title
root.title("Reminder")
#--------root size
root.geometry("225x300")
#--------create empty list
tasks = []
#--------fuction
def darkmd():
    root.get_themes()
    root.set_theme("equilux")
#--------command
lbl_title = Label(root, text="ToDoList", bg="white")
lbl_title.grid(row=0, column=0)

lbl_display = Label(root, text="", fg="black", bg="white")
lbl_display.grid(row=0, column=1)

txt_input = Entry(root, width=20, fg="black", bg="white")
txt_input.grid(row=1, column=1)

bt_add_task = Button(root, text="Add Task", fg="black", bg="white",         command = add_task)
bt_add_task.grid(row=1, column=0)

bt_del_all = Button(root, text="Del all", fg="black", bg="white", command = del_all)
bt_del_all.grid(row=2, column=0)

bt_del_one= Button(root, text="Del", fg="black", bg="white", command = del_one)
bt_del_one.grid(row=3, column=0)

bt_sort_asc = Button(root, text="Sort (ASC)", fg="black", bg="white", command = sort_asc)
bt_sort_asc.grid(row=4, column=0)

bt_sort_desc = Button(root, text="Sort (DESC)", fg="black", bg="white", command = sort_desc)
bt_sort_desc.grid(row=5, column=0)

bt_total_task = Button(root, text="Num Of Task", fg="black", bg="white", command = total_task)
bt_total_task.grid(row=6, column=0)

bt_darkmd = Button(root, text="Darkmode", fg="black", bg="white", command = darkmd)
bt_darkmd.grid(row=7, column=0)

lb_tasks = Listbox(root,fg="black", bg="white")
lb_tasks.grid(row=2, column=1, rowspan=9)

#--------main
root.mainloop()

A: As an alternative to ThemedTk, you can use ThemedStyle. This way your code will be exactly like if you were using one of the standard ttk themes except that you define your style with style = ThemedStyle(root) instead of style = Style(root). Then you simply use style.theme_use(<theme name>) to change theme and you can list the available themes with  style.theme_names().
from tkinter import ttk
import tkinter as tk
from ttkthemes import ThemedStyle

#--------root style
root = tk.Tk()
#--------root backgroud
root.configure(bg="white")
#--------root title
root.title("Reminder")
#--------root size
root.geometry("225x300")

# white theme
style = ThemedStyle(root)
style.theme_use('arc')  # white style

#--------create empty list
tasks = []

#--------function
def darkmd():
    style.theme_use("equilux")  # only changes the theme of the ttk widgets
    # change style of tk widgets manually:
    bg = style.lookup('TLabel', 'background')
    fg = style.lookup('TLabel', 'foreground')
    root.configure(bg=style.lookup('TLabel', 'background'))
    lb_tasks.configure(bg=bg, fg=fg)

#--------command
lbl_title = ttk.Label(root, text="ToDoList")
lbl_title.grid(row=0, column=0)

lbl_display = ttk.Label(root, text="")
lbl_display.grid(row=0, column=1)

txt_input = ttk.Entry(root, width=20)
txt_input.grid(row=1, column=1)

bt_add_task = ttk.Button(root, text="Add Task")
bt_add_task.grid(row=1, column=0)

bt_del_all = ttk.Button(root, text="Del all")
bt_del_all.grid(row=2, column=0)

bt_del_one = ttk.Button(root, text="Del")
bt_del_one.grid(row=3, column=0)

bt_sort_asc = ttk.Button(root, text="Sort (ASC)")
bt_sort_asc.grid(row=4, column=0)

bt_sort_desc = ttk.Button(root, text="Sort (DESC)")
bt_sort_desc.grid(row=5, column=0)

bt_total_task = ttk.Button(root, text="Num Of Task")
bt_total_task.grid(row=6, column=0)

bt_darkmd = ttk.Button(root, text="Darkmode", command=darkmd)
bt_darkmd.grid(row=7, column=0)

lb_tasks = tk.Listbox(root, fg="black")
lb_tasks.grid(row=2, column=1, rowspan=9)

#--------main
root.mainloop()

Clear theme:
Dark theme:
Note that only the ttk widgets become dark after setting the theme to "equilux". So you need to manually change the colors of your tk widgets in darkmd() (like I did for root and lb_tasks).

A:
Comment: HowTo using: ttkthemes

To use ttkthemes change to the following:
No style.theme_use(... statement, as this is alredy done in __init__(....
from ttkthemes import ThemedTk

class App(ThemedTk):
    def __init__(self):
        super().__init__("equilux")

        # ATTENTION!!
        # The following could fail as i couldn't test with `ThemedTk`
        # ATTENTION!!
        style = ttk.Style(self)
        style.configure("TLabel", background="white")

Question: How to add themes?

First you have to understand, not to mix tkinter and tkinter.ttk widgets in a uncontrolled way. Only tkinter.ttk widgets can be styled using theme and style.

*

*TkDocs - Tk Tutorial - Styles and Themes

*tkinterbook - Widget Styling

*

*Use only the following common import statements
import tkinter as tk
import tkinter.ttk as ttk

*To instantiate a ttk widget use:

Note: You can't use bg= on a ttk widget!

lbl_title = ttk.Label(root, text="ToDoList")

*Application wide usage:

Note: It's important to do all style definition once and before any widget instantiation.

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        style = ttk.Style(self)
        style.theme_use('clam')
        style.configure("TLabel", background="white")

        self.title("Tkinter Style")
        self.geometry("225x300")

        lbl_title = ttk.Label(self, text="ToDoList")
        lbl_title.grid(row=0, column=0)

if __name__ == "__main__":
    App().mainloop()

Tested with Python: 3.5

A: After reading your comment, I thought my input may help.
First, identify your OS. Windows/Mac
Second, open IDLE and then open IDLE preferences
You will see the settings and in "Highlights", below the radio buttons for the themes, you will see a drop box that allows you to switch your themes from IDLE Dark to Classic and New!


text:
Q: Is Sharepoint 2003/MOSS 2007 able to return a document snippet containing search terms? Is there a search API for getting a short text containing the search terms so that I can use to display to users?

A: There's properties that can be returned from a search - HitHighlightedSummary & HitHighlightedFields.
If you're building a search in code you can request these in the same way as other fields - they should contain what you're after.
If you take a look at the configuration for the standard results web part, you can see there's an XML property which is the fields requested which includes these by default.

A: Not sure exactly what you mean, but you could traverse through all managed and / or crawled properties? for more information look here MSDN
Examples from the referenced page:
Managed Properties:
Schema schema = new Schema(this.searchContext);
foreach (ManagedProperty prop in schema.AllManagedProperties)
{
  TreeNode node = treeViewManagedProperties.Nodes.Add(prop.Name);
  node.Tag = prop;
  foreach (Mapping mapping in prop.GetMappings())
  {
   node.Nodes.Add(mapping.CrawledPropertyName);
  }
}

Crawled Properties
Schema schema = new Schema(this.searchContext);
foreach (CrawledProperty cprop in schema.QueryCrawledProperties(string.Empty, 1000, Guid.NewGuid(), string.Empty, true))
{
  listBoxCrawledProperties.Items.Add(cprop);
}

EDIT: This is for MOSS BTW


text:
Q: Function to toggle visibility of tableLayout in android not working I have a button in my XML, that when clicked will toggle the visibility of my TableLayout. This is the XML,
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/LayoutAddOns"
        android:orientation="vertical" >

            <!-- Accordion button -->
            <Button
                android:id="@+id/DisplayAddOns"
                android:layout_width="335dp"
                android:layout_height="35dp"
                android:drawableLeft="@drawable/rarrow"
                android:onClick="ShowAddons"
                android:text="AddOns (Optional)" />
            <!-- Table for add ons -->
              <TableLayout
                android:id="@+id/tableAddOns"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" >

                        <TableRow
                            android:id="@+id/tableRow1"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                             >

                            <CheckBox
                                android:id="@+id/CheckGalleryPlus"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="10dp"
                                android:text="Gallery Plus"
                                android:textSize="14sp" />

                            <CheckBox
                                android:id="@+id/CheckSubtitle"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="10dp"
                                android:text="Subtitle"
                                android:textSize="14sp" />

                        </TableRow>
                        <TableRow
                            android:id="@+id/tableRow2"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content" >

                            <CheckBox
                                android:id="@+id/CheckDesigner"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="10dp"
                                android:text="Designer"
                                android:textSize="14sp" />

                            <CheckBox
                                android:id="@+id/CheckSupersize"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="10dp"
                                android:text="Supersize"
                                android:textSize="14sp" />

                        </TableRow>

                        <TableRow
                            android:id="@+id/tableRow3"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content" >

                            <CheckBox
                                android:id="@+id/CheckScheduled"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="10dp"
                                android:text="Scheduled"
                                android:textSize="14sp" />

                            <CheckBox
                                android:id="@+id/CheckInternationalVisibility"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="10dp"
                                android:text="International Visibility"
                                android:textSize="14sp" />

                        </TableRow>

                        <TableRow
                            android:id="@+id/tableRow4"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content" >

                            <CheckBox
                                android:id="@+id/CheckBold"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="10dp"
                                android:text="Bold"
                                android:textSize="14sp" />

                            <CheckBox
                                android:id="@+id/CheckHighlight"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="10dp"
                                android:text="Highlight"
                                android:textSize="14sp" />

                        </TableRow>

                        <TableRow
                            android:id="@+id/tableRow5"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content" >

                            <CheckBox
                                android:id="@+id/CheckFeaturedList"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="10dp"
                                android:text="Featured List"
                                android:textSize="14sp" />

                            <CheckBox
                                android:id="@+id/CheckFeaturedPlus"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="10dp"
                                android:text="Featured Plus"
                                android:textSize="14sp" />

                        </TableRow>

            </TableLayout>

    </LinearLayout>

This is the data from LogCat,
04-03 01:21:52.891: D/AndroidRuntime(408): Shutting down VM
04-03 01:21:52.891: W/dalvikvm(408): threadid=1: thread exiting with uncaught         exception (group=0x40014760)
04-03 01:21:52.911: E/AndroidRuntime(408): FATAL EXCEPTION: main
04-03 01:21:52.911: E/AndroidRuntime(408): java.lang.IllegalStateException: Could not find a method ShowAddons(View) in the activity class toggler.state.TogglerActivity for onClick handler on view class android.widget.Button with id 'DisplayAddOns'
04-03 01:21:52.911: E/AndroidRuntime(408):  at android.view.View$1.onClick(View.java:2670)
04-03 01:21:52.911: E/AndroidRuntime(408):  at android.view.View.performClick(View.java:3110)
04-03 01:21:52.911: E/AndroidRuntime(408):  at android.view.View$PerformClick.run(View.java:11934)
04-03 01:21:52.911: E/AndroidRuntime(408):  at android.os.Handler.handleCallback(Handler.java:587)
04-03 01:21:52.911: E/AndroidRuntime(408):  at android.os.Handler.dispatchMessage(Handler.java:92)
04-03 01:21:52.911: E/AndroidRuntime(408):  at android.os.Looper.loop(Looper.java:132)
04-03 01:21:52.911: E/AndroidRuntime(408):  at android.app.ActivityThread.main(ActivityThread.java:4123)
04-03 01:21:52.911: E/AndroidRuntime(408):  at java.lang.reflect.Method.invokeNative(Native Method)
04-03 01:21:52.911: E/AndroidRuntime(408):  at java.lang.reflect.Method.invoke(Method.java:491)
04-03 01:21:52.911: E/AndroidRuntime(408):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
04-03 01:21:52.911: E/AndroidRuntime(408):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
04-03 01:21:52.911: E/AndroidRuntime(408):  at dalvik.system.NativeStart.main(Native Method)
04-03 01:21:52.911: E/AndroidRuntime(408): Caused by: java.lang.NoSuchMethodException: ShowAddons [class android.view.View]
04-03 01:21:52.911: E/AndroidRuntime(408):  at java.lang.ClassMembers.getConstructorOrMethod(ClassMembers.java:235)
04-03 01:21:52.911: E/AndroidRuntime(408):  at java.lang.Class.getMethod(Class.java:904)
04-03 01:21:52.911: E/AndroidRuntime(408):  at android.view.View$1.onClick(View.java:2663)
04-03 01:21:52.911: E/AndroidRuntime(408):  ... 11 more

and this is the Java code,
    public void ShowAddons(){

    int TableId = R.id.tableAddOns;

    TableLayout TableVisibility = (TableLayout)findViewById(TableId);

    if(TableVisibility.getVisibility() == View.VISIBLE)
    {
        TableVisibility.setVisibility(View.GONE);
    }

    else
    {
        TableVisibility.setVisibility(View.VISIBLE);
    }

}

It has no errors in eclipse, but when I run it, it says am error has occured and force closes the application. Thanks.

A: Try making ShowAddOns() take a View argument, as ShowAddOns(View target), even if you don't use the target view in the method.


text:
Q: How to extract specific lines from a .txt file in R and store it in a vector I am working with a transcript of a show and would like to extract the text of each speaker and store it into its own vector. The data looks like this -
BOB: blah blah blah blah

TRUDY: blah blah

BOB: you get the idea however some of the text  is on a new line like

this so I don't know how to extract it to the correct vector

TRUDY: blah blah blah

.. and so on.
I imagine I need to use a combination of readLines and grep however I am not sure how to implement it.

A: Interesting problem. Not sure this is exactly the output you need, but it should give you a good idea.
text <-
"BOB: blah blah blah blah
TRUDY: bleh bleh
BOB: you get the idea however some of the text is on a new line like
this so I don't know how to extract it to the correct vector
TRUDY: bleh bleh bleh
BOB: Durrh!!!"

# Replace line feeds with spaces
text <- gsub(pattern = "\\n", replacement = " ", x = text)

# Split string into words to find alternations of BOB / TRUDY
who <- strsplit(x = text, split = " ")[[1]]
who <- who[who %in% c("BOB:", "TRUDY:")]

# Split string using BOB: and TRUDY:
dialog <- strsplit(x = text, split = "(BOB: )|(TRUDY: )", perl = TRUE)[[1]][-1]

# create the two final vectors
bob <- trimws(dialog[which(who=="BOB:")])
trudy <- trimws(dialog[which(who=="TRUDY:")])

RESULTS
> bob
[1] "blah blah blah blah"
[2] "you get the idea however some of the text is on a new line like  this so I don't know how to extract it to the correct vector"
[3] "Durrh!!!"
> trudy
[1] "bleh bleh"      "bleh bleh bleh"

A: Suppose text contains your data. Then try this
text <- readlines("data.txt")
pos <- which(stringr::word(text,1,1) %in% c("BOB:","TRUDY:"))
mapply(function(x,y){do.call(paste,as.list(text[x:y-1]))},pos,c(pos[-1],length(text)+1))


text:
Q: Enemy character is being overdrawn by game's background I am working on a game which spawns enemies. Though once these enemies are spawned, they instantly disappear again because the background is drawn on top of them.
Is there a way to have a layer system in Pygame?
Code to recreate the problem:
import pygame
import threading
from random import randint
from time import sleep

pygame.init()
window = pygame.display.set_mode((900, 900))
bg=pygame.image.load("Background.png").convert()

def Gameplay():
    while True:
        window.blit(bg, [0,0])
        pygame.display.update()

def spawn_enemy():
    enemyW = 50
    enemyH = 50
    enemyX = 420
    enemyY = 850
    pygame.draw.rect(window, (93,124,249),(enemyX,enemyY,enemyW, enemyH))
    print("an enemy has been spawned")
    return True # would be "return enemy" after you create your enemy entity

def EnemySpawn():
    enemy_list = [] # to maintain records of all enemies made
    while True: # make enemies forever
        sleep(randint(1,5))
        enemy_list.append(spawn_enemy()) # call our function we made above which spawns enemies

Gameplay = threading.Thread(target=Gameplay)
Gameplay.start()
EnemySpawn = threading.Thread(target=EnemySpawn)
EnemySpawn.start()

A: I do not understand pygame and it for some reason becomes generally unresponsive when I run this, but it does generate enemies and show how one would implement a class to store their variables (perhaps a pygame expert could edit it to become responsive or comment what my code is doing that makes the window "freeze up"):
import pygame
import threading
from random import randint
from time import sleep
import random

pygame.init()
window = pygame.display.set_mode((900, 900))
bg = pygame.image.load("Background.png").convert()

class Enemy:
    def __init__(self):
        self.W = random.randint(30, 50)
        self.H = random.randint(30, 50)
        self.X = random.randint(0, 900)
        self.Y = random.randint(0, 900)

def Gameplay():
    global enemy_list
    while True:
        window.blit(bg, [0, 0])
        for enemy in enemy_list:
            pygame.draw.rect(window, (93, 124, 249), (enemy.X, enemy.Y, enemy.W, enemy.H))
        pygame.display.update()

def EnemySpawn():
    global enemy_list
    while True: # make enemies forever
        sleep(randint(1, 5))
        print("Spawned an enemy")
        enemy_list.append(Enemy()) # make an instance of our class

enemy_list = [] # to maintain records of all enemies made
game_thread = threading.Thread(target=Gameplay)
game_thread.start()
enemy_spawner_thread = threading.Thread(target=EnemySpawn)
enemy_spawner_thread.start()

The key points to note are the use of enemy_list being in the global space and then calling it into functions with global enemy_list so they are accessing the same list object. The class does essentially the same thing you were doing in your function, but gives the enemies random spawn points. As @Rabbid pointed out, you need to draw the enemies in the same part of your code that draws the background.
P.S. You should not use Gameplay = threading.Thread(target=Gameplay) as this overwrites your function. I've implemented a different variable for the thread in my code


text:
Q: Update row in DataTables table without refresh page I have a problem with my script.
In my table, every row has a url link which open modal window with email input to change this email without refresh page.
Script is ok if you change only one row. If I change second, third, etc row, every values changed by last one.
If I refresh page (F5) - script works perfectly.
Any helps ? Thanks a lot.

$(document).ready(function() {
  var table = $('#example').DataTable();

$('#example tbody').on('click', 'a', function () {
  var row = $(this).closest('tr[role="row"]');
  var data = table.row(row).data();

  $("#myModal").modal("show");
  $("#email").val(data[0]);

  $("#ulozit").click(function(){
    var novy_email = $("#email").val();
     $.ajax
         ({
             method: "POST",
          url: "action_admin.php?action=uprava_emailu",
          data: { novy_email:novy_email, id:data[3] },
            success: function(data)
      {
       table.ajax.reload();
       $("#myModal").modal("hide");
      }
         })
    });
  });
});

A: You have nested onClick handlers.
The second handler is added every time the first handler is called. The jQuery event model allows multiple handlers on one element, therefore a later handler does not override an older handler. The handlers will execute in the order in which they were bound.
In short: Do not nest your handlers.


text:
Q: Probability of meeting someone infected Let's take Italy as an example. There are $60,360,000$ citizens out of which are currently $95,262$ infected. What is the probability that when you randomly pick $100,000$ citizens of Italy, there will be at least one infected?
I started like this: $\frac{60,360,000}{95,262} = 633.6$. This means that every $633.6$-th citizen of Italy is infected. So when considering all citizens, there is a chance of $\frac{95,262}{60,360,000} \cdot 100 = 1.58 \%$ meeting someone infected. So what about the chances out of $100,000$?
My guess was that $100,000$ is $603.6$ times smaller, so the probability would be also $603.6$ time smaller, meaning $\frac{1.58}{603.6}=0.0026 \%$. Is that a correct assumption?

A: No, it's a repeated experiment, (I'll assume, independent) the chance that none are infected is $(1- \frac{I}{N})^n$, where $I$ is the number of infected, $N$ the total population, and $n$ the sample size. This binomial chance is a good approximation for the hypergeometric one here, due to the large numbers involved. So at least one is $1 - (1- \frac{I}{N})^n$, which is pretty close to $1$ I think.

A: First of all you should use the converse probability. $P(X\geq 1)=1-P(X=0)$.
Since the sample is not very large we can assume approximately the probability $p=\frac{95,262}{60,360,000}=0.00157823\approx 0.157823\%$. Here you missed a $0$.
Then $P(X\geq 1)=1-(1-0.00158)^{100000}=1-\left(1- \frac{157.82}{100000}\right)^{100000}$
This is approximately $\boxed{1-e^{-157.82}}=1-0=1$

A: This is a relatively straightforward binomial distribution. First, find the probability of encountering an infected individual:
\begin{equation}
\frac{95262}{60360000} \approx .1578\%
\end{equation}
Then, you can take the binomial probability mass function
\begin{equation}
\begin{pmatrix}
n \\
k
\end{pmatrix}
 p^kq^{n-k}
\end{equation}
where $n$ is the total population you encounter, $k$ is the number of infected individuals you encounter, $p$ is the probability of encountering an infected individual, and $q$ is the probability of encountering an uninfected individual.
If you want to find the probability of encountering exactly one infected individual, do:
\begin{equation}
\begin{pmatrix}
100 \\
1
\end{pmatrix}
(.001578)^1(1-.001578)^{99}
\end{equation}
But note that this is not the result you asked for. You wanted the chance of encountering at least one infected individual. So, to find that result using this method, you would need to add the probability of encountering exactly one infected individual, and the probability of encountering exactly two infected individuals, and the probability of infecting at least three, etc. until you have the chance that you encounter one, or two, or three, etc. infected individuals (which is the same as the probability of encountering at least one infected person).
However, this route is obviously a complete pain. So instead, I recommend thinking about the chance that you encounter exactly zero infected individuals. What would this result look like and how would it be relevant to your question?
Hope this helps!


text:
Q: JQuery.Validate CDN fallback A bit of a follow on from this question:
Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail
So I can detect if the JQuery CDN is down and allow for this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
        <script type="text/javascript">
            if (typeof jQuery == 'undefined') {
                document.write(unescape("%3Cscript src='/Script/jquery-1.7.2.min.js' type='text/javascript'%3E%3C/script%3E"));
            }
</script>

How do I do the same for jquery.validate, when loaded as:
<script type="text/javascript" language="javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>

A: Something like this could do the trick
<script type="text/javascript" language="javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>
<script type="text/javascript">
    if (typeof jQuery().validate == 'undefined') {
        document.write(unescape("%3Cscript src='/js/jquery.validate.min.js' type='text/javascript'%3E%3C/script%3E"));
    }
</script>

A: Use this instead:
if(typeof $().validate == 'undefined')
{
    /// same code as before except pointing at your local jQuery.validate path
}

DEMO - Check if validate exists
Returns true in the console if it exists and false if not.
Remove the script reference in the DEMO to get false as output.
Your complete code may look similar to this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>

<script type="text/javascript">
    if (typeof jQuery == 'undefined') {
        document.write(unescape("%3Cscript src='/Script/jquery-1.7.2.min.js' type='text/javascript'%3E%3C/script%3E"));
    };

    if (typeof $().validate == 'undefined') {
        document.write(unescape("%3Cscript src='/Script/jquery.Validate-1.6.min.js' type='text/javascript'%3E%3C/script%3E"));
    }
</script>


text:
Q: Wierd font in Javascript alert Google Chrome We have a plain text message being output in a javascript alert() popup for form errors on our system. For some reason Google Chrome is displaying part of it in a weird font, as seen in the image below.

Does anyone know why?
The plain text is:

"___________________________________________________________________

The form was not submitted because of the following error(s).
Please correct these error(s) and re-submit the form.
___________________________________________________________________

- The following required field(s) are empty:
    Title
    Company
"

A: Google Chrome appears to do this on certain OS's when a line is preceded by a tab (\t)

alert("Normal text\r\n\tPreceeded by a tab");

Which is supersonically bizarre behaviour - no other browser does that.
At least its not a 6 year old bug oh.wait.fail!


text:
Q: Updating a scheduled task with 'repeat every x hours' causes it to be triggered on Windows 10 Synopsis
I have a scheduled task that runs a program with highest privileges every 4 hours. On Windows 10 version 1803 (build 17134.81), any update to this task causes it to be triggered as soon as the task is saved. The task is triggered even if the update is to disable the trigger! Disabling the 'run every x hours' clause seems to be the only way to get around this issue. However, saving the same task on Windows 7 (SP1) does not trigger it.
Details
Updating a task logs event #140 (task registration updated) in the task history. At the same instant, event #107 (task triggered on scheduler) is logged and the task starts up:
Link to event history screenshot

The 'run task as soon as possible after a scheduled start is missed' option on the Settings tab does not have any effect on this behavior.
Has anyone else come across this issue? Please suggest a reasonable workaround that does not cause the task to be triggered as soon as it is saved.

A: Prevent a Task Scheduler Task from Executing on Setting Updates
Set the Edit Trigger to run at an interval of One Time and then in Advanced settings section, select Repeat task every 4 hour with for a duration of indefinitely but be sure the Start time up top is the time which you want this task to first be run.

Note: A key point here is to be sure the Start time is the exact time you want the process to run the first time but of a prior date and then it'll run first starting only at that time.

Furthermore, from the Settings tab you might also uncheck the Run task as soon as possible after a scheduled start is missed as this can cause this problem as well.