text:
Q: Django DB data to HTML table Ok, this is more or less "present sparse data having two foreign keys in a table, key1 in rows and key2 in columns". Common enough thing to do, I imagine, but with a wee twist.
In Django, I need to make a page with semester score for a group of students. It should look like this:

          Cryptography intro  |    Discrete Math     | ...
         Chkpt1 Chkpt2 Chkpt3 | Chkpt1 Chkpt2 Chkpt3 | ...
Alice      15     26    47    |   10     20     -    | ...
Bob        25     54    73    |   25     54     -    | ...
Chuck      33     66    99    |   33     60     -    | ...
...

Students in a group all take the same courses, and the school has defined 3 checkpoints during each semester when all instructors report the scores. Some columns may not be filled yet if the instructor has not yet turned in the scores (Chkpt3 in Discrete Math in the example above).
Model for a Grade references Student, Course, and Checkpoint. Checkpoint references Semester. Students reference Group.
Problem is how to pass data to the template. I get data from the DB with
reportgrades = Grade.objects.filter(student__group__id=group_id,
                                    checkpoint__semester=semester)

Then I:

*

*go create nested dict gr[studid][courseid][chkptid] in a nested loop, fill it with dashes,

*loop over reportgrades to put values into this dict, overwriting dashes where grades exist,
no_grade = u'—'
grades = {}
for student in students:
    grades[student.id] = {}
    for course in courses:
        grades[student.id][course.id] = {}
        for chkpt in checkpoints:
            grades[student.id][course.id][chkpt.id] = no_grade

for g in reportgrades:
    grades[g.student.id][g.course.id][g.checkpoint.id] = g.points

*create custom template tag to extract these,
@register.filter
def getitem ( item, param1 ):
    return item.get(param1)

*use this inside a 3-nested for in the template
{% for s in students %}

    {{ s }}
    {% for c in courses %}
        {% for tp in test_periods %}
        {{ grades| getitem:s.id | getitem:c.id | getitem:tp.id }}
        {% endfor %}
    {% endfor %}

{% endfor %}

That's an awful lot to do to get a simple table, is it not? I've considered a linear list of size 3 x NUM_STUDENTS x NUM_COURSES. Not very pretty, either. A better way?

A: Keep your template code as simple as possible, as RickyA suggests.  Do complicated data transformations in your view instead.
Since you have headers on the tops and sides, I would store these in their own lists.  Then I would store the actual data in a list of lists.  So for instance, in your view code:
student = Student.objects.all()
context['classes'] = [class.name for class in Class.objects.all()]
context['checkPoints'] = range(1, 4)
context['data'] = ...

(code to flatten checkpoints for each students in to flat list,
then make list of these lists, don't forget to add the student
name as the first item in each row)

And in your template, you do something like

{% for class in classes %}
{{ class }}
{% endfor %}

{% for row in data %}

{% for item in row %}
{% if not forloop.counter0 %}
{{ item }}
{% else %}
{{ item }}
{% endif %}
{% endfor %}

{% endfor %}

I think that is valid Django template code.  I've been using Jinja2 lately, so my apologizes if I threw in a feature that doesn't work, but it should be okay.


text:
Q: Editing Title of Existing Custom Option I have configurable products with options.  I simply want to change the title of that option, but can't find a field where it is editable. Is this possible?

A: In the AdminInterface
Stores -> Attributes -> Product simply search for your attribute and click on it. this will open the edit view.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add a condition inside criteria in excel? As an example, I want to have an averageIf and inside one of the criterias, criteria_range: H:H I want inside criteria a condition such as TEXT(H;"mmm") = "Jan" to extract the month. Also tried something else but didn't work either:
'=AVERAGEIF(TEXT(H:H;"[$-409]mmm"); "Jan"; K:K)
Any idea?
Thanks,


text:
Q: Obter linha de um ficheiro Estou a ler um ficheiro txt em PHP, e pretendo obter a primeira linha e a ultima linha para poder escrever. Utilizei este codigo para ler todo o ficheiro linha a linha. Mas o que pretendo é so umas linhas.
$fp = fopen($fichier,"r");

if ($fp) {

    while (!feof($fp)) {
        $texte = fgets($fp);

        if(strpos($texte,"--") === false )
        {}
        else {
            $titre = $texte; /
            echo $titre."<br>";
        }

    }
fclose($fp);}

A: A 1a linha é fácil, basta usar fgets como vc já está usando. Pra pegar a última linha sem ter que ler todo o arquivo use a classe ReverseFile desta resposta do Stackoverflow em inglês aqui:
https://stackoverflow.com/questions/3234580/read-a-file-backwards-line-by-line-using-fseek

A: Use a função file.
Ex:
<?php
$linhas = file('arquivo.txt');

Essa função te retorna o conteúdo do arquivo com uma linha por entrada do array. A partir daí é só manipular a linha que você quiser por meio do índice do array e depois reescrever o arquivo com o conteúdo do array (se for o caso):
<?php
file_put_contents('arquivo.txt', implode(PHP_EOL, $linhas));

A: Seguindo o seu próprio exemplo, uma maneira de se fazer o processo seria criar uma função e pegar a linha especifica configurando os argumentos da função.
No caso usei um array para definir as linhas que você necessita capturar.
A função retorna um array, pois é melhor para você poder organizar.
Descrição:
array getLines ( mixed $handle , array $lines)

*

*$handle Pode ser uma string com o caminho do arquivo ou um resource retornado de um fopen

*$lines Deve ser um array com as linhas especificadas

A função:
function getLines($context, $lines) {
    $isResource = false;

    if (is_resource($context)) {
        //Você pode definir um resource ao invés de um "path"
        $fp = $context;
        $isResource = true;
    } else if (is_file($context)) {
        $fp = fopen($context, 'r');
    } else {
        return false;
    }

    $i = 0;
    $result = array();

    if ($fp) {
        while (false === feof($fp)) {
            ++$i;
            $data = fgets($fp);
            if (in_array($i, $lines)) {
                $result[] = $data;
            }
        }
    }

    //Pega última linha
    if ($i !== 1 && in_array('last', $lines)) {
        $result[] = $data;
    }

    if ($isResource === true) {
        //Não fecha se for resource, pois pode estar sendo usada em outro lugar
        $fp = null;
    } else {
        fclose($fp);
    }
    $fp = null;

    return $result;
}

Exemplos:
Lendo linhas 1 e 2 de um arquivo:
print_r(getLines('/home/user/test.txt', array(1, 2)));

Lendo linhas 3, 6, 11, 12 e 13 de um resource:
$res = fopen('data.txt', 'r');
print_r(getLines($res, array(3, 6, 11, 12, 13)));
...
fclose($res);

Lendo a primeira e a ultima linha:
print_r(getLines('/home/user/test.txt', array(1, 'last')));


text:
Q: ElasticSearch phrase suggestor randomly returns 0 results I'm running ElasticSearch 2.3.5 on OS X, using the Node.JS client. Sometimes the _suggest endpoint returns 0 results -- this occurs at random, for example in a test suite where only four documents are indexed.
Is there any reason why the suggestor would return 0 results? This is causing my tests to fail about 50% the time.
The test suite goes through the following steps:

*

*Create a new, blank index

*

*Supply a mapping for a document where title: {type: 'string'}

*Inject four documents with a title field using the _bulk API.

*

*I am passing refresh=true to ensure the documents are indexed.

*A simple test queries the documents. They are all there.

*Request suggestions for an obvious misspelling. 50/50 chance of pass or fail
I will create a self-contained example app to prove this if nobody can suggest anything obvious.
One observation: Lowercase misspellings (eg. alhpa for alpha have 100% success; the failures only occur when introducing creative misspellings like viTOR for victor. Quite possibly I could be imagining this behaviour, though, because the errors have been coming and going...)

Additional: Here's the wrapper function I've written for the ElasticSearch API:
didYouMean(input) {
  return this.conn.suggest({
    index: this.indexName,
    type: 'customdoc',
    body: {
      titles: {
        text: input,
        phrase: {
          field: 'title',
          direct_generator: [{
            // Only needs to be one character
            // long to suggest a correction
            field: 'title',
            suggest_mode: 'always',
            min_word_length: 1,
          }],
          highlight: {
            pre_tag: '',
            post_tag: '',
          },
        },
      },
    },
  });
}

A: Suggestions are computed per shard.
How many shards do you have in this index?
If more then 1, could you check if it happens on the index with one shard?


text:
Q: Emacs uses dvi2tty  instead of evince to open dvi I started to use emacs for LateX editing again. Back in the days, it was configured automatically that C-c C-f would open the corresponding *.dvi file with evince. With the latest version of emacs, it does not do the same. Is there a way to open the doc with evince? (I am sure there is a way. It is emacs afterall).
Thanks!

A: I use this code with auctex-mode:
;; use evince for dvi and pdf viewer
;; evince-dvi backend should be installed
(setq TeX-view-program-selection
      '((output-dvi "DVI Viewer")
        (output-pdf "PDF Viewer")
        (output-html "Google Chrome")))
(setq TeX-view-program-list
      '(("DVI Viewer" "evince %o")
        ("PDF Viewer" "evince %o")
        ("Google Chrome" "google-chrome %o")))

You didn't mention if you're using auctex-mode or the old latex-mode that comes bundled with Emacs.

A: Depending on whether you are using AUCTeX or emacs' default LaTeX mode there are different configuration options to set this. I would suggest you have a look at them with customize-browse since the config strings can be pretty dense.
With AUCTeX
Browse to Emacs > Wp > Tex > AUCTeX > Tex Command > TeX View > TeX View Program Selection. Change the output-dvi viewer.
Plain LaTeX mode
Browser to Emacs > Wp > Tex > Tex View > Tex Dvi View Command.
Also, instead of directly hardcoding evince I would suggest putting xdg-open there and configuring your preferred dvi-viewer in your desktop environment. Then you need to worry about only one place to configure this in the future.

A: I had the same problem even with the correct settings for view commands. I had started the Emacs daemon from a shell inside screen. I then connected to the server with emacsclient using an X window. AucTeX checks two settings to see if you're using a window system and both are nil or undefined (the $DISPLAY variable and (window-system)) inside screen where I started the server.
So in my case, starting the Emacs daemon from a shell running in an X window solved the problem.
I guess it would help if AucTeX checked the variables for each Emacs frame separately because it shouldn't matter where the server was started but what kind of client (tty or X) you use AucTeX in.


text:
Q: Instabot won't download_photo() So I want to make a script (just for fun) that downloads all the pictures of a given user (that has accepted my follow request of course).. It says "downloading photo:" at some point but then it breaks.. here is the code :
bot = instabot.Bot()
bot.min_likes_to_like = 0
bot.max_likes_to_like = 1e3

username = instabot_settings.USERNAME
password = instabot_settings.PASSWORD

if bot.login(username=username, password=password):
    # main script
    user_name = input("Enter someones username to get their photos")
    user_id = bot.get_user_id_from_username(user_name)
    user_medias = bot.get_user_medias(user_id)

    os.mkdir(user_name + '_photos')

    for media in user_medias:
        post = media.split('_')[0]
        bot.download_photo(post , user_name + '_photos')

Any ideas what is going on ?
-Thanks!


text:
Q: How to Cache Spring JPA Pagination Count Data? I'm Creating a Simple Spring Boot application with JPA. I have millions of records to retrieve it from a database. in my repository when I call findAll(Pageable pageable) it gets the records I want.
But takes lot of time to return me the subset of records. I found it happening because of count query.
Is there a way we can cache the page response after first call ?


text:
Q: How to test a controller with steps to use some action In my system, I have a user that have one company that have multiple accounts.
User sign in system using Devise, and have a virtual attribute called selected_company that was setted in CompaniesController.
I want to make multiple tests in AccountsController with this scenario.
I have this code to sign_in user, this code works well:
before :each do
  @user = create(:user)
  @user.confirm!
  sign_in @user
end

But I must to have a specific context that I tried to code as:
context 'when user already selected a company' do
  before :each do
    @company = create(:company)
    @account = create(:account)
    @company.accounts << @account
    @user.selected_company = @company
  end

  it "GET #index must assings @accounts with selected_company.accounts" do
    get :index
    expect(assigns(accounts)).to match_array [@account]
  end
end

But this code won't work, when I run it I got this error:
undefined method `accounts' for nil:NilClass

My AccountsController#index have only this code:
def index
  @accounts = current_user.selected_company.accounts
end

I'm new in rspec and TDD and I have some time to test everything I want, and I want to test everything to practice rspec.
I don't know if this is the best way to test this things, so I'm open to suggestions.

A: Replace with:
expect(assigns(:accounts)).to match_array [@accounts]

Note, :accounts instead of just account.
Also, as I see it, you don't have @accounts in your spec. Please declare that, too. :)

A: Probably you are not saving selected_company and when you call this on your controller it returns nil.
Try save @user.save after set selected_company:
context 'when user already selected a company' do
  before :each do
    @company = create(:company)
    @account = create(:account)
    @company.accounts << @account
    @user.selected_company = @company
    @user.save
  end

  it "GET #index must assings @accounts with selected_company.accounts" do
    get :index
    expect(assigns(accounts)).to match_array [@account]
  end
end

Hope to help you.

A: Finaly, I found the problem!
I changed the before statement to:
before :each do
  @company = create(:company)
  @account = create(:account)
  @company.accounts << @account
  controller.current_user.selected_company = @company
end

And changed assigns(accounts) to assings(:accounts) (with symbol) in expect method.


text:
Q: raise NotSupported("Response content isn't text") - scrapy.exceptions.NotSupported: Response content isn't text I have the same error since few days. I can't solve it!! I really don't understand where my code isn't correct. I already solved a error message like that before by changing the 'link' part but now, it's not working anymore. Somebody can help me please?
# -*- coding: utf-8 -*-
import scrapy
import re
import numbers
from amazon_test.items import AmazonTestItem
from urllib.parse import urlparse
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class AmazonSellersSpider(CrawlSpider): #scrapy.Spider
    name = 'AmazonFR'
    allowed_domains = ['amazon.fr']
    start_urls = ['https://www.amazon.fr']

    rules = (
        Rule(LinkExtractor(allow=()), callback='parse'),
    )

    def parse(self, response):
        item = AmazonTestItem()
        link = (response.xpath('//div[@class="a-column a-span6"]/h3[@id="-component-heading"]/text()'))
        if link:
            wait = response.xpath('//div[@class="a-column a-span6"]/h3[@id="-component-heading"]/text()').extract()
            if (len(wait) != 0):
                name = response.xpath('//div[@class="a-row a-spacing-medium"]/div[@class="a-column a-span6"]/ul[@class="a-unordered-list a-nostyle a-vertical"]/li//span[@class="a-list-item"]/span[contains(.,"Nom")]/following-sibling::text()').extract()
                phone = response.xpath('//div[@class="a-column a-span6"]/ul[@class="a-unordered-list a-nostyle a-vertical"]/li//span[@class="a-list-item"]/span[contains(.,"Téléphone")]/following-sibling::text()').extract()
                registre = response.xpath('//div[@class="a-column a-span6"]/ul[@class="a-unordered-list a-nostyle a-vertical"]/li//span[@class="a-list-item"]/span[contains(.,"registre de commerce")]/following-sibling::text()').extract()
                TVA = response.xpath('//div[@class="a-column a-span6"]/ul[@class="a-unordered-list a-nostyle a-vertical"]/li//span[@class="a-list-item"]/span[contains(.,"TVA")]/following-sibling::text()').extract()
                address = response.xpath('//div[@class="a-column a-span6"]/ul[@class="a-unordered-list a-nostyle a-vertical"]/li//span[span[contains(.,"Adresse")]]/ul//li//text()').extract()
                item['Business_name'] = ''.join(name).strip()
                item['Phone_number'] = ''.join(phone).strip()
                item['VAT_number'] = ''.join(TVA).strip()
                item['Address'] = '\n'.join(address).strip()
                item['Registre_commerce'] = ''.join(registre).strip()
                yield item
        else:
            for sel in response.xpath('//html/body'):
                item = AmazonTestItem()
                list_urls = sel.xpath('//a/@href').extract()
                for url in list_urls:
                    yield scrapy.Request(response.urljoin(url), callback=self.parse, meta={'item': item})

and the error message is :
Traceback (most recent call last):
  File "C:\Users\paulpo\AppData\Local\Continuum\Anaconda3\lib\site-packages\scrapy\utils\defer.py", line 102, in iter_errback
    yield next(it)
  File "C:\Users\paulpo\AppData\Local\Continuum\Anaconda3\lib\site-packages\scrapy\spidermiddlewares\offsite.py", line 29, in process_spider_output
    for x in result:
  File "C:\Users\paulpo\AppData\Local\Continuum\Anaconda3\lib\site-packages\scrapy\spidermiddlewares\referer.py", line 339, in <genexpr>
    return (_set_referer(r) for r in result or ())
  File "C:\Users\paulpo\AppData\Local\Continuum\Anaconda3\lib\site-packages\scrapy\spidermiddlewares\urllength.py", line 37, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "C:\Users\paulpo\AppData\Local\Continuum\Anaconda3\lib\site-packages\scrapy\spidermiddlewares\depth.py", line 58, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "C:\Users\paulpo\Documents\amazon_test\amazon_test\spiders\AmazonFR.py", line 21, in parse
    link = (response.xpath('//div[@class="a-column a-span6"]/h3[@id="-component-heading"]/text()')).extract
  File "C:\Users\paulpo\AppData\Local\Continuum\Anaconda3\lib\site-packages\scrapy\http\response\__init__.py", line 105, in xpath
    raise NotSupported("Response content isn't text")
scrapy.exceptions.NotSupported: Response content isn't text


text:
Q: How do I make this into a working CRS in ArcGIS? +proj=tmerc +lat_0=0 +lon_0=-114 +k=0.9999 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
I have this text string which I successfully used to project data in QGIS. How do I use this to define a CRS in ArcGIS and project my data correctly? Thanks

A: If you have Qgis, you can ask gdalsrsinfo in the OSGeo4w shell:
gdalsrsinfo "+proj=tmerc +lat_0=0 +lon_0=-114 +k=0.9999 +x_0=0 +y
_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"

PROJ.4 : '+proj=tmerc +lat_0=0 +lon_0=-114 +k=0.9999 +x_0=0 +y_0=0 +ellps=GRS80
+towgs84=0,0,0,0,0,0,0 +units=m +no_defs '

OGC WKT :
PROJCS["unnamed",
    GEOGCS["GRS 1980(IUGG, 1980)",
        DATUM["unknown",
            SPHEROID["GRS80",6378137,298.257222101],
            TOWGS84[0,0,0,0,0,0,0]],
        PRIMEM["Greenwich",0],
        UNIT["degree",0.0174532925199433]],
    PROJECTION["Transverse_Mercator"],
    PARAMETER["latitude_of_origin",0],
    PARAMETER["central_meridian",-114],
    PARAMETER["scale_factor",0.9999],
    PARAMETER["false_easting",0],
    PARAMETER["false_northing",0],
    UNIT["Meter",1]]

The WKT parameters should be usable with Arcgis.


text:
Q: Can I run an offline graph processing algo on AWS? Currently we have a table of followers on dynamo. (user_id, follows_who_id, date). We back it up in S3 and when we want to do heavy data processing we run EMR on the S3 files.
Now I need to make friends recommendations. This is more a graph job than a map reduce job. I can use the S3 files as an input (edges/vertices are natural from the data), but what tool do I use after ?
I found blog posts about Titan etc but it seems they work for queries (more or less like dynamo queries) but not for big batch processing.


text:
Q: How to set Rating Bar using Array List Im try to set value of Rating Bar using Array List,  im set the value of rating to Float, but i don't know how to set the value and show it into the Rating Bar, and im use listview to show the data. please help me to solve this problem
this is my Artikel Activity, im set the ratingbar into float
package com.example.latihanlist;
public class Artikel {
    private int imageId;
    private float ratingId;
    private String title;
    private String timestamp;
    private String descriptions;

    public Artikel(int imageId, String title, String timestamp, String
            descriptions, float ratingId) {
        this.imageId = imageId;
        this.title = title;
        this.timestamp = timestamp;
        this.descriptions = descriptions;
        this.ratingId = ratingId;
    }
    public int getImageId() {
        return imageId;
    }

    public float getRatingId() {
        return ratingId;
    }

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getTimestamp() {
        return timestamp;
    }
    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }
    public String getDescriptions() {
        return descriptions;
    }
    public void setDescriptions(String descriptions) {
        this.descriptions = descriptions;
    }
}

here my MainActivity, im set the value for rating 2.0
package com.example.latihanlist;

        import androidx.appcompat.app.AppCompatActivity;

        import android.content.Intent;
        import android.os.Bundle;
        import android.view.View;
        import android.view.ViewStub;
        import android.widget.AdapterView;
        import android.widget.Button;
        import android.widget.ListView;
        import android.widget.RatingBar;
        import android.widget.Toast;
        import java.util.ArrayList;
        import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ViewStub stubList;
    private ListView listview;
    private ListViewArrayAdapter listViewArrayAdapter;
    private List<Artikel> artikelList;

    private List<Artikel> getArtikelList() {
        artikelList= new ArrayList<>();
        artikelList.add(new Artikel(R.drawable.mob,"Title 1","1 hours ago","Descriptions of text 1", "2.0"));
        artikelList.add(new Artikel(R.drawable.mob,"Title 2","1 hours ago","Descriptions of text 2", "2.0"));
        artikelList.add(new Artikel(R.drawable.mob,"Title 3","1 hours ago","Descriptions of text 3", "2.0"));
        artikelList.add(new Artikel(R.drawable.mob,"Title 4","1 hours ago","Descriptions of text 4", "2.0"));
        artikelList.add(new Artikel(R.drawable.ic_launcher_background,"Title 5","1 hours ago","Descriptions of text 5", "2.0"));
        return artikelList;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        stubList=(ViewStub) findViewById(R.id.stublist);
        stubList.inflate();
        listview=(ListView) findViewById(R.id.list_view);
        stubList.setVisibility(View.VISIBLE);

        getArtikelList();
        listViewArrayAdapter=new ListViewArrayAdapter(this,R.layout.list_item,artikelList);
        listview.setAdapter(listViewArrayAdapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               // Toast.makeText(getApplicationContext(),
                   //     artikelList.get(position).getTitle(), Toast.LENGTH_SHORT).show();

                Bundle bundle = new Bundle();
                bundle.putString("dataTitle", artikelList.get(position).getTitle().toString());
                bundle.putInt("dataImg", artikelList.get(position).getImageId());
                bundle.putString("dataDesc", artikelList.get(position).getDescriptions().toString());

                Intent intent = new Intent(MainActivity.this, DetailBerita.class);
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });

        Button mBtn_login = (Button)findViewById(R.id.button1);
        mBtn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MenuApkAndroid.class);
                startActivity(intent);
            }
        });

    }

}

this is my list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:src="@drawable/mob"/>
    <TextView
        android:id="@+id/textTitle"
        android:text="Title of the Text"
        android:layout_marginLeft="75dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"/>
    <TextView
        android:id="@+id/textTime"
        android:layout_below="@id/textTitle"
        android:text="1 hours ago"
        android:layout_marginLeft="75dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="9dp"/>
    <TextView
        android:id="@+id/textDesc"
        android:layout_below="@+id/textTime"
        android:text="This is descriptions of the title of text"
        android:layout_marginLeft="75dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="10dp"/>

    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="75dp"
        android:numStars="5"
        android:stepSize="1.0"
         />
</RelativeLayout>

A: Let we discuss first behaviour of RatingBar.
Official Document say:

When using a RatingBar that supports user interaction, placing widgets
  to the left or right of the RatingBar is discouraged.
The number of stars set (via setNumStars(int) or in an XML layout)
  will be shown when the layout width is set to wrap content (if another
  layout width is set, the results may be unpredictable).

Meaning RatingBar will not work as expected if you put any view to the left or right of RatingBar.
It will not work also if you set RatingBar width other than wrap_content.
"But I need views left or right or both to the RatingBar. Is it possible to do?"
Yes!!!
"How??"
Put RatingBar alone inside a Layout.Something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">
    <TextView
        android:id="@+id/cell1"
        android:layout_width="0dp"
        android:layout_weight="2"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/cell2"
        android:layout_width="0dp"
        android:layout_weight="2"
        android:layout_height="wrap_content" />
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:stepSize="1.0"
        />
</LinearLayout>

</LinearLayout>

For more detail check official RatingBar.
Now,Come to the point. Where is the solution for me??.
Your all the code is fine except rating parameter in Artikel Object.That must be float as per your definition of class.I think compiler will give you that error.
Since your are using RelativeLayout so i think you will not have issue of left-right too.
You need to set the ArrayAdapter properly.
Have a look on following:
public class ListViewArrayAdapter extends ArrayAdapter<Artikel> {
    Context mContext;
    ArrayList<Artikel> mArtikels;
    public ListViewArrayAdapter(@NonNull Context context, @NonNull ArrayList<Artikel> artikels) {
        super(context, 0, artikels);
        mContext = context;
        mArtikels = artikels;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View listItem = convertView;
        if (listItem ==null){
            listItem = LayoutInflater.from(mContext).inflate(R.layout.artikel_list_item,parent,false);
        }
        Artikel artikel = mArtikels.get(position);

        ImageView imageView = listItem.findViewById(R.id.imageView);
        TextView title = listItem.findViewById(R.id.textTitle);
        TextView time = listItem.findViewById(R.id.textTime);
        TextView disc = listItem.findViewById(R.id.textDesc);
        RatingBar ratingBar = listItem.findViewById(R.id.ratingBar);

        imageView.setImageResource(artikel.getImageId());
        title.setText(artikel.getTitle());
        time.setText(artikel.getTimestamp());
        disc.setText(artikel.getDescriptions());

        ratingBar.setRating(artikel.getRatingId());

        return listItem;
    }
}

Hope It will help. Full Source code is here
Please Up Vote if it works. Happy coding.
Thanks


text:
Q: Can't set attribute of document.documentElement; I have following code to set the dark mode for the document.body

function myFunction() {
  var element = document.body;
  element.classList.toggle("dark-mode");
}
.dark-mode {
  background-color: black;
  color: white;
}

  <input onclick="myFunction()" type="checkbox">

If I set the document.body to document.documentElement it does not work. Does someone know how to fix it for the root element of the HTML? I also tried document.querySelector(":root");.

A: So the code as you have it seem to be working fine, both document.body and document.documentElement, so the issue might be related on where and how you are importing de CSS.
With document.documentElement

    Toggle
    <input onclick="myFunction()" type="checkbox">

With document.body

    Toggle
    <input onclick="myFunction()" type="checkbox">

But also as a general recommendation de input shouldn't be wrapped in the label tag.

    Toggle

  <input id="toggle" name="toggle" onclick="myFunction()" type="checkbox">


text:
Q: How to get title from HTTP text representation via Qt? Qt 4.7 DOM API seems kind of strange :(. I have a text HTML representation and need to get "title" text. Seems very easy, but following code is not working, i get empty string:
QDomDocument dom;
dom.setContent( "<title>this is a title</title>" );
QString title = dom.elementsByTagName( "title" ).item( 0 ).nodeValue();

Any suggestions?

A: Try this:
QString title = dom.elementsByTagName( "title" ).item( 0 ).firstChild().nodeValue();

Because the tree structure for text is:
node <title>
=> text element


text:
Q: UNIX Domain Socket programming 3 sockets I am trying to make a server.c file that supports 3 sockets, which are represented by 3 respective client classes: client1, client2, client3.
In my server.c file, I currently have this code which I found on the internet.
If I wanted to make it have 3 sockets. I want to use the select() command to see the write activities of the 3 clients. My question is how can I use this to support 3 sockets.
Can I bind the 3 clients to 3 sockets that the server can listen to? If so, how can the server listen to these 3 sockets respectively? With an array possibly?
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>

#define socket1 "sock1"
#define socket2 "sock2"
#define socket3 "sock3"

int main(int argc, char *argv[]) {
    //struct sockaddr_un addr;
    struct sockaddr_un addr1;
    struct sockaddr_un addr2;
    struct sockaddr_un addr3;
    char buf[100];
    int socket1;
    int socket2;
    int socket3;
    //int fd;
    int cl,rc;

    if (argc > 1) socket_path=argv[1];

    if ( (socket1 = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        perror("socket error");
        exit(-1);
    }

    memset(&addr1, 0, sizeof(addr1));
    addr1.sun_family = AF_UNIX;
    strncpy(addr1.sun_path, socket_path, sizeof(addr1.sun_path)-1);

    unlink(socket_path1);

    if ( (socket2 = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        perror("socket error");
        exit(-1);
    }

    memset(&addr2, 0, sizeof(addr2));
    addr1.sun_family = AF_UNIX;
    strncpy(addr2.sun_path, socket_path, sizeof(addr2.sun_path)-1);

    unlink(socket_path2);

    if ( (socket3 = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        perror("socket error");
        exit(-1);
    }

    memset(&addr3, 0, sizeof(addr3));
    addr3.sun_family = AF_UNIX;
    strncpy(addr3.sun_path, socket_path, sizeof(addr3.sun_path)-1);

    unlink(socket_path3);

    if (bind(socket1, (struct sockaddr*)&addr1, sizeof(addr1)) == -1) {
        perror("bind error");
        exit(-1);
    }

    if (bind(socket2, (struct sockaddr*)&addr2, sizeof(addr2)) == -1) {
        perror("bind error");
        exit(-1);
    }

    if (bind(socket3, (struct sockaddr*)&addr3, sizeof(addr3)) == -1) {
        perror("bind error");
        exit(-1);
    }

    if (listen(socket1, 5) == -1) {
        perror("listen error");
        exit(-1);
    }

    if (listen(socket2, 5) == -1) {
        perror("listen error");
        exit(-1);
    }

    if (listen(socket3, 5) == -1) {
        perror("listen error");
        exit(-1);
    }

    while (1) {
        if ( (cl = accept(fd, NULL, NULL)) == -1) {
            perror("accept error");
            continue;
        }

        while ( (rc=read(cl,buf,sizeof(buf))) > 0) {
            printf("read %u bytes: %.*s\n", rc, rc, buf);
        }
        if (rc == -1) {
            perror("read");
            exit(-1);
        }
        else if (rc == 0) {
            printf("EOF\n");
            close(cl);
        }
    }

    return 0;
}

A: If you want three listening sockets in the same process, you have to make them unique. In the AF_INET family you do that by bind(2)-ing different ports, in the AF_UNIX family you do that with different paths.
Also your line:
char *socket_path = "\0hidden";

has at least two problems:

*

*Type of the string literal on the right side of the assignment is const char[8], which decays to const char* pointer type, but not char* type. Make the left hand side const char*. Plus, compile with higher warning level, like -Wall -pedantic to get help from your compiler.

*Zero byte at the beginning of the string makes strncpy(3) not copy anything, since it copies at most n characters from the string pointed to by src, including the terminating null byte ('\0').

Create a function that take UNIX path as an argument and creates, binds, and marks socket as listening, and returns created socket descriptor. Call it three times - you have three listening UNIX sockets. Setup select(2) on them for reading - that'll tell you when client connections arrive. At that point call accept(2) on the active socket to get connected client socket, which is separate from the listening socket itself.

A: Ok, since select, is and has always been my favorite Unix syscall, I decided to do a little something, which is, in my humble opinion, what you were looking for.
I shamelessly took server's and client's code from here:
https://troydhanson.github.io/misc/Unix_domain_sockets.html
I did of course some little modifications, to make it fit your needs, lets see:
server.c:
#include <stdio.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>

char *socket_path = "/tmp/socket";

int main() {
  int fd, i;
  int clients[10], num_clients;
  fd_set read_set;
  char buf[100];

  struct sockaddr_un addr;

  if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
    perror("socket error");
    exit(-1);
  }

  unlink(socket_path);

  memset(&addr, 0, sizeof(addr));
  addr.sun_family = AF_UNIX;
  strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path)-1);

  if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
    perror("bind error");
    exit(-1);
  }

  if (listen(fd, 5) == -1) {
    perror("listen error");
    exit(-1);
  }

  num_clients = 0;

  while (1) {
    FD_ZERO(&read_set);
    FD_SET(fd, &read_set);

    for (i = 0; i < num_clients; i++) {
      FD_SET(clients[i], &read_set);
    }

    select(fd + num_clients + 1, &read_set, NULL, NULL, NULL);

    if (FD_ISSET(fd, &read_set)) {
      if ( (clients[num_clients++] = accept(fd, NULL, NULL)) == -1) {
        perror("accept error");
        continue;
      }
      printf("we got a connection!\n");
    }

    for (i = 0; i < num_clients; i++) {
      if (FD_ISSET(clients[i], &read_set)) {
        read(clients[i], buf, sizeof(buf));
        printf("client %d says: %s\n", i, buf);
      }
    }
  }
}

client.c:
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

char *socket_path = "/tmp/socket";

int main(int argc, char *argv[]) {
  struct sockaddr_un addr;
  char buf[100];
  int fd,rc;

  if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
    perror("socket error");
    exit(-1);
  }

  memset(&addr, 0, sizeof(addr));
  addr.sun_family = AF_UNIX;
  strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path)-1);

  if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
    perror("connect error");
    exit(-1);
  }

  while( (rc=read(STDIN_FILENO, buf, sizeof(buf))) > 0) {
    printf("writing\n");
    *index(buf, '\n') = 0;

    if (write(fd, buf, rc) != rc) {
      if (rc > 0) fprintf(stderr,"partial write");
      else {
        perror("write error");
        exit(-1);
      }
    }
  }

  return 0;
}

Ok, this works very easily, you just fire the server in one terminal, and then you open a couple other terminals and fire a couple clients.
Running it on my pc I get:
exe@atreides:~/tmp$ ./server
we got a connection!
client 0 says: Hello!
we got a connection!
client 1 says: Hey man!

Another terminal at the same time:
exe@atreides:~/tmp$ ./client
Hey man!
writing

And in another:
exe@atreides:~/tmp$ ./client
Hello!
writing

The magic behind all this is to properly use socket and select.
First you need a server socket, the one that will accept connections.
Once you bind to a server socket, let it be a Unix socket or a network socket, you can get sockets to your clients by accepting connections on that socket. Each client gets a new socket number.
Then, you add these sockets, the server socket and the clients socket to an fd_set and pass it to select. Select will listen on all sockets at the same time and will leave in the set those who have received data.
Now you iterate the set to see what sockets are hot and, you're there!
One more thing, which I guess was confusing you, all clients connect to the same server socket address (file). Yes it is like if many processes opened the same file, at the same time... But this isn't an ordinary file, it is a Unix socket. :)
Have fun and good luck!!!


text:
Q: Why this responsive CSS can't change my lay out? <!DOCTYPE HTML>

        <link rel="stylesheet" href="style.css">

@media (max-width:250px){
    .flexParent{display: flex;flex-direction:column;}
}
.debug{border-style: solid;}
.flexParent{display:flex;height:100%;width:100%;margin:0;flex-direction: row;}
.sidebar{flex: 0 1 200px;height: 100%;text-align: center;margin-right: 2px;}
.mainContent{flex: 1;}

When I try to set my browser to 240px, It doesn't work. I think this should change row to column.


text:
Q: Animating the file upload button using CSS I've a form in which I've a file upload filed I did customized it to fit the color theme which the PHP form is using it works but it's just static. I wanted to add a small transition to the button which I archived following the W3Schools tutorial.
But after that I'm facing a problem which I really don't have an idea how to solve. I did a search on this matter but most answers suggest to use bootstrap which I also tried and it messed up my current projects CSS.
Can some one show me what I'm doing wrong with the animation part.

.fileUpload {
  float: left;
  position: relative;
  overflow: hidden;
  background-color: #4068E0;
  color: white;
  height: 30px;
  width: 120px;
  text-align: center;
  border: 2px solid #4068E0;
  border-radius: 20px;
  box-shadow: 2px 2px 1px 1px rgba(0, 0, 0, 0.4);
  -webkit-transition: prop 0.4s;
  -moz-transition: prop 0.4s;
  -ms-transition: prop 0.4s;
  -o-transition: prop 0.4s;
  transition: prop 0.4s;
}

.fileUpload:after {
  content: "";
  background: #85b7e8;
  display: block;
  position: absolute;
  opacity: 0;
  transition: all 0.8s;
  padding-top: 300%;
  padding-left: 350%;
  margin-left: -20px!important;
  margin-top: -120%;
  font-size: 20px;
  cursor: pointer;
  filter: alpha(opacity=0);
  height: 100%;
  text-align: center;
}

.fileUpload:active:after {
  padding: 0;
  margin: 0;
  opacity: 1;
  transition: 0s
}

.fileUpload input.upload {
  position: absolute;
  top: 0;
  right: 0;
  margin: 0;
  padding: 0;
  font-size: 20px;
  cursor: pointer;
  opacity: 0;
  filter: alpha(opacity=0);
  height: 100%;
  text-align: center;
}

.fileName {
  margin: 2px 0 0 130px;
  width: auto;
}

.updLabel {
  line-height: 30px;
  font-weight: bold;
}

#uploadFile {
  border: none;
  width: 150px;
  height: 30px;
}

    Add Image
    <input type="file" id="uploadFile" class="upload">

    <input id="uploadFile" placeholder="0 files selected" disabled>

As you can see in the above snippet the animation does happens but it doesn't pop the file selection window. If I disable the animation part it does pop up I tried few other things which also didn't work that's why I decided to ask here.

A: I've got success with your code when I add a z-index on the input. I tried with z-index: 1 and it worked. the visuals on the button won't change.
.fileUpload > input {
    z-index: 1;
}


text:
Q: Android Design Application I here attached some snap here.
I am very new in android so any give idea for create the design or give any link to learn design

A: http://www.androidhive.info/2011/10/android-login-and-registration-screen-design/
There are lots of beginner courses for Android design. You can try this link.

A: I recommend you to follow the Android Material Design guidelines
https://material.io/
https://material.io/guidelines/


text:
Q: How to send elasticsearch multi search request in Postman? I'm trying to send elasticserach multi search request via postman as below:
POST - http://localhost:9200/_msearch
content-type : x-www-form-urlencoded
body:
{"index":"accounts"}
{"query":{"bool":{"should":[{"match":{"owner.first_name":"Creeple"}}]}}}

However, I'm getting following error:
{
  "error": {
    "root_cause": [
      {
        "type": "parse_exception",
        "reason": "Failed to derive xcontent"
      }
    ],
    "type": "parse_exception",
    "reason": "Failed to derive xcontent"
  },
  "status": 400
}

Note that if I perform same request via my play code, results are succesfully fetched.
WS.url("localhost:9200/_msearch").withHeaders("Content-type" -> "application/x-www-form-urlencoded").post(query)

A: Three things are important here:

*

*When inserting body, select raw radiobutton and Text (or JSON) from dropdown.

*Add header: Content-type: application/x-ndjson

*Most important: put new line after the last line of your query

Body:

Header:

Curl version:
curl -X POST \
  http://127.0.0.1:9200/_msearch \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/x-ndjson' \
  -d '{"index":"script","type":"test"}
{"query":{"match_all":{}}}
'

A: You can also make your request body be json format and change your Content-Type be application/json, please take a look as below

A: I have found error for "Expected [START_OBJECT] but found [null]" when I use _msearch API in elasticsearch.
Response of this api
Request parameters and url


text:
Q: How to run a Tasker command from a Android app? I see that apps like Nova Launcher, Trigger and etc have an option to run Tasker tasks. Instead of creating an app with Tasker App Factory, I want to know how to implement an Intent that runs a Tasker task.
Thanks.

A: Just found by myself in Tasker Developer Information:
http://tasker.dinglisch.net/developers.html


text:
Q: __str__ not enough arguments for format string Hello  I'm having trouble with the __str__ when I try to print my object.  The interpreter is telling me "TypeError: not enough arguments for format string"
This is the code that I'm trying to run!
    'My Practice Class'
    class Directory:
        'A Simple Directory Class'

        def __init__(self, name, parent):
            self.name = name
            self.parent = parent

        def __str__(self):
            return 'I am %s a Child directory of %s' % (self.name, self.parent)

        def __repr__(self):
            return 'Directory(%r)' % self.name

print a
Traceback (most recent call last):
  File "<\stdin>", line 1, in <\module>
  File "myclass.py", line 14, in \__str\__
    def \__repr\__(self):
TypeError: not enough arguments for format string

Thank you

A: [Moved from comments as this might be a helpful sign post question]
If you are importing a module that you are working on calling
import xxx

a second time does not re-import the changed file (python is trying to be clever, sees you already have that module loaded short-circuts the process).  What was going on was that you were changing the file, but python was never seeing those changes.
To reload a module call
reload(xxx)

Also becareful if you imported things as
from xxx import yyy

Calling reload xxx will not affect yyy you would need to do
reload(xxx)
yyy = xxx.yyy

A: Seems to work fine for me:
>>> class Directory:
        'A Simple Directory Class'

        def __init__(self, name, parent):
            self.name = name
            self.parent = parent

        def __str__(self):
            return 'I am %s a Child directory of %s' % (self.name, self.parent)

        def __repr__(self):
            return 'Directory(%r)' % self.name

>>> a = Directory('Name', 'Parent')
>>> print(a)
I am Name a Child directory of Parent
>>>
>>>


text:
Q: Can we use CrossOrigin * (wildcard) in production what is the difference when you use a specific cross origin and when you put * ?
for example
@CrossOrigin(origins = localhost:8080) or

@CrossOrigin(origins = "*")

does it have any security issue if it is * ?

A: The CrossOrigin was introduced to prevent background requests from untrusted websites.
Immagine the scenario:

*

*You are browsing on: malicious.example.com

*The website sends a background HTTP request to "DELETE http://facebook.com/my-account" to delete your account silently

You would be pretty mad if that could happen right?
That's the main reason for CORS. It prevents XHR request from non "trusted" origins. I'd encourage you to use CORS when you can to prevent such disasters to happen.
This is a simplified version, the server might also need to enable cookies and headers, and so for the Facebook DELETE to work, but... You got the idea


text:
Q: Error with SQL Server profiler I am having a strange problem with SQL Server Profiler. We have a .NET program running and collecting traces every hour and dumping into a central database.
In a few instances, I see that the trace is closing, but not deleting the file (in original folder) and moving to the archives folder.
EXEC sp_trace_setstatus @TraceID, 0
EXEC sp_trace_setstatus @TraceID, 2

The above two commands are running most of the time, but when the first command fails, it's a problem to run renamefiles.cmd.
I have to manually stop the trace and delete the files manually again and start the trace back.
Contents of renamefiles.cmd:
@ECHO OFF
if '%1' == '' goto usage
if '%2' == '' goto usage
if '%3' == '' goto usage

set fileDes= "D:\Audit\archives\%1%"
set fileSource="D:\Audit\%1%"
ECHO %fileDes%

COPY /Y /B %fileSource%  %fileDes%

if '%3' == '1'  goto dbchange
if '%3' == '2'  goto WRchange
:dbchange
ren %fileDes%  DBaudit_%2%.trc
del %fileSource%
goto done

:WRchange
ren %fileDes%  WR_DBaudit_%2%.trc
del %fileSource%
goto done

REM: How to use screen
:usage
echo.
echo Usage: MyScript Server Environment
echo file: file source to copy
echo timestamp: time stamp
echo.
echo Example: MyScript.cmd filesource timestamp tracetype
echo.
echo.
goto done

:done


text:
Q: JTable#repaint() not functioning as expected This application pulls data from a text file and inserts it into JTable. An Observer is attached to check every 300 ms if there is a change to the file and reload the data. I have the setChanged() and notifyObservers() in my Observer class.
When data is added to the table, a getRowCount() reports that the row was added, notifiers are  operational. Virtually everything is working except for the repaint(). I have tried revalidate() and fireTableDataChanged() all to no avail. I would appreciate some help on this. No compile errors are reported throughout the process.
Table Model
package HardwareDbFile;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;

public class HardwareFileTableModel extends AbstractTableModel{
    protected Vector data;
    protected Vector columnNames ;
    protected String datafile;

    public HardwareFileTableModel(String file){
        datafile = file;
        initVectors();
    }

    public void initVectors() {
        String aLine ;
        data = new Vector();
        columnNames = new Vector();
        try {
            FileInputStream fin =  new FileInputStream(datafile);
            try (BufferedReader br = new BufferedReader(new InputStreamReader(fin))) {
                StringTokenizer st1 = new StringTokenizer(br.readLine(), "|");
                while(st1.hasMoreTokens()) {
                    columnNames.addElement(st1.nextToken());
                }
                // extract data
                while ((aLine = br.readLine()) != null) {
                    StringTokenizer st2 = new StringTokenizer(aLine, "|");
                    while(st2.hasMoreTokens()) {
                        data.addElement(st2.nextToken());
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public int getRowCount() {
        return data.size() / getColumnCount();
    }

    @Override
    public int getColumnCount(){
        return columnNames.size();
    }

    @Override
    public String getColumnName(int columnIndex) {
        String colName = "";

        if (columnIndex <= getColumnCount()) {
            colName = (String)columnNames.elementAt(columnIndex);
        }
        return colName;
    }

    @Override
    public Class getColumnClass(int columnIndex){
        return String.class;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
    }

    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    }
}

Observer Class
package HardwareDbFile;

import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.Timer;

 public class HardwareFileObserver extends Observable implements ActionListener {
     Timer time = new Timer(300,this); // check every 300ms
     long lastModified;
     String file ;

     HardwareFileObserver (String string) {
         file = string;
         File f = new File(file);
         lastModified = f.lastModified(); // original timestamp
         time.start();
     }

     @Override
     public void actionPerformed(ActionEvent e) {
         File f = new File(file);
         long actualLastModified = f.lastModified();
         if (lastModified != actualLastModified) {
             // the file have changed
             lastModified = actualLastModified;
             setChanged();
             notifyObservers();
         }
     }
}

Main Class
    public class HardwareInventoryUI extends javax.swing.JFrame implements Observer {

    private String datafile = "hardware.dat";
    private String dataFilePath = "C:\\Windows\\Temp\\hardware.dat";
    protected HardwareFileTableModel model;

    /**
     * Creates new form HardwareInventoryUI
     */
    public HardwareInventoryUI() {
        initComponents();

        model = new HardwareFileTableModel(dataFilePath);
        HardwareFileObserver  fileWD;

        // this Observable object is monitoring any file change
        fileWD = new HardwareFileObserver(dataFilePath);
        fileWD.addObserver(this);
    }

    @Override
    public void update(Observable o, Object arg) {
        // reload data because data file have changed
        model.initVectors();
        jTable.repaint();
    }

Add Record Button
    private void jAddRecordActionPerformed(java.awt.event.ActionEvent evt) {

        String toolID = jToolID.getText();
        String toolName = jToolName.getText();
        String quantity = jQuantity.getText();
        String itemPrice = jItemPrice.getText();
        try {
            model = new HardwareFileTableModel(dataFilePath);
            FileWriter fstream = new FileWriter(dataFilePath, true);
            try (BufferedWriter newRecord = new BufferedWriter(fstream)) {
                newRecord.newLine();
                newRecord.write(toolID + "|"+ toolName + "|" + quantity + "|" + itemPrice );
            }
        } catch (IOException ex) {
            Logger.getLogger(HardwareInventoryUI.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

A: *

*Your TableModel should implement Observer, not your view. In the update() method, update data and fireTableDataChanged(). A JTable listens to its TableModel and updates itself automatically in response.

*Also consider alternate implementations of the observer pattern mentioned here.

*As illustrated here, your implementation of setValueAt() is incorrect. You need to fire the event that would notify the listening table of the change:
@Override
public void setValueAt(Object value, int row, int column) {
    // update data
    fireTableCellUpdated(row, column);
}

*If the content of your datafile can be obtained as the standard output of a command, you may be able to eliminate the file using the approach outlined here.
Addendum: As @kleopatra comments, "Note that with a well-behaved model, you never need to put any thought into view updates, they simply happen auto-magically :-) Or the other way round: if manual repaints on a view (such as table, tree, list) seem be be a solution, the model implementation is incorrect."


text:
Q: JavaScript Delete String starts with/finish with I have some string with the same template:
input:
azert,erty,tytr,0.243,jfrd,er,dr,0.85493,ftdre,0.2233

output exepected:
azert,erty,tytr,jfrd,er,dr,ftdre

So I need to delete all ",0." ...
How can I proceed in JavaScript?
Thanks!

A: You can use:
var str = 'azert,erty,tytr,0.243,jfrd,er,dr,0.85493,ftdre,0.2233';

var r = s.replace(/(^|,)0[^,]*/g, '');
//=> azert,erty,tytr,jfrd,er,dr,ftdre

OR else:
var r = str.replace(/(^|,)0[^,]*(,|$)/g, '$1').replace(/,+$/g, "");
//=> azert,erty,tytr,jfrd,er,dr,ftdre

A:
start with "," then with "0." untill the next "," : for each

*

*Must start with , then 0.

*Must replace with NULL up to the next ,
You can use
var str = "azert,erty,tytr,0.243,jfrd,er,dr,0.85493,ftdre,0.2233";
var output = str.replace(/(^|,)0.[^,]+/g, "")

http://jsfiddle.net/wfhnm6oe/2/
http://regex101.com/r/bS9mY3/1

*

*(^|,) - Match begining of string or comma

*0. - Then match 0. literal

*[^,]+ - Match everything up to a comma

*/g - Global flag - all matches (don't return on first match)

A: ,\d+(\.\d+)?

Try this.Replace with empty string.See demo.
http://regex101.com/r/zX3tG3/2

A: Here is my take : http://regex101.com/r/cX6qR7/1
The regex I used is /,0\.\d+,/g and a substitution of ,.
var re = /,0\.\d+,/g;
var str = 'azert,erty,tytr,0.243,jfrd,er,dr,0.85493,ftdre,0.2233';
var subst = ',';

var result = str.replace(re, subst);


text:
Q: jwebunit set a proxy for webtester webclient I have a problem in setting a proxy config in webtester.
Before, with htmlunit 2.11 jar I was using the following code:
HtmlUnitTestingEngineImpl h = (HtmlUnitTestingEngineImpl) wt.getTestingEngine();
ProxyConfig proxyConfig = new ProxyConfig(ip, 4128);
h.getWebClient().setProxyConfig(proxyConfig);

After updating jwebunit libraries (i.e. htmlunit 2.13, httpclient4.3.1 etc.) the setProxyConfig method isn't supported in WebClient.
It seems the only way to set proxy in WebClient is in the constructor.
Now, How can I set a proxy configuration for a jwebunit WebTester?
Thanks

A: You can use
webTester.getTestContext().setProxyAuthorization(null, null, ip, 4128);

buy pay attention to set the proxyauthorization BEFORE webtester.beginAt(..)
In the beginAt method happens the webclient init with proxy parameter.
After beginAt the webclient is reused so the first code (setProxyAuthorization) can't affect the webclient.


text:
Q: Attempting to Determine if ISP is Blocking Port 3074 In the last week I have experienced problems getting onto Xbox live.  I have a wireless access point / router connected to a cable modem provided by my local ISP.  After checking the settings on my router, it appears that the port for the xbox live service (3074) was producing outgoing traffic, but no incoming traffic.  I don't have much experience with networking, but I suspect that whatever the ISP has on my modem is blocking incoming TCP packets on port 3074.
To test this, I plugged my laptop directly into the cable modem's Ethernet port and tried both Shield's Up! and Canyouseeme, both of which labeled port 3074 as closed.  While plugged into the modem I also tried the following command,
hping3 --traceroute -V -S -p 3074 xbox.com

I received the following response,
using eth0, addr: X.X.X.X, MTU: 1500
HPING xbox.com (eth0 65.55.42.140): S set, 40 headers + 0 data bytes
^C
--- xbox.com hping statistic ---
47 packets transmitted, 0 packets received, 100% packet loss
round-trip min/avg/max = 0.0/0.0/0.0 ms

Is this the right way to find out if my problems are being caused by my ISP?  I'd like to know before contacting my ISP.

A: Rebooting all of your networking equipment would help. Failing that, contacting the ISP and talking to a tech would let you know for sure.
You could also try manually adding an entry in your router for said port number, mapping it to your Xbox.

A: This approach is sound, one can also try from another supplier or from a proxy/VPN. Think about all the firewalls between the points.
Also consider trying DMZ options.
Ask yourselves, has it ever worked ?
Is that port being forwarded to another PC ?


text:
Q: How to get url object from response object of Rest Client I am trying to solve a problem   mentioned below
Query this web service 100 times:
http://www.randomwebsite.com/cgi-bin/random.pl

The response contains a short HTML document with one link inside. Query this link and store link URL, as well as the returned HTTP response codes in a suitable data structure.
The application should output a list of all link URLs ordered by the first character of the domain name (ignore http:// and www prefixes) and also print the related HTTP Code, if it's not 200.
I am trying to use jersey client
Client client = Client.create();
            WebResource webResource2 = client.resource("http://www.randomwebsite.com/cgi-bin/random.pl");

            ClientResponse response2 = webResource2.accept("text/html").get(ClientResponse.class);

            System.out.println(response2);

            if (response2.getStatus() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + response2.getStatus());
            }

            String output2 = response2.getEntity(String.class);
            System.out.println("\n============getFtoCResponse============");
            System.out.println(output2);

GET http://www.westciv.com/ returned a response status of 200 OK

Now the problem is to store the URI i am not able to get the uri.How to get URI from the response object.I am able to see the random url  in response2  when its printed.But not able to get as a object to see the URL.I cannot get from client because the randomwebsite redirects to  random site.

A: The response sent is a redirect, with status 302. Your client allows not following redirects automatically:
client.setFollowRedirects(false);

You should get the URL from the Location response header.


text:
Q: Disable Variable Product Price Range on the WooCommerce Single Product Pages Only I'm looking to hide variable products price range only on the single product pages for the product that is currently being viewed. I do not want the price range to be disabled for all the products listed in the "Related Products" below and any products listed in the widgets in the footer as well.
Everyone of the snippets I've found so far hides the price range for every product listed on the single products page. It also hides the price completely from view from the variable products that have the exact same price for all of them since they do not display below the drop down when selected.
Here is an example of a snippet I've found:
/*
Disable Variable Product Price Range completely:
*/

add_filter( 'woocommerce_variable_sale_price_html', 'my_remove_variation_price', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'my_remove_variation_price', 10, 2 );

function my_remove_variation_price( $price ) {
  $price = '';
  return $price;
}

Example of price issue below:

A: Let's look on the Visual Hook Guide. The price range is a part of the single product summary. The woocommerce_single_product_summary hook consists of:
 * @hooked woocommerce_template_single_title - 5
 * @hooked woocommerce_template_single_rating - 10
 * @hooked woocommerce_template_single_price - 10
 * @hooked woocommerce_template_single_excerpt - 20
 * @hooked woocommerce_template_single_add_to_cart - 30
 * @hooked woocommerce_template_single_meta - 40
 * @hooked woocommerce_template_single_sharing - 50

And the woocommerce_template_single_price function adds the single-product/price.php template-part.
So we have two ways:
1. Remove this template part for variable products only
add_action( 'woocommerce_before_single_product', 'my_remove_variation_price' );
function my_remove_variation_price() {
  global $product;
  if ( $product->is_type( 'variable' ) ) {
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price' );
  }
}

2. Or edit the template part itself
Copy wp-content/plugins/woocommerce/templates/single-product/price.php to wp-content/themes/YOUR_THEME/woocommerce/single-product/price.php and replace this code fragment

<?php echo $product->get_price_html(); ?>

with this one
<?php if ( ! $product->is_type( 'variable' ) ) : ?>

<?php echo $product->get_price_html(); ?>

<?php endif; ?>

A: add_filter( 'woocommerce_variable_sale_price_html', 'ninja_remove_variation_price', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'ninja_remove_variation_price', 10, 2 );

function ninja_remove_variation_price( $price ) {
if ( is_product() ) {
$price = '';
}
return $price;
}

A: This code will remove "From" text without removing the price completely for variable products.
  add_filter( 'woocommerce_variable_price_html','variation_price_min', 9999, 2 );

  function variation_price_min( $price, $product ) {
  $prices = $product->get_variation_prices( true );
  $min_price = current( $prices['price'] );
  $price = sprintf( __( '%1$s', 'woocommerce' ), wc_price( $min_price ) );
  return $price;
   }


text:
Q: How to merge the unallocated space with a drive in windows 7? I allocated 30 GB to my C drive in windows 7 at the time of installation which now I feel to be insufficient. I've 15 GB of unallocated space which now I want to merge with my C drive but I don't know know how to do that. Someone please suggest me how to carry it on. Thanks in advance.

A: *

*Open the Start Menu (or press Win+R), enter diskmgmt.msc, then press Enter.

*Right-click on C: and select Extend Volume.

*Use the wizard to add the free space to the volume.

A: Use your Windows 7 installation DVD to boot and select "Repair Your Computer at the Install screen". Afterwards open the "Command prompt".
There you can extend the partition using the command line tool diskpart.exe.
For the details on the required diskpart commands see the article "How to extend a data volume...".


text:
Q: Ephemeral RSA key vs Ephemeral DH key? I try to design system that encrypts  files(audio) and store them in disc in order that only my clients(applet) decrypt and play them. So I decided to use AES cipher for bulk encryption and store keys in database. My problem is transferring secret key  securely.
In modern systems use SSL for transferring keys and data which are not stored cryptically. In SSL/TLS design, session key is generated two ways;
First way client creates key and encrypt it server's public key(certificate).
Second option is more secure and becomes more important after detecting heartbleed security bug. In this option key is created by client and server with (EC)DHE key agreement for every sessions.
When it comes to my case, there are two options as well.
First case;

*

*Client(applet) can create ephemeral RSA key pair and sends public key to server.

*Server encrypts secret key with client's public key and sends to client.

*Client(applet) decrypt secret key with private key.

*Client(applet) can decrypt audio files streamly and play.

Second case;

*

*Client(applet) and server agrees on session key using (EC)DHE.

*Server encrypts secret key symmetrically with session key and sends to client.

*Client(applet) decrypt secret key with session key.

*Client(applet) can decrypt audio files streamlly and play.

Which option is suits my scenario? What is pros and cons each case?
Thanks for answers.

A: Both solutions are vulnerable to an active attacker, in position of man-in-the-middle, because the key exchange is not authenticated. This issue is solved in SSL/TLS by the use of the X.509 PKI. It could also be solved by giving your client prior knowledge of the server's public key, for example.
That being said, between your two options, go with the (EC)DHE one, because generating a new DH key from pre-computed DH group (also known as DH parameters) is fast, whereas generating a new RSA key is very slow.


text:
Q: Python basics, dataframe iteration - calculating average number of ratings In dataframe I have columns such as prime_genre and user_rating. I want to calculate  average number of ratings (to do that i try to summarize ratings for each app and then divide by number of apps occurrences).
My solution looks like this:
total=0
len_genre=0
for genre in prime_genre:
    for i in iosfree['prime_genre']:
        if(i == genre):
            len_genre += 1
            total += iosfree.loc[iosfree['prime_genre']==i, 'user_rating']
    print("Genre: ", genre, "Average rating: ", total/len_genre)

Result looks like this:
Genre:  Music Average rating:  0      NaN
5      NaN
43     NaN
48     NaN
51     NaN

Average rating shouldn't be zero.
Could you please give me some advice how to fix it? I am new to Python.

A: Sounds like you can do with groupby with agg
df.groupby('prime_genre')['user_rating'].agg(['count','mean'])


text:
Q: How to use a thread that updates a panel in a Windows forms in c# I have class StillClock which is a Panel and is implemented as follows:
public class StillClock:  Panel {
  private int hour;
  private int minute;
  private int second;

  /** Construct a default clock with the current time*/
  public StillClock() {
      this.Size= new Size(200,200);
      this.Paint += OnPaint;
      setCurrentTime();
  }

  /** Construct a clock with specified hour, minute, and second */
  public StillClock(int hour, int minute, int second) {
    this.hour = hour;
    this.minute = minute;
    this.second = second;
  }

  /** Return hour */
  public int getHour() {
    return hour;
  }

  /** Set a new hour */
  public void setHour(int hour) {
    this.hour = hour;
    this.Refresh();
  }

  /** Return minute */
  public int getMinute() {
    return minute;
  }

  /** Set a new minute */
  public void setMinute(int minute) {
    this.minute = minute;
    this.Refresh();
  }

  /** Return second */
  public int getSecond() {
    return second;
  }

  /** Set a new second */
  public void setSecond(int second) {
    this.second = second;
    this.Refresh();
  }

  /** Draw the clock */
  private  void OnPaint(object sender, PaintEventArgs e) {

      Graphics g = e.Graphics;
    // Initialize clock parameters
    int clockRadius =
      (int)(Math.Min(this.Size.Width , this.Size.Height ) * 0.8 * 0.5);
    float xCenter = Size.Width / 2.0f;
    float yCenter = Size.Height / 2.0f;

    // Draw circle
    Pen pen = new Pen(Color.Black);
    g.DrawEllipse(pen,xCenter - clockRadius, yCenter - clockRadius,
      2 * clockRadius, 2 * clockRadius );

    g.DrawString( "12", new Font("System", 8), new SolidBrush(Color.Black),  xCenter - 5f,   yCenter - clockRadius + 12f -10);
    g.DrawString("9", new Font("System", 8), new SolidBrush(Color.Black), xCenter - clockRadius + 3f, yCenter + 5f - 10);
    g.DrawString("3", new Font("System", 8), new SolidBrush(Color.Black), xCenter + clockRadius - 10f, yCenter + 3f - 10);
    g.DrawString("6", new Font("System", 8), new SolidBrush(Color.Black), xCenter - 3f, yCenter + clockRadius - 3f - 10);

    // Draw second hand
    int sLength = (int)(clockRadius * 0.8);
    int xSecond = (int)(xCenter + sLength *
      Math.Sin(second * (2 * Math.PI / 60)));
    int ySecond = (int)(yCenter - sLength *
      Math.Cos(second * (2 * Math.PI / 60)));

    g.DrawLine(new Pen(Color.Red), xCenter, yCenter, xSecond, ySecond);

    // Draw minute hand
    int mLength = (int)(clockRadius * 0.65);
    int xMinute = (int)(xCenter + mLength *
      Math.Sin(minute * (2 * Math.PI / 60)));
    int yMinute = (int)(yCenter - mLength *
      Math.Cos(minute * (2 * Math.PI / 60)));

    g.DrawLine(new Pen(Color.Blue), xCenter, yCenter, xMinute, yMinute);

    // Draw hour hand
    int hLength = (int)(clockRadius * 0.5);
    int xHour = (int)(xCenter + hLength *
      Math.Sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
    int yHour = (int)(yCenter - hLength *
      Math.Cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));

    g.DrawLine(new Pen(Color.Black), (float)xCenter, (float)yCenter, (float)xHour, (float)yHour);
  }

  public void setCurrentTime() {
    // Construct a calendar for the current date and time
    Thread.sleep(1000);
    // Set current hour, minute and second
    this.hour = DateTime.Now.Hour;
    this.minute = DateTime.Now.Minute;
    this.second = DateTime.Now.Second;
  }
 }

I have to inherit class ClockAnimationUsingThread from class StillClock to develop an animated clock making use of a Thread object to set time of the StillClock every 1000ms.
I tried like this:
public class ClockAnimationUsingThread : StillClock
    {
        public ClockAnimationUsingThread()
        {
            Thread thread1 = new Thread(new ThreadStart(this.setCurrentTime));
            thread1.Start();
        }
    }

and then :
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            var panel = new ThreadedClock_ClassLibrary.ClockAnimationUsingThread();
            this.Controls.Add(panel);
        }
    }

in the Form1 class but after starting it, it just generates the still clock and doesn't update it at all.

A: You'll have to let the UI thread know that it needs to repaint the clock.  Just add:
  this.Invalidate();

Which is thread-safe, no need to invoke to the UI thread.  Do note that it is incredibly wasteful to burn up an entirely thread to just run a microsecond worth of code once a second.  A simple Timer gets the job done too, a lot cheaper.  And trivially solves your shutdown problem as well, you should not leave that thread running when the window is gone of course.

A: For the sake of correcting this issue and showing how threads can work, do the following:
Do this:
public class ClockAnimationUsingThread : StillClock
{
    public ClockAnimationUsingThread()
    {
    }

    public void Start()
    {
        Thread thread1 = new Thread(new ThreadStart(this.setCurrentTime));
        thread1.Start();
    }

}

Then this:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        var panel = new ThreadedClock_ClassLibrary.ClockAnimationUsingThread();
        this.Controls.Add(panel);
        panel.Start();
    }
}

I put it in a loop so the thread will continuously update every 1000ms, if you make the thread a background thread it will abort when the app is shut down.  If you don't want it to wait for that then you'd need to put some boolean property in the while loop and then set it to false when you close your form.
public void setCurrentTime() {
// Construct a calendar for the current date and time
while(true){
// Set current hour, minute and second
   this.Invoke((MethodInvoker) delegate {
   this.hour = DateTime.Now.Hour;
   this.minute = DateTime.Now.Minute;
   this.second = DateTime.Now.Second;
   });

   Thread.sleep(1000);
 }

}


text:
Q: PHP on IIS 6 as ISAPI, which process isolation mode? We have IIS 6 server with many php applications. PHP 5.2 runs as ISAPI modul and IIS is set to IIS 5.0 Isolation Mode.
Now I want to switch to FastCGI and enable application pools, with needs to release IIS 5.0 Isolation Mode and use Worker Process Isolation Mode.
But I don't know, if it is safe to change. Server is production, so I better ask you for your experiences, before any big mistake (apps are not so critical, but one restart is enough).
Do you have any experiences with this setting? On what deppends, if application will bee working fine on second mode also?

A: Switching large setups that are live is never an easy thing.
Because you ask if it's safe, I'd say, it's highly likely if you do the switch, you're not found enough to cope with problems and situations that can potentially occur which will make the process unsafe.
Take note that this is independent to the technical problems here, it's just the soft-skills. You can simulate the technical problems by cloning the live system and doing the switch on the clone so you know into which problems you will likely run.
My suggestion: Leave the system running until you need to switch. If there is a real need, there is a real will and there is budget to hire professionals that just do the job.


text:
Q: Using pgfkeys to switch between "enumerate" and "enumerate*" when using the enumitem package with the package option "inline"" No matter what I seem to do, I'm just getting this wrong.
I would like to be able to set a key to determine how my list is arranged.
\documentclass{article}
\usepackage[inline]{enumitem}
\usepackage{xparse}
\usepackage{pgfkeys}
\usepackage{pgffor}
\pgfkeys{/ae/testing/.cd,
  list collection/.store in=\mylistcollection,
  arrange horizontally/.code={\def\myenumitem{enumerate*}},
}
\def\myenumitem{enumerate}
\def\aeset#1{\pgfkeys{/ae/testing/.cd,#1}}
\def\aeget#1{\pgfkeysvalueof{/ae/testing/#1}}

\NewDocumentCommand{\mylist}{ m }
    {\bgroup
     \aeset{#1}
      \expandafter\begin\expandafter{\myenumitem}[label=(\alph*)]
        \foreach \x in \mylistcollection {\item \x}
      \expandafter\end\expandafter{\myenumitem}
      \egroup
    }

\pagestyle{empty}
\begin{document}

\mylist{list collection={a,b,c,d}}

\mylist{list collection={a,b,c,d},arrange horizontally}

\end{document}

Initially, I wanted to have the key arrange horizontally be defined as
arrange horizontally/.is if=ArrangeHorizontally,

and then also define
\newif\ifArrangeHorizontally
\ArrangeHorizontallyfalse

but that too was giving me problems (in fact, I've never been able to get .is if to work the way I expect them to.
Nevertheless, the code as I've written it above results in an error:
! Extra }, or forgotten \endgroup.
\item ...ctor \relax \fi }\color@endgroup \egroup
                                                  \enit@outeritem
l.32 ...collection={a,b,c,d},arrange horizontally}

?

I don't see what's going on.  I would think everything should expand as expected.
I also tried working around using \expandafter\begin\expandafter{.... by directly calling \enit@enumerate* or enit@enumerate.  But that too resulted in errors.
UPDATE
Here is my attempt with the .is if approach
\documentclass{article}
\usepackage[inline]{enumitem}
\usepackage{xparse}
\usepackage{pgfkeys}
\usepackage{pgffor}
\pgfkeys{/ae/testing/.cd,
  list collection/.store in=\mylistcollection,
  arrange horizontally/.is if=ArrangeHorizontally,
}
\newif\ifArrangeHorizontally
\ArrangeHorizontallyfalse

\def\myenumitem{enumerate}
\def\aeset#1{\pgfkeys{/ae/testing/.cd,#1}}
\def\aeget#1{\pgfkeysvalueof{/ae/testing/#1}}

\makeatletter
\NewDocumentCommand{\mylist}{ m }
    {\bgroup
     \aeset{#1}
  \ifArrangeHorizontally\@nameuse{enumerate*}\else\expandafter\@nameuse{enumerate}\fi
    [label=(\alph*)]
    \foreach \x in \mylistcollection {\item \x}
  \ifArrangeHorizontally\@nameuse{endenumerate*}\else\expandafter\@nameuse{endenumerate}\fi

      \egroup
    }

\makeatother
\pagestyle{empty}
\begin{document}

\mylist{list collection={a,b,c,d}}

\mylist{list collection={a,b,c,d},arrange horizontally=true}

\end{document}

A: Here's how I would do it. The code uses \etoolbox's list processing tools, especially \forlistloop{<handler>}{<list macro>} (which is expandable). And since it's already loaded it also uses \etoolbox's boolean tests and its \ifdefempty and \csuse.
I added a warning message in case an empty list or no list has been given.

\documentclass{article}

\usepackage[inline]{enumitem}
\usepackage{pgfkeys,etoolbox}

\makeatletter
\newbool{ae@enumerate@inline}
\def\ae@list@collection{}

\pgfkeys{
  ae/.cd ,
    list collection/.code =
      \forcsvlist{\listadd\ae@list@collection}{#1} ,
    arrange horizontally/.is if = ae@enumerate@inline
}

\newrobustcmd\aeset[1]{\pgfkeys{ae/.cd,#1}}

\newrobustcmd\aelist[1]{%
  \begingroup
    \aeset{#1}%
    \ifdefempty\ae@list@collection{%
      \@latex@warning@no@line{%
        \string\aelist: Empty List! I'll do nothing\on@line
      }%
    }
    {%
      \ifbool{ae@enumerate@inline}
        {\csuse{enumerate*}}
        {\enumerate}[label=(\alph*)]
      \forlistloop{\item}\ae@list@collection
      \ifbool{ae@enumerate@inline}
        {\csuse{endenumerate*}}
        {\endenumerate}%
    }%
    \endgroup
}

\begin{document}

\aelist{list collection={one,two}}

\aelist{list collection={one,two},arrange horizontally}

\aelist{list collection={one,two}}

\aeset{arrange horizontally=true}

\aelist{list collection={one,two}}

\end{document}


text:
Q: View Controller will not appear when Table View Controller Cell is Selected I am relatively new to Swift/Xcode and I am trying to make a view controller appear with different values when a button is selected (an add button) or a table view cell is selected (which allows them to edit). However, I am unable to get any response upon the selection of my row including a print statement I have put in for testing, although the segue does function when I link the transition to a button. The code is identical to that of a functioning table view cell I wrote previously that makes the current table view appear. Could this be an issue with the storyboard?
Storyboard screenshot with cell settings
Here is my code:
override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
    cell.textLabel?.text = items[indexPath.row].name
    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("Selected")
}

//Sends current receipt information to the AddItemViewController display when tapped
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "AddItemViewSegue" || segue.identifier == "EditItemViewSegue" {
        let destination = segue.destination as? AddItemViewController
        destination?.currentReceipt = currentReceipt
        let index = tableView.indexPathForSelectedRow?.row
        print("test")
        if segue.identifier == "AddItemViewSegue" {
            destination?.addMessage = "Add a New Item to Your Receipt"
            destination?.buttonMessage = "Add Item"
        }
        else {
            print("test1")
            destination?.addMessage = "Edit an Item in Your Receipt"
            destination?.buttonMessage = "Edit Item"
            destination?.currentItem = items[index!]
        }
    }
}

I have also looked into this forum post because it is similar to mine but I was unable to apply any of the suggested fixes.
https://developer.apple.com/forums/thread/14842

A: First of all the didSelectRow method is wrong. The code is Swift 2 code. The proper signature is
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { ...

Didn't you wonder why the compiler doesn't complain about the missing override?
Rather than from the view controller reconnect the segue (why are there 2 ones?) from the table view cell to the destination controller and delete didSelectRow


text:
Q: Routing from childs components "blinks" my navigation I'm trying to implement the routing for my application. When I'm routing from the firsts components in the tree, it's Ok (like app-menu or search), but when I'm in childs components (event-item or sticker), my app blinks : it displays the good page a few seconds (in a good way, I mean menus et search are well displayed (without all reloading), and result page in the router-outlet as wished), then go back to the root routing (so the resume one) with a whole-charging page. My route code is
(app.module.ts)

const appRoutes: Routes = [
  { path: 'profile', component: ProfileComponent },
  { path: 'resume', component: ResumeComponent },
  { path: 'result/:searchType', component: ResultComponent },
  { path: '', component: ResumeComponent }
];

My structure :
app-root
    app-search
    app-menu
       app-event-item
    app-resume
       app-sticker
    app-profile
    app-result

Extract of HTML code of app-root component :

       <app-menu></app-menu>

             <app-search></app-search>

       <router-outlet></router-outlet>

My code is simply  :
 [...]

where xxxx is my routing page ; that's what I've done on every navigation links (a or button or whatever), the ones working and the ones don't. I didn't had a ts ou js code to manage the routing. I thought this could be enough for my needs.
For example :
[...]

I tried adding a "/" thinking of a relative/absolute problem, but it don't seems to be my problem...
Thank you !

A: Actually I found my error
The link was embedded in another "a" tag having an

  [... some code]
     [...]
  [... some code]

When I remove the href, it's all OK.

  [... some code]
     [...]
  [... some code]


text:
Q: Fail to import Jackson Jersey and Jersey Client in Android Studio I am in trouble in using Jersey dependencies with Android Studio.
Here is my build.gradle file :
apply plugin: 'com.android.application'

android {
compileSdkVersion 22
buildToolsVersion "21.1.2"

defaultConfig {
    minSdkVersion 15
    targetSdkVersion 22
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
testCompile 'junit:junit:4.12'
compile 'javax.ws.rs:javax.ws.rs-api:2.0.1'
compile 'com.android.support:appcompat-v7:22.1.1'
compile files('libs/jersey-client-2.8.jar')
compile files('libs/jersey-media-json-jackson-2.8.jar')
}

I add the following import to my Activity :
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

public class LoginActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    Client client = ClientBuilder.newClient();

And I keep having the same ERROR :
FATAL EXCEPTION: main
Process: com.example.julie.myapplication, PID: 30599
java.lang.NoClassDefFoundError: org.glassfish.jersey.client.ClientConfig

It seems that the import fail, could someone please help me ?
Thanks a lot,
Julie

A: From Jersey version 2.16, it should be possible to use Jersey Client on Android. The support is still not perfect. refer this this info might be helpful who searches about Support of Jersey Client in android..


text:
Q: Core ML - Append Models to existing collection I have created a collection with 2 models on Core ML Deployment Dashboard under the Apple developer console. Now I want to add more models under the same collection but I don't see this option. How can I do that?

*

*Video from WWDC:
https://developer.apple.com/videos/play/wwdc2020/10152/

*Documentation: https://developer.apple.com/documentation/coreml/creating_and_deploying_a_model_collection


text:
Q: missing permissions required by BluetoothAdapter.isEnabled.BLUETOOTH I add bluetooth to my app but am running into the following problem. When I do the code:
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
    Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}

if(!bluetoothAdapter.isEnabled()) {
    Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableAdapter, 0);
}

The error is on the following line:
if(!bluetoothAdapter.isEnabled())

Error:

Missing permissions required by BluetoothAdapter.isEnabled :android.permissions.BLUETOOTH

I added the following permissions to the android manifest file:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<permission android:name="android.permission.BLUETOOTH" android:label="BLUETOOTH" />
<permission android:name="android.permission.BLUETOOTH_ADMIN" />

but am still getting the same issue. Do you know what I did wrong?

A: Let's say you have a button and then you click on it, Bluetooth needs to turn on. Here's a quick example how you would do it for Android 6.0 and above.
First, declare this variable in your Activity/Fragment:
public static final int PERMISSION_ASK = 1001;

Now, let's say this buttons is going to enable the bluetooth.
setOnClickListener:
myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(isBluetoothPermissionGranted()) {
                // app already has required permissions
                // do some task here
            } else {
                // app does not have permission yet.
                // ask for permissions
                askForBluetoothPermissions();
            }
        } else {
            // Android version below 6.0, no need to check or ask for permission
            // do some task here
        }
    }
});

Checking if application already has the required permission:
@RequiresApi(api = Build.VERSION_CODES.M)
private boolean isBluetoothPermissionGranted() {
    boolean granted = false;
    int bluetoothGranted = checkSelfPermission(Manifest.permission.BLUETOOTH);
    int bluetoothAdminGranted = checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN);

    if(bluetoothGranted == PackageManager.PERMISSION_GRANTED &&
            bluetoothAdminGranted == PackageManager.PERMISSION_GRANTED) {
        granted = true;
    }

    return granted;
}

If required permission is not granted, here's how you would ask for it:
@RequiresApi(api = Build.VERSION_CODES.M)
private void askForBluetoothPermissions() {
    String[] permissions = new String[] {
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN
    };
    requestPermissions(permissions, PERMISSION_ASK);
}

And finally, here's how you would confirm if the user granted you the permission(s) or not:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_ASK:
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                // all requested permissions were granted
                // perform your task here
            } else {
                // permissions not granted
                // DO NOT PERFORM THE TASK, it will fail/crash
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            break;
    }
}

Hope this helps

A: *

*You only need <uses-permission> tag since you are using a permission. You don't need <permissions> tag since this is not your custom permission.

*Maybe you have placed <uses-permission> tag in the wrong element in manifest, but I cannot say anything else with the information you provided

*Since your bluetoothAdapter can be null, either add to second IF null pointer check, or add a RETURN in first IF

*It is also nice to have <uses-feature> tag

A: For Android 6.0 and above you must add the following to manifest file
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<permission android:name="android.permission.BLUETOOTH" android:label="BLUETOOTH" />
<permission android:name="android.permission.BLUETOOTH_ADMIN" />
<permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<permission android:name="android.permission.ACCESS_COARSE_LOCATION" />


text:
Q: Segmentation fault while embedding Python into C Running the code from the answer of another post, I tried running the same on Linux, however I always encounter a segmentation fault. On trying to debug through gdb, it shows that the variable mymodule remains NULL even after appending the path of the current directory as described. Can anyone help me in letting me know what am I missing?
The code is as follows:
pyarray.c
#include <Python.h>
void initPython(void)
{

Py_Initialize();

PyObject *sysmodule = PyImport_ImportModule("sys");
PyObject *syspath = PyObject_GetAttrString(sysmodule, "path");
PyList_Append(syspath, PyBytes_FromString("."));

Py_DECREF(syspath);
Py_DECREF(sysmodule);
}

int callModuleFunc(int array[], size_t size) {

PyObject *pname=PyBytes_FromString((char *)"py_function");
PyObject *mymodule = PyImport_Import(pname);
if (mymodule==NULL)
{
    printf("Abort");
    exit(-1);
}
assert(mymodule != NULL);
PyObject *myfunc = PyObject_GetAttrString(mymodule,"printlist");
assert(myfunc != NULL);
PyObject *mylist = PyList_New(size);
size_t i;
for (i = 0; i != size; ++i) {
    PyList_SET_ITEM(mylist, i, PyLong_FromLong(array[i]));
}
PyObject *arglist = Py_BuildValue("(O)", mylist);
assert(arglist != NULL);
PyObject *result = PyObject_CallObject(myfunc, arglist);
assert(result != NULL);
int retval = (int)PyLong_AsLong(result);
Py_DECREF(result);
Py_DECREF(arglist);
Py_DECREF(mylist);
Py_DECREF(myfunc);
Py_DECREF(mymodule);
return retval;
}

 int main(int argc, char *argv[])
 {

 initPython();

 int a[] = {1,2,3,4,5,6,7};
 callModuleFunc(a, 4);
 callModuleFunc(a+2, 5);

 Py_Finalize();
 return 0;
 }

py_function.py
def printlist(mylist):
    print mylist
    return 0


text:
Q: "Instance member cannot be used on type" error in lazy property
Please help me solve this problem or tell me the right way to declaring this property.
// MARK: Properties
var expensiveItems = [Item]()
var cheapItems = [Item]()

lazy var allItems: [[Item]] = {
    return [cheapItems, expensiveItems]
}()

A: Because you're assigning the result of a closure to your lazily loaded property - you need to follow the closure rules. One of those rules is that if you're referring to self - you must do it explicitly. (although this isn't applicable for @noescape closures – but you can't use them here anyway)
This is simply so that you acknowledge that you're capturing and retaining self, but seeing as it's a lazily loaded property it shouldn't cause a retain cycle, as it is only called once and it's result is then assigned to the property.
Therefore you need to use self.cheapItems and self.expensiveItems.
// MARK: Properties
var expensiveItems = [Item]()
var cheapItems = [Item]()

lazy var allItems: [[Item]] = {
    return [self.cheapItems, self.expensiveItems]
}()


text:
Q: Is it possible to make a circular NSButton? I am trying to create a custom shape NSButton. In particular I am trying to make a round button, using a custom image. I've found a tutorial on the creation of custom UIButton and tried to adapt it to NSButton. But there's a huge problem. clipsToBounds seems to be iOS only(
Here's my code:
import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var mainButton: NSButton!
    var size = 32

    override func viewDidLoad() {
        super.viewDidLoad()
        configureButton()
                // Do any additional setup after loading the view.
    }
    func configureButton()
    {
        mainButton.wantsLayer = true
        mainButton.layerContentsRedrawPolicy = NSViewLayerContentsRedrawPolicy.OnSetNeedsDisplay
        mainButton.layer?.cornerRadius = 0.5 * mainButton.bounds.size.width
        mainButton.layer?.borderColor = NSColor(red:0.0/255.0, green:122.0/255.0, blue:255.0/255.0, alpha:1).CGColor as CGColorRef
        mainButton.layer?.borderWidth = 2.0
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }

}

What am I doing wrong? How can I make a circular NSButton? Can you suggest anything on replacing clipsToBounds?
Because here is what I was able to get so far:

A: NSButton is a subclass of NSView, so all methods in NSView, such as drawRect(_:), are also available in NSButton.
 So create a new Button.swift which you draw your custom layout
import Cocoa

class Button: NSButton {

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

        // Drawing code here.
        let path = NSBezierPath(ovalIn: dirtyRect)
        NSColor.green.setFill()
        path.fill()
    }

}

Great Tutorial Here. It is iOS , but quite similar!

A: Don't play around with corner radius. A circle doesn't have corners. To make the button appear as a circle, mask the button's layer to a circle.

A: You are setting the radius based upon the width of the button.  By the look of your screenshot, the button is not a square when you start, so rounding the corners cannot create a circle.