text:
Q: Is there an AWS service that provides <= 20 milliseconds query latency? For a use-case, my team is using DynamoDB to query a GSI. With increasing number of rows returned, the query latency increases.
Our code looks something like this (Java) (pretty normal)
        Map<String, Condition> keyConditions = new HashMap<>();
        keyConditions.put(indexHashKeyName, new Condition()
                .withAttributeValueList(Collections.singletonList(new AttributeValue(identifier.toString())))
                .withComparisonOperator(ComparisonOperator.EQ));
        QueryRequest queryRequest = new QueryRequest();
        queryRequest.setTableName(tableName);
        queryRequest.setIndexName(indexName);
        queryRequest.setKeyConditions(keyConditions);
        queryRequest.withAttributesToGet(attributesRequired);
        QueryResult result = dynamoDB.query(queryRequest);

Our DynamoDB table has about 4-5 attributes of type String. We use AWS KMS for encryption-at-rest, and all 4-5 attributes are present in the GSI.
We see p99 latencies on the GSI as typically 30-40ms (milliseconds) for retrieving ~30 rows of data.
Is there a good way to reduce this latency (apart from caching)? Caching is not a viable solution for the pattern of client traffic our service receives.
We were looking into a couple of options:-

*

*Create a DynamoDB new table which is indexed on the GSI-hash-key, with all data stored as a JSON blob (or compressed blob). This would reduce latency since the Query would now become a GET. But this would get difficult once items grow beyond the 400KB attribute size limit.

*Create a new DynamoDB table which is indexed on the GSI-has-key, and has a range key of 1,2,3... and everytime a blob of data exceeds 400KB, create a new range item, and do multiple GETs to retrieve multiple rows of JSON blobs. This would increase latency once too many range keys start getting created for a given hash key.

*Using ElasticSearch to do the above (presumably ElasticSearch has less limitations of size of a document), but we're not sure whether latencies would be similar or worse than DynamoDB query latencies.
Is there any other database solution AWS provides that would help for our use-cases?
Note:- Our EC2 hosts are in the same region as our DynamoDB table. The latency of 30-40ms is purely for dynamoDB query.

A: *

*I think you talking about query time, not latency. If you need to improve latency you can use VPC endpoints. Actually, by default, DDB works over public internet

*If you want to improve query time, maybe you need to change RCU capacity. Or switch to on-demand pricing


text:
Q: The used SELECT statements have a different number of columns in codeigniter
Error Number: 1222
  The used SELECT statements have a different number of columns

This is controller
    <?php
    class Autocomplete extends CI_Controller{
        function __construct() {
            parent::__construct();
            $this->load->model('datacomplete');
        }

        public function index(){
            $this->load->view('view_demo');
        }
        public function GetCountryName(){
            $keyword=$this->input->post('keyword');
            $data=$this->datacomplete->GetRow($keyword);

            echo json_encode($data);
        }

    }
    ?>

This is model
        <?php
    class Datacomplete extends CI_Model{

        public function GetRow($keyword) {
           $this->db->select('collg_name,city,state,country as type');
           $this->db->from('tbl_college');
           $this->db->like("collg_name",$keyword);
           $this->db->or_like('city',$keyword,'after');
           $this->db->or_like('state',$keyword,'after');
           $this->db->or_like('country',$keyword,'after');
           $query1 = $this->db->get_compiled_select();
           $this->db->select('course_offrd_name,category_name,subcategory_name');
           $this->db->from('tbl_course_offered');
           $this->db->like("course_offrd_name",$keyword);
           $this->db->or_like('category_name',$keyword,'after');
           $this->db->or_like('subcategory_name',$keyword,'after');
           $query2 = $this->db->get_compiled_select();
           $result = $this->db->query($query1." UNION ".$query2);
           return $result->result();
        }
    }

This is view
    <!DOCTYPE html>

            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">

AUTOCOMPLETE FORM FROM DATABASE USING CODEIGNITER AND AJAX

                        Country Name
                        <input style="height:70px" type="text" id="country" autocomplete="off" name="country" class="form-control" placeholder="Type to get an Ajax call of Countries">

    This is custom.js

    $(document).ready(function () {
        $("#country").keyup(function () {
            $.ajax({
                type: "POST",
                url: "http://localhost/codeajax/autocomplete/GetCountryName",
                data: {
                    keyword: $("#country").val()
                },
                dataType: "json",
                success: function (data) {

                    if (data.length > 0) {
                        $('#DropdownCountry').empty();
                        $('#country').attr("data-toggle", "dropdown");
                        $('#DropdownCountry').dropdown('toggle');
                    }
                    else if (data.length == 0) {
                        $('#country').attr("data-toggle", "");
                    }
                    $.each(data, function (key,value) {
                        if (data.length >= 0)
                            $('#DropdownCountry').append('
' + value['name'] + '
');
                    });
                }
            });
        });
        $('ul.txtcountry').on('click', 'li a', function () {
            $('#country').val($(this).text());
        });
    });

Here i m trying to search a keyword from three table using codeigniter and ajax.
I'm getting that error in the model
How can I solve this issue?
Also, if the issue is solved whether my search will fetch the data from database.
What is wrong in the code?

A: You have to use same column number in your select statement as following
First select you use 4 columns :
$this->db->select('collg_name,city,state,country as type');

second select you use 3 columns :

$this->db->select('course_offrd_name,category_name,subcategory_name');

class Datacomplete extends CI_Model{

    public function GetRow($keyword) {
       $this->db->select('collg_name,city,state,country as type');
       $this->db->from('tbl_college');
       $this->db->like("collg_name",$keyword);
       $this->db->or_like('city',$keyword,'after');
       $this->db->or_like('state',$keyword,'after');
       $this->db->or_like('country',$keyword,'after');
       $query1 = $this->db->get_compiled_select();
       $this->db->select('course_offrd_name,category_name,subcategory_name, null as type');
       $this->db->from('tbl_course_offered');
       $this->db->like("course_offrd_name",$keyword);
       $this->db->or_like('category_name',$keyword,'after');
       $this->db->or_like('subcategory_name',$keyword,'after');
       $query2 = $this->db->get_compiled_select();
       $result = $this->db->query($query1." UNION ".$query2);
       return $result->result();
    }
}

A: In '$result = $this->db->query($query1." UNION ".$query2);' you are combining 2 table results but in 1st table you are selecting 4 columns & in 2nd table you are selecting 3 columns.
When You combine using UNION then it will result into records & here both table columns are different  and also the column count is different. To use UNION you have to select same column count & if possible then select same columns only.
In above situation error occure bcz:
                     + collg_name + city + state + type +
---------------------+------------+------+-------+------+
1st table record     + A          + b    + c     + d    +
---------------------+------------+------+-------+------+
2nd table record     + x          + y    + z     + -    +

2nd table don`t have last column value
Union execute in below condition:
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

Result :
        + City +
1st tbl | city1|
1st tbl | city2|
2st tbl | city3|

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oracle shifts in work with dates Can you help me with shifts? I need to assign each event what shift it is.
I want to count how many items machine done in every shift. "ILE" means "HOW MANY ITEMS IN SHIFT WERE DONE"
    SELECT lz.EVENT,
    TO_CHAR(lz.DATA_ZATW, 'YYYY-MM-DD') AS DATA,
            CASE WHEN TO_CHAR(lz.DATA_ZATW, 'HH24:MI') BETWEEN '06:00' AND '13:59' THEN 'First Shift'
                 WHEN TO_CHAR(lz.DATA_ZATW, 'HH24:MI') BETWEEN '14:00' AND '21:59' THEN 'Second Shift'
                 WHEN TO_CHAR(lz.DATA_ZATW, 'HH24:MI') BETWEEN '22:00' AND '23:59' THEN 'Third Shift'
                 WHEN TO_CHAR(lz.DATA_ZATW, 'HH24:MI') BETWEEN '00:00' AND '05:59' THEN 'Third Shift'
                 END AS SHIFT

FROM PLC.LIST lz;

But when I check now query and I have third shift of 2017-08-03 and it is wrong because according to sysdate I shound have first shift only.
Any idea?
EDIT:
Whole query
SELECT "DATA",
           "ZMIANA",
           "SOV_GAO_1_ILE",
           "SOV_GAD_2_ILE",
           "SOV_GAM_3_ILE"
      FROM (SELECT TO_CHAR(lz.DATA_ZATW, 'YYYY-MM-DD') AS DATA,
                  CASE WHEN TO_CHAR(lz.DATA_ZATW, 'HH24:MI:SS') BETWEEN '06:00:00' AND '13:59:59.999999' THEN 1
                       WHEN TO_CHAR(lz.DATA_ZATW, 'HH24:MI:SS') BETWEEN '14:00:00' AND '21:59:59.999999' THEN 2
                       WHEN TO_CHAR(lz.DATA_ZATW, 'HH24:MI:SS') BETWEEN '22:00:00' AND '23:59:59.999999' THEN 3
                       WHEN TO_CHAR(lz.DATA_ZATW, 'HH24:MI:SS') BETWEEN '00:00:00' AND '05:59:59.999999' THEN 3
                        END AS ZMIANA,
                   lz.LINIA,
                   lz.DETAL
          FROM PLC.LISTA_ZDARZEN lz
          GROUP BY lz.DATA_ZATW,
                   lz.LINIA,
                   lz.DETAL) PIVOT (COUNT(DETAL) AS ILE FOR LINIA IN ('SOV_GAO_1' SOV_GAO_1, 'SOV_GAD_2' SOV_GAD_2, 'SOV_GAM_3' SOV_GAM_3));

EDIT:
SHIFTS
6-14 01.08 first shift
14-22 01.08 second shift
22-00 01.08 third shift
00-6 02.08 third shift

6-14 02.08 first shift
14-22 02.08 second shift
22-00 02.08 third shift
00-6 03.08 third shift

6-14 03.08 first shift
14-22 03.08 second shift
22-00 03.08 third shift
00-6 04.08 third shift

HERE ARE DATES:
SELECT TO_DATE('2017-08-01 23:54:56', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 01.08 Third shift
    SELECT TO_DATE('2017-08-01 23:57:58', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 01.08 Third shift
    SELECT TO_DATE('2017-08-02 03:54:56', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 01.08 Third shift
    SELECT TO_DATE('2017-08-02 04:54:56', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 01.08 Third shift
    SELECT TO_DATE('2017-08-02 06:54:56', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 02.08 First shift
    SELECT TO_DATE('2017-08-02 07:54:56', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 02.08 First shift
    SELECT TO_DATE('2017-08-02 10:24:34', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 02.08 First shift
    SELECT TO_DATE('2017-08-02 14:54:56', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 02.08 Second shift
    SELECT TO_DATE('2017-08-02 15:54:56', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 02.08 Second shift
    SELECT TO_DATE('2017-08-02 19:21:10', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 02.08 Second shift
    SELECT TO_DATE('2017-08-02 22:54:56', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 02.08 Third shift
    SELECT TO_DATE('2017-08-02 23:55:20', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 02.08 Third shift
    SELECT TO_DATE('2017-08-02 23:55:56', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 02.08 Third shift
    SELECT TO_DATE('2017-08-03 00:02:34', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 02.08 Third shift
    SELECT TO_DATE('2017-08-03 00:05:34', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 02.08 Third shift
    SELECT TO_DATE('2017-08-03 00:10:38', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 02.08 Third shift
    SELECT TO_DATE('2017-08-03 09:01:24', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 03.08 First shift
    SELECT TO_DATE('2017-08-03 09:01:32', 'yyyy-mm-dd hh24:mi:ss') FROM DUAL UNION ALL -- 03.08 First shift
    SELECT TO_DATE('2017-08-03 17:01:10', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 03.08 Second shift
    SELECT TO_DATE('2017-08-03 19:28:45', 'yyyy-mm-dd hh24:mi:ss') FROM DUAL UNION ALL -- 03.08 Second shift
    SELECT TO_DATE('2017-08-03 23:54:56', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 03.08 Third shift
    SELECT TO_DATE('2017-08-03 23:55:20', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL -- 03.08 Third shift
    SELECT TO_DATE('2017-08-03 23:55:56', 'yyyy-mm-dd hh24:mi:ss') FROM DUAL           -- 03.08 Third shift

A: Maybe try this:
CASE WHEN TO_CHAR(lz.DATA_ZATW, 'HH24MI') BETWEEN 600 AND 1359 THEN 'First Shift'
     WHEN TO_CHAR(lz.DATA_ZATW, 'HH24MI') BETWEEN 1400 AND 2159 THEN 'Second Shift'
     WHEN TO_CHAR(lz.DATA_ZATW, 'HH24MI') BETWEEN 2200 AND 2359 THEN 'Third Shift'
     WHEN TO_CHAR(lz.DATA_ZATW, 'HH24MI') BETWEEN 0 AND 559 THEN 'Third Shift'
END AS SHIFT

or like this:
CASE WHEN (lz.DATA_ZATW - TRUNC(lz.DATA_ZATW)) * INTERVAL '1' DAY BETWEEN INTERVAL '6' HOUR AND INTERVAL '13:59:59.999999' HOUR TO SECOND THEN 'First Shift'
CASE WHEN (lz.DATA_ZATW - TRUNC(lz.DATA_ZATW)) * INTERVAL '1' DAY BETWEEN INTERVAL '14' HOUR AND INTERVAL '21:59:59.999999' HOUR TO SECOND THEN 'Second Shift'
...

According to your sample data it works:
WITH t (DATA_ZATW) AS (
    SELECT TO_DATE('2017-08-03 09:03:31', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:03:11', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:03:07', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:02:44', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:02:22', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:02:21', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:01:58', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:01:32', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:01:24', 'yyyy-mm-dd hh24:mi:ss') FROM dual)
SELECT DATA_ZATW,
    CASE
        WHEN TO_CHAR(DATA_ZATW, 'HH24MI') BETWEEN 600 AND 1359 THEN 'First Shift'
        WHEN TO_CHAR(DATA_ZATW, 'HH24MI') BETWEEN 1400 AND 2159 THEN 'Second Shift'
        WHEN TO_CHAR(DATA_ZATW, 'HH24MI') BETWEEN 2200 AND 2359 THEN 'Third Shift'
        WHEN TO_CHAR(DATA_ZATW, 'HH24MI') BETWEEN 0 AND 559 THEN 'Third Shift'
    END AS SHIFT
FROM t;

DATA_ZATW   SHIFT
03.08.2017 09:03:31 First Shift
03.08.2017 09:03:11 First Shift
03.08.2017 09:03:07 First Shift
03.08.2017 09:02:44 First Shift
03.08.2017 09:02:22 First Shift
03.08.2017 09:02:21 First Shift
03.08.2017 09:01:58 First Shift
03.08.2017 09:01:32 First Shift
03.08.2017 09:01:24 First Shift

I assume at the end you are looking for something like this:
WITH t (DATA_ZATW) AS (
    SELECT TO_DATE('2017-08-03 09:03:31', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:03:11', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:03:07', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:02:44', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:02:22', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:02:21', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:01:58', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:01:32', 'yyyy-mm-dd hh24:mi:ss') FROM dual UNION ALL
    SELECT TO_DATE('2017-08-03 09:01:24', 'yyyy-mm-dd hh24:mi:ss') FROM dual)
SELECT TRUNC(DATA_ZATW), SHIFT, COUNT(*)
FROM
(
SELECT DATA_ZATW,
    CASE
        WHEN TO_CHAR(DATA_ZATW, 'HH24MI') BETWEEN 600 AND 1359 THEN 'First Shift'
        WHEN TO_CHAR(DATA_ZATW, 'HH24MI') BETWEEN 1400 AND 2159 THEN 'Second Shift'
        WHEN TO_CHAR(DATA_ZATW, 'HH24MI') BETWEEN 2200 AND 2359 THEN 'Third Shift'
        WHEN TO_CHAR(DATA_ZATW, 'HH24MI') BETWEEN 0 AND 559 THEN 'Third Shift'
    END AS SHIFT
FROM t
)
GROUP BY TRUNC(DATA_ZATW), SHIFT;

A: I think that the only thing You have to do is to substract six hours from data_zatw to assign it to previous day.
select data_zatw, trunc(data_zatw - interval '6' hour) shift_date,
       case when to_char(data_zatw, 'HH24') >= '06'
             and to_char(data_zatw, 'HH24') <  '14' then 1
            when to_char(data_zatw, 'HH24') >= '14'
             and to_char(data_zatw, 'HH24') <  '22' then 2
            when to_char(data_zatw, 'HH24') >= '22'
              or to_char(data_zatw, 'HH24') <  '06' then 3
       end shift
  from lz

Then make your pivot and aggregations and pivot.
Test data:
with lz as (
  select to_date(column_value, 'yyyy-mm-dd hh24:mi:ss') data_zatw
    from table(
      sys.odcivarchar2list(
        '2017-08-01 23:54:56', '2017-08-01 23:57:58', '2017-08-02 03:54:56',
        '2017-08-02 04:54:56', '2017-08-02 06:54:56', '2017-08-02 07:54:56',
        '2017-08-02 10:24:34', '2017-08-02 14:54:56', '2017-08-02 15:54:56',
        '2017-08-02 19:21:10', '2017-08-02 22:54:56', '2017-08-02 23:55:20',
        '2017-08-02 23:55:56', '2017-08-03 00:02:34', '2017-08-03 00:05:34',
        '2017-08-03 00:10:38', '2017-08-03 09:01:24', '2017-08-03 09:01:32',
        '2017-08-03 17:01:10', '2017-08-03 19:28:45', '2017-08-03 23:54:56',
        '2017-08-03 23:55:20', '2017-08-03 23:55:56')))
select data_zatw, trunc(data_zatw - interval '6' hour) shift_date,
       case when to_char(data_zatw, 'HH24') >= '06'
             and to_char(data_zatw, 'HH24') <  '14' then 1
            when to_char(data_zatw, 'HH24') >= '14'
             and to_char(data_zatw, 'HH24') <  '22' then 2
            when to_char(data_zatw, 'HH24') >= '22'
              or to_char(data_zatw, 'HH24') <  '06' then 3
       end shift
  from lz


text:
Q: Custom variable in module How can I create custom variable in helper.php file set it right here and use it in tmpl file? Example:
in helper.php I add variable
 $customstring = 'My string';

Then I want to display this variable in i.e tmpl/default.php
<?php echo $customstring; ?>

Not working. What's wrong here?

A: Include your helper in the main module file (mod_mymodule.php) and then call the right function and use the variable in the view, this is an example:
http://blog.joomlaearth.com/2012/create-you-first-joomla-1-6-module-completely-from-scratch/

A: Your helper file should contain a function or class and should return the result(s) you want to pass back.
If your module's main file is similar to the mod_weblinks.php file
You populate your variable like so
$list = modWeblinksHelper::getList($params);

and $list is in scope and automatcally available to you within your view and its tmpl files.
If your module is more complex then have a look through some of the other modules within the site.


text:
Q: React missing an onClick? I have the following code in a component:
  deleteShare: function(e) {
    console.dir(e);
  },

  render: function() {
    createShare = function(share) {
      return (

          {share}
          x

      )
    }

    return (

        <input type='hidden' name='shares' value={this.state.shares.join(',')} />

          {this.state.shares.map(createShare)}
          <input type='text' id='new_share' placeholder='Add an email' onKeyDown={this.addShare}/>

    )
  }

However, I'm finding that the onClick on a anchor in createShare doesn't appear to trigger, like it's not binding.  There's no error or anything in the console.
I assume there's something funky going on with the way React is setting up bindings to the event, or some sort of context issue.  How can I resolve this?

A: In createShare this will be bound to window, as it is inside the function.
You could change createShare to a method on the component, and React will autobind it to the component, or bind it to what you expect with Function.prototype.bind
Another nice solution is ES6 arrow functions which bind this to the scope they are defined in, but that will take a bit of setup


text:
Q: Missing 3rd party dependencies on Github that are resolved correctly on computer I'm moving a website off Weebly to host on Github.
I downloaded the website as a zip from Weebly. Opening it on my computer, it looks perfect. When I upload it on Github, I see that it's missing several sources:

*

*cdn2.editmysite.com

*fonts.googleapis.com

*fonts.gstatic.com

The sources are still referenced in the HTML, but I don't see it show up in the Chrome development tool. I see the development tool list "(no domain)" as a source instead. Ajax.googleapis.com is referenced correctly as a source.
What is going on to make the exact same code behave differently when it's hosted on Github vs when it's in repo on my computer?
Here's the Github repo: github.com/robbyhowell/robbyhowell.github.io
Here's Github page live: robbyhowell.github.io
Here's how it should look: www.elementaltheory.net

A: This was caused by mix-content blocks. Github defaults to using https. I had scripts in http.


text:
Q: Getting following exception org.apache.bcel.verifier.exc.AssertionViolatedException I am getting following error while executing my java code. What is this error and how it can be removed? I googled and mostly people have talked bugs related to bcel.
Can anyone direct me to the relevant website with details. Thanks for your time.
  Exception in thread "main" org.apache.bcel.verifier.exc.AssertionViolatedException:
  FOUND:
  INTERNAL ERROR: Oops!
  Exiting!!

  at org.apache.bcel.verifier.exc.AssertionViolatedException.main(AssertionViolatedException.java:102)

A: This exception is thrown when BCEl tries to verify bytecode modifications and fails.
You are clearly doing something (either yourself or through some tool) that uses BCEL to modify the bytecode your Java compiler produces.
If you are working with BCEL yourself, you should be able to figure out what you are doing and why this breaks.
If it's a tool, figure out which one and report a bug. Typical candidates are things like code coverage tools, badly coded AOP stuff or some crazy research tool.

A: Right click on java program, select Run As and > "Java Application".


text:
Q: Incremental Game c# My name is John and I'm trying to do basic Incremental game in c# WFA
I managed to do clickable button that adds value to my money
Clickable button which upgrade the value, decrease my money by price and increase the price (If i have enough money) else just show messagebox
I want to add the idle like money per second but still be able to use buttons SO- everysecond x money will be added and i still can use buttons even when it is not necessary
Code:
    using System;
    using System.Windows.Forms;

    namespace WindowsFormsApplication1
    {
public partial class Form1 : Form
{
    public void Ref()
    {
        lbl_Money.Text = money.ToString();
        lbl_PerTap.Text = upgrade.ToString();
        lbl_Price.Text = price.ToString();
    }

    int money = 0;
    int upgrade = 1;
    int price = 64;

    public Form1()
    {
        InitializeComponent();
        Ref();
    }

    private void Tap_Clicked(object sender, EventArgs e)
    {
        money += upgrade;
        Ref();
    }

    private void Upgrade_Clicked(object sender, EventArgs e)
    {
        if(money >= price)
        { //Ano
            upgrade += 1;
            money -= price;
            price += (price / 16);
        }
        else
        { //NE
            MessageBox.Show("Not Enough Money!");
        }
        Ref();
    }

}

A: A basic Timer (fix it to suit your needs):
Add this in the class:
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer() { Interval = 1000 };

and this in the constructor:
timer.Tick += Timer_Tick;
timer.Start();

And this, too, in the class:
private void Timer_Tick(object sender, EventArgs e)
{
    money += upgrade;
}


text:
Q: Reuse SQL Server cursor with different parameter value? I wonder whether cursor for query with @variable parameter can be re-used (CLOSE + OPEN) when value of the @variable changes. To me it looks that it always needs CLOSE + DEALLOCATE + DECLARE + OPEN to take new value of the @variable into effect. Perhaps no big deal, but I wanted to know whether DEALLOCATE + DECLARE can be left out between uses.
Here you have complete simple example to try it out:
DECLARE @ta TABLE (a int);
INSERT INTO @ta (a) VALUES (1),(2),(4),(8),(16),(32),(64);
---------
DECLARE @current_a int;
DECLARE @threshold int = 12;
DECLARE crs1 CURSOR FOR SELECT a FROM @ta WHERE a < @threshold;

--- first cursor use
OPEN crs1;

    FETCH NEXT FROM crs1 INTO @current_a;
    WHILE @@FETCH_STATUS = 0
        BEGIN
            SELECT @threshold, @current_a
            FETCH NEXT FROM crs1 INTO @current_a;
        END;

CLOSE crs1;
DEALLOCATE crs1; -- can this be left out?

SET @threshold = 3;
DECLARE crs1 CURSOR FOR SELECT a FROM @ta WHERE a < @threshold;  -- can this be left out?

--- second cursor use
OPEN crs1;

    FETCH NEXT FROM crs1 INTO @current_a;
    WHILE @@FETCH_STATUS = 0
        BEGIN
            SELECT @threshold, @current_a
            FETCH NEXT FROM crs1 INTO @current_a;
        END;

CLOSE crs1;
DEALLOCATE crs1;

This was linearized example, but the question applies also to nested cursors when outer cursor changes the query parameter of inner cursor.

A: One way is to use cursor variable:

DECLARE
{
    { @local_variable [AS] data_type  | [ = value ] }
  | { @cursor_variable_name CURSOR }

@cursor_variable_name
Is the name of a cursor variable. Cursor variable names must begin with an at (@) sign and conform to the rules for identifiers.
CURSOR
Specifies that the variable is a local cursor variable.
A cursor variable:

*

*Can be the target of either a cursor type or another cursor variable. For more information, see SET @local_variable.

*Can be referenced as the target of an output cursor parameter in an EXECUTE statement if the cursor variable does not have a cursor
  currently assigned to it.

*Should be regarded as a pointer to the cursor.

DECLARE crs1 CURSOR FOR SELECT a FROM @ta WHERE a < @threshold;
-- could be changed to
DECLARE @crs1 CURSOR;
SET @crs1 = CURSOR FOR SELECT a FROM @ta WHERE a < @threshold;

LiveDemo


text:
Q: GetPrivateProfileString: Strange Behaviour, works only when the file is excluded and included again in project I am working on a migration project from VB6 to VB.NET 4.0 (VS 2013 Professional) where I am supposed to use INI file for reading inputs (client requirements).
To read a specific file path, code calls the function to read INI file. The declaration is as:
Dim i As Integer = IniFile.GetPrivateProfileString(Section, Key, "", temp, 1024, m_sIniFileName)

 <DllImport("kernel32")> _
Public Shared Function GetPrivateProfileString(ByVal section As String, ByVal key As String, ByVal def As String, ByVal retVal As System.Text.StringBuilder, ByVal size As Integer, ByVal filePath As String) As Integer
End Function

where m_sIniFileName is of type String.
The strange thing is, when I freshly open the solution, no value is returned from "GetPrivateProfileString", but when I exclude and then include the Class file (which includes this code), the expected value is returned and it works fine till the time I close and open the solution again.
Any idea what wrong is going on here?

A: As suggested by David Heffernan, we agreed to stop using GetPrivateProfileString, instead we are using now XMLs to fix this up.
Though this technology is quite primitive and not recommended at all, but just to answer the question, I worked and found what the actual problem was.
The issue was with "m_sIniFileName".
The Software which was changing the IniFiles didn't have privelges to actually modify the C:\WINDOWS\Win.Ini (files from where we are reading the values) , instead the values were getting updated in Virtual Store,
C:\Users(User)\AppData\Local\VirtualStore\Windows\win.ini.
Please refer to the  link for more information.
So, users has to grant the permission to the third party software to modify C:\WINDOWS\Win.Ini (not recommended)
Once the full access is granted to the software, it worked.
This solution is highly NOT recommended, please use another methods to achieve the same functionality


text:
Q: get touchEvent outside alertDialog I have a main view (SurfaceView) in which i open an alertDialog without buttons to show some information. So then the alertDialog is a small window above the main view.
I want to close the alertDialog when the user touch anywhere on the screen.
Until now i can close the alertDialog with the touchEvent in the alertDialog.
Is there an attribute on the alterDialog or on the surfaceView?
Can i kind of activate the touchEvent listener on the surfaceView even the alertDialog is showing?
Android 2.3.3
I found additional Information about my Task on this question: dialog dismiss.
Now i set this two flags (my dialog is not modal):
FLAG_NOT_TOUCH_MODAL, FLAG_WATCH_OUTSIDE_TOUCH
Unfortunately in the override of the touchevent i never receive the event MotionEvent.ACTION_OUTSIDE when touch outside the dialog.
In my Activity i do this:
alertBuilder.setView(mDialogLayout);
alertDialog = alertBuilder.create();
alertDialog.setOwnerActivity(this);

And later in a other class i do that:
alertDialog.show();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alertDialog.getWindow().getAttributes());
lp.width = (int)(oJassSurfaceView.oCanvas.getWidth() *Constants.d_FactorResizeDialogWidth);

lp.height = (int)(oJassSurfaceView.oCanvas.getHeight() *Constants.d_FactorResizeDialogHeight);

lp.x=Constants.iX_PositionDialog;

lp.y=Constants.iY_PositionDialog;

alertDialog.getWindow().setAttributes(lp);
alertDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);

alertDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);

where is the mistake? do i need to follow a certain order when i set the flags?


text:
Q: ¿Cómo puedo traer más datos a la vista? Estoy aprendiendo a usar .Net solo que tengo una duda, ¿Cómo traigo mas atributos de una tabla?
Por ejemplo, de la tabla grupo muestro el grupo pero con tiene relación con la tabla alumno traigo al alumno, en la alumno tengo otros atributos que quiero mostrar pero no sé cómo traerlos, estuve investigando que usaban LINQ que es equivalente a JOIN pero no me quedo la implementación.

Controlador Grupo

namespace WebApplication1.Controllers

{
    public class grupoController : Controller
    {
        private exampleEntities1 db = new exampleEntities1();
    // GET: grupo
    public ActionResult Index()
    {
        var grupo = db.grupo.Include(g => g.alumno);
        return View(grupo.ToList());
    }

    // GET: grupo/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        grupo grupo = db.grupo.Find(id);
        if (grupo == null)
        {
            return HttpNotFound();
        }
        return View(grupo);
    }

    // GET: grupo/Create
    public ActionResult Create()
    {
        ViewBag.id_alumno = new SelectList(db.alumno, "id_alumno", "nom");
        return View();
    }

    // POST: grupo/Create
    // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
    // más información vea https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "id_grupo,nom_grupo,id_alumno")] grupo grupo)
    {
        if (ModelState.IsValid)
        {
            db.grupo.Add(grupo);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.id_alumno = new SelectList(db.alumno, "id_alumno", "nom", grupo.id_alumno);
        return View(grupo);
    }

    // GET: grupo/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        grupo grupo = db.grupo.Find(id);
        if (grupo == null)
        {
            return HttpNotFound();
        }
        ViewBag.id_alumno = new SelectList(db.alumno, "id_alumno", "nom", grupo.id_alumno);
        return View(grupo);
    }

    // POST: grupo/Edit/5
    // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
    // más información vea https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "id_grupo,nom_grupo,id_alumno")] grupo grupo)
    {
        if (ModelState.IsValid)
        {
            db.Entry(grupo).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.id_alumno = new SelectList(db.alumno, "id_alumno", "nom", grupo.id_alumno);
        return View(grupo);
    }

    // GET: grupo/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        grupo grupo = db.grupo.Find(id);
        if (grupo == null)
        {
            return HttpNotFound();
        }
        return View(grupo);
    }

    // POST: grupo/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        grupo grupo = db.grupo.Find(id);
        db.grupo.Remove(grupo);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

}

A: Imagino estas usando Entity Framework (EF)
La clave esta en tu linea de código
var grupo = db.grupo.Include(g => g.alumno);

Con esta, básicamente, estas diciendo que también se incluyan los alumnos pertenecientes al grupo. Un 'inner join', al final del día.
Hasta aquí, lo tienes bien. Lo que necesitas hacer ahora es usaron en tu vista. Y como no muestras el código de la vista, pondré algo genérico para que te des una idea de como se usa en la vista.
@model List<WebApplication2.Models.Grupo>

            Nombre

    @foreach (var grupo in Model)
    {

                @foreach (var alumno in grupo.Alumnos)
                {
                    @alumno.Nombre
                }

    }

O hacer llamado a uno en especifico:
@Model.FirstOrDefault().Alumnos.FirstOrDefault().Nombre

etc..


text:
Q: popup can't close (IBAction not working) I use a popup system that I found here : https://blog.typpz.com/2013/12/09/ios-sdk-create-a-pop-up-window/
And after following the guide step by step everything works except the closing button. I tried to link it in various ways but nothing works.
Does anyone know what I do wrong ?
here is my code:
PopUpController.h:
#import <UIKit/UIKit.h>
//#import <QuartzCore/QuartzCore.h>
#import "AppDelegate.h"

@interface PopUpViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *popUpView;

- (void)showInView:(UIView *)aView animated:(BOOL)animated;
- (IBAction)closePopup:(id)sender;

@end

PopUpController.m:
#import "PopUpViewController.h"

@interface PopUpViewController ()

@end

@implementation PopUpViewController

- (void)viewDidLoad {
  self.view.backgroundColor=[[UIColor blackColor]     colorWithAlphaComponent:.6];
self.popUpView.layer.cornerRadius = 5;
self.popUpView.layer.shadowOpacity = 0.8;
self.popUpView.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
self.popUpView.clipsToBounds = YES;
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

#pragma animation

- (void)showAnimate
{
self.view.transform = CGAffineTransformMakeScale(1.3, 1.3);
self.view.alpha = 0;
[UIView animateWithDuration:.25 animations:^{
    self.view.alpha = 1;
    self.view.transform = CGAffineTransformMakeScale(1, 1);
}];
}

- (void)removeAnimate
{
[UIView animateWithDuration:.25 animations:^{
    self.view.transform = CGAffineTransformMakeScale(1.3, 1.3);
    self.view.alpha = 0.0;
} completion:^(BOOL finished) {
    if (finished) {
        [self.view removeFromSuperview];
    }
}];
}

- (void)showInView:(UIView *)aView animated:(BOOL)animated
{
[aView addSubview:self.view];
if (animated) {
    [self showAnimate];
}
}

- (IBAction)closePopup:(id)sender {
NSLog(@"closing...");
[self removeAnimate];
}

@end

NOTE: I don't even get the NSLog closing... on my console when I click the closing button
here is a screenshot of my .xib file:

Thank you for your response.


text:
Q: How-to stream H.264 with netcat? I use this command to stream a live video from a Raspberry camera:
raspivid -n -ih -t 0 -rot 0 -w 1280 -h 720 -fps 15 -b 1000000 -o - | nc -lkv4 5001

I need a way to stream a H.264 file through netcat like the example above. It must be received in the same way than my Raspberry camera.

A: If your input file is h264, I guess you can simply pipe the file in netcat:
For instance:
cat <yourfile> | nc -lkv4 5001

If you need to do some transcoding you can use ffmpeg. For instance from a MP4/FLV file (see original answer here):
ffmpeg -i <your file>.flv -vcodec copy -an -bsf:v h264_mp4toannexb | nc -lkv4 5001


text:
Q: Integration test for server I have server that should perform some job before start, and log about success. For example:
const http = require('http');

function startServer() {
    const server = http.createServer((req, res) => {
        res.write('hello\n');
        res.end();
    }).listen(3000);
    console.log('server is ready');
}

//as 'job' we will use timer
setTimeout(startServer, 10000);

I need create integration tests that will check:

*

*log contains information about server is ready

*request/response work correct

Questions:

*

*Should I run server for every test case or enough single instance?

*Job before start server takes some time.
How I know when need send
request? I cannot rely on log since in this case second test will
dependent on result of first one.

A: Wyck, do you suggest using the observer pattern? Something like that:
describe('app', () => {
    let orchestrator;
    let process;

    beforeAll(() => {
        jest.setTimeout(50000);
        orchestrator = (function () {
            const listeners = [];
            let serverIsReady = false;
            return {
                addListener: fn => {
                    listeners.push(fn);
                    fn(serverIsReady);
                },
                setServerIsReady: status => {
                    serverIsReady = status;
                    listeners.forEach(item => item(status));
                },
            }
        })();
    });

    test('server is ready', done => {
        process = spawn('node', ['./app.js']);
        process.stdout.on('data', data => {
            expect(`${data}`).toContain('server is ready');
            orchestrator.setServerIsReady(true);
            done();
        });
    });

    test('server return response', done => {
        orchestrator.addListener(serverIsReady => {
            if (serverIsReady) {
                http.get('http://localhost:3000', res => {
                    res.on('data', chunk => {
                        expect(`${chunk}`).toContain('hello');
                        done();
                    });
                });
            }
        });
    });
});


text:
Q: Produce a 'Tuple' like output from a method but with lists as members of said tuple I'm required to create a function that will produce multiple outputs. There are 4 outputs of 'double' type and two outputs of a specific object type. I don't want to output them all individually, nor do I want to put them in their own class (it seems wasteful to create a class just for this one method that won't be used anywhere else). So instead I thought to create a Tuple-like class that can take List types as inputs:
/**
 * This class will create a Tuple-like data structure where both inputs can be lists.
 * @param <A>
 * @param <B>
 */
public class ListPair<A extends List, B extends List> {
  public final A a;
  public final B b;

  public ListPair(A a, B b) {
    this.a = a;
    this.b = b;
  }
}

The intent being that my function can now simply output this class.
I haven't worked with Java before (most of my experience is with C#) so I'm not sure if creating a class like this would be the best way to go. Any alternative recommendations would be welcome.


text:
Q: Visualforce page rendered as xls no longer working I am having trouble with a visualforce page rendered as xls. It was working fine for a year and now it stopped. The .xls file is generated and downloaded but shows up as a blank grey background with no content. I've tried making a simple test page with the same result. I have added contentType="application/vnd.ms-excel#FILENAME.xls" to the page tag to accomplish this in the past. Was something changed in the spring/summer 16 releases
?
*SOLVED BELOW: The issue was not a Salesforce problem, but a MS Office security update issue.

A: From Tech Support on Solutions to issues opening exported Excel Files
Following the installation of a Microsoft security update released on July 12, 2016, users are unable to open Excel files downloaded from several websites, including Salesforce.
The update is documented in the Microsoft article linked below:
https://support.microsoft.com/en-us/kb/3170008
Salesforce known issue: https://success.salesforce.com/issues_view?id=a1p3A000000IZSEQA4
To resolve the issue please follow the workarounds that we have right now:

*

*Disable the Protected View setting within Excel. To do this:
-Open MS Excel
-Go to File > Options
-Click Trust Center (from the menu on the left)
-Click the 'Trust Center Settings' button
-Click Protected View (from the menu on the left)
-Remove the check mark next to "Enable Protected View for files originating from the internet"
-Click OK
-Click OK
OR

*Unblock access in File Properties. To do this:
-Right click on the file and choose Properties
-On the General tab, click Unblock
-Click OK
OR

*Remove this specific MS update from the local computer - MS16-088: Security update for Microsoft Office: July 12, 2016
Other which makes sense to me and has worked for some:
SOLUTION: if you do not have salesforce as a "trusted site" in your internet browser.
We believe that the reasoning behind the issue could be that salesforce is not setup as a "trusted site" and the following link will be helpful into adding salesforce as a trusted site and its categorized by internet browser:
http://kb.mcgill.ca/?portalid=2&articleid=1925#tab:homeTab:crumb:8:artId:1925:src:article.
If using Google Chrome:
Click the 3 horizontal lines icon on the far right of the Address bar.
Click on Settings, scroll to the bottom and click the Show Advanced Settings link.
Click on Change proxy settings.
Click the Security tab > Trusted Sites icon, then click Sites.
Trusted site link: https://na28.salesforce.com (use the instance that hosts your org)
Enter the URL of your Trusted Site, then click Add.
Click Close > OK.


text:
Q: Manipulate Blast Result File Python I wrote a Biopython scrip which give me result and i have a file like that :
>NW_020169394.1_41 [10497-10619]|KE647364.1_346 [38084-37959]
MDQLSRKLNLTYLKVGILTSQNEFVTKHLLIIKGLKIFTET

>NW_020169394.1_41 [10497-10619]|KE646921.1_20 [383-240]
MDQLSRKLNLTYLKVGILTSQNEFVTKHLLIIKGLKIFTET

>NW_020169394.1_41 [10497-10619]|KE647277.1_227 [70875-70720]
MDQLSRKLNLTYLKVGILTSQNEFVTKHLLIIKGLKIFTET

How can I get a result on a single comment line like that :
>NW_020169394.1_41 [10497-10619]|KE647364.1_346 [38084-37959] | KE646921.1_20 [383-240] | KE647277.1_227 [70875-70720]
MDQLSRKLNLTYLKVGILTSQNEFVTKHLLIIKGLKIFTET

I tried with regex but it doesn't work . Thanks for your answers.

A: okkey didnt use 'SeqIO.to_dict()' don't know about it maybe someone else will post an answer using that [EDITED
record_dict = SeqIO.to_dict(SeqIO.parse(fasta_file , "fasta"))
will raise a
raise ValueError("Duplicate key '%s'" % key)
ValueError: Duplicate key 'NW_020169394.1_41'

My input 'res.txt' file is:
>NW_020169394.1_41 [10497-10619]|KE647364.1_346 [38084-37959]
MDQLSRKLNLTYLKVGILTSQNEFVTKHLLIIKGLKIFTET

>NW_020169394.1_41 [10497-10619]|KE646921.1_20 [383-240]
MDQLSRKLNLTYLKVGILTSQNEFVTKHLLIIKGLKIFTET

>NW_020169394.1_41 [10497-10619]|KE647277.1_227 [70875-70720]
MDQLSRKLNLTYLKVGILTSQNEFVTKHLLIIKGLKIFTET

My code is:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 28 15:57:59 2021

@author: Pietro

https://stackoverflow.com/questions/68160254/manipulate-blast-result-file-python

"""
from Bio import SeqIO

fasta_file = 'res.txt'

sequences = {}
sequences2 = {}

sequa = SeqIO.parse(fasta_file, "fasta")

count = 0
for seq_record in sequa   :
            sequences[count] = seq_record
            count +=1

for key,seq_record in sequences.items():
    countz = 0
    if seq_record.seq not in [valuez.seq for keiz,valuez in sequences2.items()]:
        sequences2[countz] = seq_record
        countz += 1

    else:
        for keiz,valuez in sequences2.items():
            if seq_record.seq == valuez.seq:
                new = valuez.description.replace('valuez.id', '')
                newnew = new.replace(valuez.name , '')
                sequences2[keiz].description = seq_record.description + (newnew)

print('########################')
print(sequences2)

with open('modified_res.text', 'w') as handle:

    for key,value in sequences2.items():

           print(value)
           SeqIO.write(value, handle, 'fasta')

My output 'modified_res.text' file is:
>NW_020169394.1_41 [10497-10619]|KE647277.1_227 [70875-70720] [10497-10619]|KE646921.1_20 [383-240] [10497-10619]|KE647364.1_346 [38084-37959]
MDQLSRKLNLTYLKVGILTSQNEFVTKHLLIIKGLKIFTET

cant get rid of duplicated [10497-10619] and order is different from yours
sorry, was my best effort
Moreover if your sequences are parsable by a specifit seqrecord format (i.e. genbank and so on , not an expert here , could be possible to play with their description in different way, please let me know).

A: In a FASTA label, everything until the first space is the ID and is supposed to be unique. That's not the case in your example so SeqIO.to_dict() won't work. Instead, map the sequences back to their labels and then combine them:
from Bio import SeqIO
from collections import defaultdict

seq2label = defaultdict(list)
for record in SeqIO.parse('result.fa', 'fasta'):
    seq2label[str(record.seq)].append(record.description)

for sequence, labels in seq2label.items():
    combined_label = ' | '.join(labels[:1] + [label.split('|')[1] for label in labels[1:]])
    print(f'>{combined_label}\n{sequence}\n')

output:
>NW_020169394.1_41 [10497-10619]|KE647364.1_346 [38084-37959] | KE646921.1_20 [383-240] | KE647277.1_227 [70875-70720]
MDQLSRKLNLTYLKVGILTSQNEFVTKHLLIIKGLKIFTET


text:
Q: UIImage(named:) with period loads wrong image (e.g. for SFSymbols) I want an easy way to load SFSymbol images with configuration, if possible. Else just load the image normally. So I have this extension and I have all SFSymbols I need in in my assetcatalog with the same name as the symbol (in this case I have "circle" and "circle.fill").
However, in iOS 12 this gives me "circle"!
I assume what's happening is that it counts the dot/period (i.e. circle . fill) as a file extension and assumes the extension is wrong so just grab the circle image with the 'other extension'. Even tho it's not. Is there an easy fix for this? Is this intended?
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let imageView = UIImageView(frame: CGRect(x: 30, y: 30, width: 50, height: 50))
        imageView.image = UIImage.image(sfsymbolName: "circle.fill")
        view.addSubview(imageView)
    }
}

extension UIImage {
    static func image(sfsymbolName: String, config: Any? = nil) -> UIImage? {
        if #available(iOS 13.0, *), let sfImage = UIImage(systemName: sfsymbolName, withConfiguration: config as? UIImage.Configuration) {
            return sfImage
        } else {
            return UIImage(named: sfsymbolName)
        }
    }
}

A: As mentioned in @matt's comment the probably best solution is to just not have images in you asset catalog with a dot (.). Instead use a different character which you can replace at runtime. Just make sure that that character also also doesn't appear in any SFSymbol name (e.g. an underscore _).
Then you can load the image like this:
let image = loadImage(named: "circle_fill")

func loadImage(named imageName: String) -> UIImage? {
    let sfSymbolName = imageName.replacingOccurrences(of: "_", with: ".")
    if #available(iOS 13.0, *), let img = UIImage(systemName: sfSymbolName)
        return img
    } else {
        return UIImage(named: imageName)
    }
}

With the catalog file structure looking like:
|Assets.xcassets
|--circle.imageset
|----...
|--circle_fill.imageset
|----...


text:
Q: c# Selection Sort Is Setting Weight of One Object To Another Instead of Sorting Ascending Min To High This is homework.  My goal is to create a selection sort that sorts my animals in my zoo by ascending the animals weight low to high given their weight.  I wouldn't be being honest if I said I struggle with the logic for the selection sort as my code shows.
 public static SortResult SelectionSortByWeight(List<Animal> animals)
    {
        // initialize a swap counter variable
        int swapCounter = 0;
        SortResult result = new SortResult();

        // loop forward through the list
        for (int i = 0; i < animals.Count - 1; i++)
        {
            // declare a variable to hold the animal with the current minimum weight
            Animal a = animals[i];
            // set the variable to the current animal
            a = animals[i];

            // loop through the remaining animals in the list to find the animal with the lowest weight
            for (int j = i + 1; j < animals.Count; j++)
            {
                // if the weight of the current animal is less than the weight of the animal with the minimum weight,
                if(animals[i].Weight < animals[j].Weight)

                // set the variable holding the animal with the current minimum weight to the current animal
                {
                    animals[i].Weight = animals[j].Weight;
                }

                // after finding the animal with the lowest weight
                // if the current animal's weight does not equal the weight of the animal with current minimum weight, swap the two animals and increment the swap count
                if (animals[i].Weight != animals[j].Weight)
                {
                    Swap(animals, j, i);
                    swapCounter++;
                }
            }
        }

        result.Animals = animals;
        result.SwapCount = swapCounter;
        return result;
    }

My result that appears to work correctly until I reach my dingo's is:

Guidance in the correct direction is appreciated.

A: One of the main problems here is that you're assigning the weight of one animal to another when you do this: if (animals[i].Weight < animals[j].Weight) animals[i].Weight = animals[j].Weight;. This is why most of the items at the end have the same weight.
Logically speaking, what you likely want to do is store the index of the animal with the lowest weight for the current subset (and by subset I mean the portion of the array that begins with i).
We would start out with the first line in the outer loop storing i as the lightest animal, something like: int minIndex = i;. Then we use our inner loop to check the rest of the animals. If at any point we have animals[j].Weight < animals[minIndex].Weight, then we know we've found a lighter animal, and we should now store that index, like: minIndex = j;
After the inner loop is done (but still inside the outer loop), we know that minIndex represents the location of the lightest animal in the subset that begins with i. If this index is different than i, then we Swap(animals, i, minIndex).
After the outer loop completes, we should have a selection-sorted array.


text:
Q: MVC 4 Model and ViewBag error Here i am using MVC 4 as per my hosting provider requirement i cannot use later version 4.5,4.5.1,4.5.2 my issue is in the image provided here
Three errors in one image
These three errors are not showing in 4.5,4.5.1 but in this version of 4 it is showing.
As i am trying to publish it in my local disk it shows up the errors on error list tab which is third in the image, first and second are in the code as you see above third. I've deleted and create a new page naming the same but error still shows.


text:
Q: 32 bit Python project to 64 bit Python project I have one project build on 32 bit Python 2.7 (most probably in windows environment). Now I pulled the project in my Ubuntu 16.06 (64 bit) Python 2.7 virtual environment. But I am facing the following error when I run it.

TypeError: Error when calling the metaclass bases
      metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

Note: If the project run on Ubuntu 16.04 (32 bit) the error disappears.
What could be the problem and how can I run the project on Ubuntu 16.06 (64 bit)?


text:
Q: Null Validation in Excel Column I need to create a template for internal data collection in MS Excel.
I need to make certain columns mandatory. I have a list of values associated with these columns.
I tried using Data Validation, but could not find any option which throws an error for null values.
How can I define data validation so that null value cannot be inserted in those columns?

A: Please provide more context.
Data validation fires when the user manually enters data into a cell. If a user does not even try to modify a specific cell, its data validation rule will never fire.
If data validation is based on a list and that list (for example defined by a named range) contains blanks, then any value can be entered, even blanks.
If you want to ensure that mandatory fields are filled in before the file can be saved, you need to add a Workbook_BeforeSave event to the workbook's ThisWorkbook module and check the respective cells for valid content.


text:
Q: Mouse Listener on Rectangle I'm trying to draw a game map using many rectangular shapes(just like a screen contains many pixels). I'm using graphics 2D and fillRect(int x, int y, width, height) method. I make the rectangular so small with 10 widths and 10 height.
How can I detect if someone clicks a rectangle? I have read other questions but I am still confused by how the mouse listener detects my small rectangle?
Can someone give me any other solution instead of making pixels with a rectangular shape? maybe like buttons or something?
Here is my example code of making multiple rectangle :
public void paint (Graphics g){

Graphics2D g2D = (Graphics2D) g;
for (int j = 0; j<Map.WIDTH; j++){
    if(j==100){
            if(map[i][j]=='#'){
                x=50;
                y+=10;
                g2D.setColor(Color.BLACK);
                g2D.fillRect(x, y, 10, 10);
                x+=10;
                y+=0;

                    }

note: just ignore the iteration because i'm iterate from some input file(a template)

A: Is it a class that extends JPanel ?
Generally you have to set your listener on your JPanel or whatever:
 void setListener(MouseListener listener) {
    myPanel.addMouseListener(listener);
}

then in your listenerClass you do something like that :
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

class ControlButton extends MouseAdapter {

private MyViewClass view;

ControlButton(MyViewClass view) {
    this.view = view;
    view.setListener(this);
}

@Override
public void mouseClicked(MouseEvent e) {

    //if my x and y point represent the upper left corner
    int rectX = view.getMyRectX();
    int rectY = view.getMyRectY();
    int rectWidth = view.getRectWidth();
    int rectHeight = view.getRectHeight();
    if (e.getX() > rectX && e.getX() < rectX + rectWidth
            && e.getY() > rectY && e.getY() < rectY + rectHeight) {
        System.out.println("YES");
    }
}

}
Of course, I suppose you are working with Swing. If it is not what you want, please be more precise in your explanation ;)


text:
Q: Verbatim in beamer showing error: "File ended while scanning use of \@xverbatim." I am using Texmaker and MiKTeX on Windows 7. I have the following beamer code,
\documentclass{beamer}
\theme{AnnArbor}
\begin{document}
\begin{frame}
\begin{verbatim}

   \begin{frame}[<alignment>]
   \frametitle{Frame Title Goes Here}
   Frame body text and/or LATEX code
   \end{frame}

\end{verbatim}
\end{frame}
\end{document}

I was expecting the following output,
       \begin{frame}[<alignment>]
       \frametitle{Frame Title Goes Here}
       Frame body text and/or LATEX code
       \end{frame}

But instead I got the following Error Message,
File ended while scanning use of \@xverbatim.

Can any one please point out the error here. As far as I know verbatim can have anything inside it.
Also when I tried the following code,
\begin{verbatim}
 \ begin{frame}[<alignment>]
 \frametitle{Frame Title Goes Here}
 Frame body text and/or LATEX code
 \ end{frame}
\end{verbatim}

I got the following output,
    \ begin{frame}[<alignment>]
     \frametitle{Frame Title Goes Here}
     Frame body text and/or LATEX code
    \ end{frame}

But I don't want space between \ and begin and \ and end.

A: Your frame should be fragile. (One additional line commented for better effect).
\documentclass{beamer}
%\theme{AnnArbor}

\begin{document}
%\begin{frame}
\begin{frame}[fragile]
\begin{verbatim}

   \begin{frame}[<alignment>]
   \frametitle{Frame Title Goes Here}
   Frame body text and/or LATEX code
   \end{frame}

\end{verbatim}
\end{frame}
\end{document}

A: Using fragile does not work for me when changing the mode as when generating slides and handouts from separate driver files calling the same content file so I came up with an ugly but effective work around. Let me give an example expanding on the one given above.
The driver file to create slides is called contentfile.beamer and has the following:
\documentclass{beamer}
\input{contentfile}

A driver file for the handouts is called contentfile.article and has the following:
\documentclass{article}
\usepackage{beamerarticle, pgfpages}
\setjobnamebeamerversion{contentfile.beamer}
\input{contentfile}

The file named contentfile has the actual content of the slides and the comments:
\begin{document}

As seen in Figure~\ref{fig:slideWithVerbatim}
the small slide image appears on the article version only and
is ignored when compiled as a beamer document.
That is what makes it a handout.
By contrast this text is ignored when the document is
build with the beamer class.

\begin{figure}
\framebox{\includeslide[width=0.9\textwidth]{frameVerb}}
\label{fig:slideWithVerbatim}
\end{figure}

\mode<beamer>{
\begin{frame}[fragile]
  \label{frameVerb} % this is the hook for the handout
  \begin{verbatim}

    \begin{frame}[<alignment>]
    \frametitle{Frame Title Goes Here}
    Frame body text and/or LATEX code
    \end{frame}

  \end{verbatim}
\end{frame}
}
\end{document}

The workflow is to run pdfLaTeX on the contentfile.beamer first to generate the slides and then run it on contentfile.article to generate the handout.
This had worked wonderfully for me until trying to use verbatim inside a frame environment. The only work around so far has been:

*

*Comment out the lines with \mode<beamer>{ and the final } around the frame environment with the problematic verbatim text in the contentfile file.

*Run pdfLaTeX on the contentfile.beamer file to generate the slides.

*Uncomment the lines from step 1, this will enable the directive that isolates this code from the article mode.

*Save the contentfile file and run pdfLaTeX on the contentfile.article file. This generates the handout version with the correct slides and avoids the collision with verbatim.
Awkward but it does work. I will be thankful to anyone sharing a more elegant and practical solution.

A: I am posting it too late. But one easy solution is "Don't use frame at all".. Latex will automatically assign a frame.
\begin{document}
\begin{verbatim}

   \begin{frame}[<alignment>]
   \frametitle{Frame Title Goes Here}
   Frame body text and/or LATEX code
   \end{frame}

\end{verbatim}
\end{document}

It will automatically assign a frame to the content and will not show any error.


text:
Q: correct usage of python multiprocessing.Pool I am quite new to multiprocessing package and after have read the doc (but far for having fully understood everything), I try to make a simple example that illustrates my needs. I have a class which contains a method that I would like to call several times in parallel, each call being run on a single processor. Moreover, I would like to specify the number of processors allocated for the task. According to the doc, multiprocessor.Pool might be a good candidate for the job. Here is the code I wrote to do the job:
import numpy as np
import random
from multiprocessing import Pool

class Analysis:
    def __init__(self):
        self.x = 10

    def run_step(self,index):
        size = int(10000*random.random())
        np.linalg.inv(np.random.uniform(0,10,(size,size)))

if __name__ == '__main__':
    M = Analysis()
    pool = Pool(processes=4)
    for i in range(10):
        pool.apply_async(M.run_step,args=(i,))
    pool.close()
    pool.join()

At first sight the script seems to work. However, looking at the CPU usage all my cpus are fired (i.e. 12) whereas I asked explicitly to use only 4 processors. I would have expected the script to work like so:

*

*Dispatch the 4 first of the 10 calls to 4 processors

*Dispatch the next 4 calls to 4 processors

*Dispatch the remaining 2 calls to 2 processors

How can I modify my script to fulfill my expectations ?


text:
Q: Is creating Stripe Payment Backend API secure? I want to process Stripe payment to create stripe subscription.
For that I need to pass card number, expiration date, cvc to my backend api.
Is it secure to create Stripe payment this way?
If it is not secure, what methods can I use to secure the subscription request to the backend api?

A: This is not recommended. Instead, you should collect payment details securely with Stripe Elements (docs)and use the safe IDs returned by that to collect payments.
If you are PCI compliant, you should contact Stripe support for assistance with enabling your account to process card details directly.


text:
Q: JBOSS CLI adding module with optional dependency I have a module.xml that looks like:
<module xmlns="urn:jboss:module:1.1" name="com.oracle">
    <resources>
        <resource-root path="ojdbc6.jar"/>
    </resources>
    <dependencies>
        <module name="javax.api"/>
        <module name="javax.transaction.api"/>
        <module name="javax.servlet.api" optional="true"/>
    </dependencies>

Using JBOSS-CLI one can do this:
./jboss-cli.sh -c --command="module add --name=com.oracle --resources=<path-to-file>/ojdbc6.jar --dependencies=javax.api,javax.transaction.api,javax.servlet.api"

to deploy the module.   It is almost the same exact thing and the module.xml is generated; so I need not keep track of another xml.
But how can I get the 'optional="true"' from JBOSS-CLI?
Version:  JBOSS-EAP 6.2.0.    (would be great if I can find a solution that would work for either jboss 6.x EAP and wildfly 8x).

A: The CLI module command appears to only support simple dependencies.
You could work around it by supplying a pre-generated modules.xml file and specifying it in the CLI command using
--module-xml=filepath_to_modules.xml


text:
Q: How to compare IDs with comma separated string in Oracle SQL? I have two tables, for instance "Employees" and "Projects". I need a list of all projects with the name of all the employes involved.
Problem now is, that the employe_ids are saved with commas, like in the example below:
employe  | ID          project   | employe_id
--------------         -----------------------
Person A | 1           Project X | ,2,
Person B | 2           Project Y |
Person C | 3           Project Z | ,1,3,

select
p.project, e.employe
from
projects p
left join employees e on e.id = p.employe_id ???

How do I have to write the join to get the desired output:
project   | employe
--------------------
Project X | Person B,
Project Y |
Project Z | Person A, Person C

A: You can try group by and listagg as following:
select
p.project,
listagg(e.employe,',') within group (order by e.id) as employee
from
projects p
left join employees e on p.employe_id like  '%,' || e.id || ',%'
Group by p.project

Cheers!!

A: Here's a kind of fun way to do it:
WITH cteId_counts_by_project AS (SELECT PROJECT,
                                        NVL(REGEXP_COUNT(EMPLOYE_ID, '[^,]'), 0) AS ID_COUNT
                                   FROM PROJECTS),
     cteMax_id_count AS (SELECT MAX(ID_COUNT) AS MAX_ID_COUNT
                           FROM cteId_counts_by_project),
     cteProject_employee_ids AS (SELECT PROJECT,
                                        EMPLOYE_ID,
                                        REGEXP_SUBSTR(EMPLOYE_ID, '[^,]',1, LEVEL) AS ID
                                   FROM PROJECTS
                                   CROSS JOIN cteMax_id_count m
                                   CONNECT BY LEVEL <= m.MAX_ID_COUNT),
     cteProject_emps AS (SELECT DISTINCT PROJECT, ID
                           FROM cteProject_employee_ids
                           WHERE ID IS NOT NULL),
     cteProject_empnames AS (SELECT pe.PROJECT, pe.ID, e.EMPLOYE
                               FROM cteProject_emps pe
                               LEFT OUTER JOIN EMPLOYEES e
                                 ON e.ID = pe.ID
                               ORDER BY pe.PROJECT, e.EMPLOYE)
SELECT p.PROJECT,
       LISTAGG(pe.EMPLOYE, ',') WITHIN GROUP (ORDER BY pe.EMPLOYE) AS EMPLOYEE_LIST
  FROM PROJECTS p
  LEFT OUTER JOIN cteProject_empnames pe
    ON pe.PROJECT = p.PROJECT
  GROUP BY p.PROJECT
  ORDER BY p.PROJECT

You can certainly compress some of the CTE's together to save space, but I kept them separate so you can see how each little bit adds to the solution.
dbfiddle here

A: You can extract the numeric IDs from the employee_id column of the projects table by using regexp_substr() and rtrim() ( trimming the last extra comma ) functions together, and then concatenate by listagg() function :
with p2 as
(
select distinct p.*, regexp_substr(rtrim(p.employee_id,','),'[^,]',1,level) as p_eid,
       level as rn
  from projects p
connect by level <= regexp_count(rtrim(p.employee_id,','),',')
)
select p2.project, listagg(e.employee,', ') within group (order by p2.rn) as employee
  from p2
  left join employees e on e.id = p2.p_eid
 group by p2.project

Demo

A: Yet another option; code you need (as you already have those tables) begins at line #12:
SQL> -- Your sample data
SQL> with employees (employee, id) as
  2    (select 'Person A', 1 from dual union all
  3     select 'Person B', 2 from dual union all
  4     select 'Person C', 3 from dual
  5    ),
  6  projects (project, employee_id) as
  7    (select 'Project X', ',2,'   from dual union all
  8     select 'Project Y', null    from dual union all
  9     select 'Project Z', ',1,3,' from dual
 10    ),
 11  -- Employees per project
 12  emperpro as
 13    (select project, regexp_substr(employee_id, '[^,]+', 1, column_value) id
 14     from projects cross join table(cast(multiset(select level from dual
 15                                                  connect by level <= regexp_count(employee_id, ',') + 1
 16                                                 ) as sys.odcinumberlist))
 17    )
 18  -- Final result
 19  select p.project, listagg(e.employee, ', ') within group (order by null) employee
 20  from emperpro p left join employees e on e.id = p.id
 21  group by p.project
 22  /

PROJECT   EMPLOYEE
--------- ----------------------------------------
Project X Person B
Project Y
Project Z Person A, Person C

SQL>


text:
Q: Rotate a PdfSignatureAppearance with iText I'm with a big problem trying to rotate a PdfSignatureAppearance in iText (90 degrees, for instance). I'm signing a PDF using the MakeSignature.signDetached method, and setting my own text and image for the appearance.
Here is some code:
PdfReader reader = new PdfReader("my input file");
FileOutputStream fout = new FileOutputStream("my output file");

PdfStamper stamper = PdfStamper.createSignature(reader, fout, '\0');
PdfSignatureAppearance sap = stamper.getSignatureAppearance();

sap.setLayer2Text("Signed by someone");
sap.setAcro6Layers(true);
sap.setSignatureGraphic("my signature image", null));
sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION);

Rectangle pageSize = reader.getPageSize(1); //the page to sign: 1 is the 1st one

Rectangle rect = new Rectangle(llx, lly, urx, ury, rotation);
//llx, lly ... come from a GUI. They are working fine, but the rotation is not considered

sap.setVisibleSignature(rect, 1, null); //1 is the page to sign

MakeSignature.signDetached(sap, ...); //sign the document

My problem is the "rotation" argument. No matter what I set, the text and the image never rotate. Looking at iText code (I'm using iText 5.3.2), the rotation argument of the bounding box of the signature layer is discarded, so, well, setting the rotation this way have no effect at all.
Now the question: Is there a way to rotate my signature layer without rewriting the entire PdfSignatureAppearance and MakeSignature classes?
Just to clarify: the code that digitally signs the document is working fine. My only problem is with the visual layer of the signature: I can't rotate it.
Thanks.

A: A working example that allows for reuse of the code in com.itextpdf.text.pdf.PdfSignatureAppearance (e.g. to calculate font size automatically):
public class RotateVisualSignature {
    public static void main(String[] args) throws IOException, DocumentException, GeneralSecurityException {
        // Loading private key and certificates.
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(new FileInputStream("signer.p12"), "secret".toCharArray());
        String alias = keyStore.aliases().nextElement();
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, "secret".toCharArray());
        Certificate[] certificateChain = keyStore.getCertificateChain(alias);

        PdfReader reader = new PdfReader("sample.pdf");
        FileOutputStream os = new FileOutputStream("sample-signed.pdf");
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setCertificate(certificateChain[0]);

        // This method has to be called as an alternative to 'com.itextpdf.text.pdf.PdfSignatureAppearance.setVisibleSignature'.
        setVisibleSignatureRotated(stamper, appearance, new Rectangle(120, 650, 170, 770), 1, null);

        // Perform the signature.
        ExternalSignature externalSignature = new PrivateKeySignature(privateKey, "SHA-256", null);
        ExternalDigest externalDigest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, externalDigest, externalSignature, certificateChain, null, null, null, 0, MakeSignature.CryptoStandard.CMS);
    }

    private static void setVisibleSignatureRotated(PdfStamper stamper, PdfSignatureAppearance appearance, Rectangle pageRect, int page, String fieldName) throws DocumentException, IOException {
        float height = pageRect.getHeight();
        float width = pageRect.getWidth();
        float llx = pageRect.getLeft();
        float lly = pageRect.getBottom();
        // Visual signature is configured as if it were going to be a regular horizontal visual signature.
        appearance.setVisibleSignature(new Rectangle(llx, lly, llx + height, lly + width), page, null);
        // We trigger premature appearance creation, so independent parts of it can be modified right away.
        appearance.getAppearance();
        // Now we correct the width and height.
        appearance.setVisibleSignature(new Rectangle(llx, lly, llx + width, lly + height), page, fieldName);
        appearance.getTopLayer().setWidth(width);
        appearance.getTopLayer().setHeight(height);
        PdfTemplate n2Layer = appearance.getLayer(2);
        n2Layer.setWidth(width);
        n2Layer.setHeight(height);
        // Then we rotate the n2 layer. See http://developers.itextpdf.com/question/how-rotate-paragraph.
        PdfTemplate t = PdfTemplate.createTemplate(stamper.getWriter(), height, width);
        ByteBuffer internalBuffer = t.getInternalBuffer();
        internalBuffer.write(n2Layer.toString().getBytes());
        n2Layer.reset();
        Image textImg = Image.getInstance(t);
        textImg.setInterpolation(true);
        textImg.scaleAbsolute(height, width);
        textImg.setRotationDegrees((float) 90);
        textImg.setAbsolutePosition(0, 0);
        n2Layer.addImage(textImg);
    }
}

Where the result would be something like this:

For using this, you just need to copy the setVisibleSignatureRotated method as is and replace calls to com.itextpdf.text.pdf.PdfSignatureAppearance#setVisibleSignature with calls to setVisibleSignatureRotated.

A: Currently setting the rotation isn't supported when creating a signature using convenience methods such as setRenderingMode(), setLayer2Text(), setSignatureGraphic(), etc...
So you have two options:
1. Either ask us to provide that functionality. The draft of the first 90 pages of the white paper on digital signatures has just been released to the subscribers of the news letter, so we are working on these classes. However: signing with smart cards, refactoring the verification process, etc... has absolute priority for the moment, so you may have to wait for a while.
2. Draw the content in any direction you want by using the getLayer() method. That would be getLayer(0) for the image in the background; and getLayer(2) for the text.
Note that there used to be layers 1, 3, 4 too, but they will only work if acro6Layers equals true; this is the case for you, but the use of acro6Layers is discouraged (it has become obsolete: you shouldn't use it anymore). As a matter of fact, I'll deprecate that method right now and set the value to false by default.


text:
Q: i want to convert "Milano\u0093Deepak Gupta\u0094" into String in java i want to convert  below string in UTF-8 string in java
String s= "Milano\u0093Deepak Gupta\u0094";

A: All strings are internally stored as UTF-16 in java. This is the reason for string containing \u0093 etc.The below piece of code can be used to convert to UTF-8
try {
    // Convert from Unicode to UTF-8
    String string = "\u003c";
    byte[] utf8 = string.getBytes("UTF-8");

    // Convert from UTF-8 to Unicode
    string = new String(utf8, "UTF-8");
} catch (UnsupportedEncodingException e) {
}


text:
Q: Associative array versus object in JavaScript In my script there is a need to create a hash table, and I searched in google for this. Most of the folks are recommending JavaScript object for this purpose. The The problem is some of the keys in the hash table have a "." in them. I am able to create these keys easily with the associative arrays.
I don't understand why associative arrays are bad. The first thing that is mentioned on the sites that I looked at is the length property.
I am coming from the Perl background, where I used hashes. Most common uses were to get the value from a key, check if a key exists, delete a key-value pair, and add a key-value pair. If these are my common uses, can I safely use an associative array?

A: Actually, an "associative array" is pretty much the same as an "array-like object" in ECMAScript. Even arrays are objects in ECMAScript, just with the exception to have numeric keys (which are still strings in the background) and a .length property, along with some inherited methods from Array.prototype.
So, a Perl hash and an ECMAScript object behave similarly. You might not know that you can access object properties not only via a dot, but also with brackets and strings, like
var myObj = { foo: 42 };

myObj.foo; // 42
myObj['foo']; // 42

Knowing that, you can also use keys with .
var myObj = { };
myObj['hello.foo.world'] = 42;

Of course, you can access that key only with the bracket notation.

A: You can use . in key names on JavaScript objects (AKA associative arrays) if you'd like; they're accepted without issue. The minor drawback is you can't use shortcut notations with the dotted keys, e.g.
var x = {};
x['hello'] = 'there';
alert(x.hello);

is perfectly acceptable and will pop up an alert with 'there' in it. But if you use a dotted name:
var x = {};
x['this.is'] = 'sparta';
alert(x.this.is);

will fail, as JavaScript will look for an attribute named this in the x object, which does not exist. There is only the this.is attribute.

A: In a JavaScript, an object and array are pretty much the same thing, with an array having a bit of magical functionality (autoupdating the length property and such) and prototype methods suitable for arrays. It is also much easier to construct an object than using an associative array:
var obj = {"my.key": "myValue"};

vs.
var obj = [];
obj["my.key"] = "myValue";

Therefore never use the array object for this, but just the regular object.
Some functionality:
var obj = {}; // Initialized empty object

Delete a key-value pair:
delete obj[key];

Check if a key exists:
key in obj;

Get the key value:
obj[key];

Add a key-value pair:
obj[key] = value;

A: There isn't an associative array. It's just an object.
foo.bar;    // Equivalent to...
foo["bar"]; // Looks like associative array.

A: For the sake of convenience of using data, there should be no difference between an object and an array. You can think of it as an object or you can think of it as an associative array. At the end, you can just think of everything as data.

*

*For PHP, [ ] accepts 0, 1, or more items(array), and it is called an associative array. It is JSON in PHP's coat:
$data = ["message"=>[ "id"=>405, "description"=>"Method not allowed.", "detail"=>[]], "object" => []];

*For JavaScript, { } accepts 0, 1, or more items(array), and it is called an object. This data format is JSON:
data = {"message": { "id":405, "description":"Method not allowed.", "detail" : {}}, "object" : {}};
I just call them data. The simplest way to describe data is JSON, or its variants.

A: Because there is no such thing as built-in associative arrays in JavaScript. That's why it's bad.
In fact, when you use something like:
theArray["a"] = "Hello, World!";

It simply creates a property called "a" and set its value to "Hello, World!". This is why the length is always 0, and why the output of alert(theArray) is empty.

A: In JavaScript, objects are associative arrays...there aren't separate concepts for them. You are also able to safely use '.' in a key name, but you can only access the value using the bracket notation:
var foo = {}
foo['bar'] = 'test';
foo['baz.bin'] = 'value';

alert(foo.bar); // Shows 'test'
alert(foo['baz.bin']); // Shows 'value'

If you're using them already and they work, you're safe.


text:
Q: How to get nested array of objects with same parameters Can some one please help i am trying to display all title and content in content array of article array
The below response is getting from database, I am equating that response to authordetails, just i gave name like this.
authordetails:any=[];

this.authordetails=[

          {"_id": "5c1a34ce5e2de421d8e060e5", "article":[
          {"content": [
                       {"content": "hh", "title": "Abstract" },
                       {"content": "gg", "title": "Introduction" },
                       {"content": "ii", "title": "Models" }
         ];

I tried like this
this.authordetails[0].article[0].content[0].title

it means it shows only 0-object of title in content array.
But i need both title and content in content array of all objects.
Thanks in advance

A: It should be something like this (pseudocode)
for (i=0;this.authordetails[0].article.length;i++) {
    let innerObject = this.authordetails.article[i];
    let content = innerObject.content;
    let title = innerObject.title;
    // more logic goes here
}

A: You can use:
for (let i = 0; i < this.authordetails.length; i++) {
      console.log('authordetails',this.authordetails[i]);
      for (let j = 0; j < this.authordetails[i].article.length; j++) {
        console.log('article',this.authordetails[i].article[j]);
        for (let k = 0; k < this.authordetails[i].article[j].content.length; k++) {
          console.log('content',this.authordetails[i].article[j].content[k]);
        }
      }
}

See Stackblitz


text:
Q: Observer CANNOT catch exception thrown in dynamic extension method I created an extension to another class.
I invoked the extension method, which throws exception.
Unfortunately, my observer CANNOT catch that exception.
Anybody knows why?
public static class MyExtensions {
    public static async void myextfunc(this SomeClass some, dynamic data) {
        throw new Exception("Atrápame si puedes.");
    } // fin myextfunc()
} // fin class

SomeClass some = new SomeClass();
IObserver<dynamic> obsv = Observer.Create<dynamic>(async (d) => {
    some.myextfunc((object)d); // NO PUEDO atrapar la exceptión
}, (exception0) => {
    Console.WriteLine(e1.Message);
});
try { obsv.OnNext(123); } catch { /* no funciona */ }

A: Actually, this behavior doesn't depend on using extension method. It depends on using async function when a method expects synchronous delegate (Observer.Create takes only Action< T > as an input for onNext).
First of all, you should never use async void because there is no way for caller to await it correctly (meaning that there will be no exception handling by try / catch for example, more details here). But even if we try to change your code (adding Task instead of void return to your extension method and awaiting it in Observer's onNext) it won't work.
It happens exactly because of Observer.Create expecting Action< T >, not Func< Task >.
It's hard to understand what exactly you wanted to achieve, so I played with your code  assuming you want to catch exception thrown from your async call. That's what I've got:
async static Task Main(string[] args)
{
    SomeClass some = new SomeClass();

    var subscription = Observable.Interval(TimeSpan.FromSeconds(1))
        .SelectMany(number => Observable.FromAsync(async () => await some.myextfunc(number)))
        .Subscribe(_ => Console.WriteLine("onNext"),
            ex => Console.WriteLine(ex.Message));

    await Task.Delay(TimeSpan.FromSeconds(10));
}

You can find out more from this discussion on GitHub and by searching SO questions on async / await with RX.


text:
Q: problems with .db and Promises so im working on this small discord bot, the parts im working on right now are for the bot to be able to track how many messages a user has sent, and be able to spit that amount back when prompted. this first chunk of code is from the main file
const client = new Discord.Client();
const prefix = "!"; //Our bot's prefix
const fs = require('fs');
const db = require('quick.db'); //Database to track user message counts

client.on('ready', () => {
    console.log('Logged in and ready to socially distance!')
});

//This will run everytime a message is recieved
client.on('message', message => {

    let args = message.content.slice(prefix.length).trim().split(" ");
    let cmd = args.shift().toLowerCase();

    try { //This is allow bot commands to be placed in seperate files, so no need for constant if-else statements
        let commandFile = require(`./commands/${cmd}.js`);
        commandFile.run(client, message, args);
    } catch(e) {

        console.log(e.message);

    } finally {

        console.log(`${message.author.username} ran the command: ${cmd}`);
    }

    if (!message.content.startsWith(prefix)) return; //Ignores a message if it doesn't start with our prefix

    //Message Tracking/Leveling
    db.add(message.author.id + message.guild.id, 1).then(i => {

        let messages;
        if (i.value == 25) messages = 25; //This will be Level 1
        else if (i.value == 50) messages = 50; //This will be Level 2
        else if (i.value == 100) messages = 100; //This will be Level 3

        if (!isNaN(messages)) { //If messages empty this runs
            db.add(`userLevel_${message.author.id + message.guild.id}`, 1)
            .then(o =>  {
                message.channel.send(`You sent ${messages} messages, so you leveled up! You are now level ${o.value}`); //Sends updated level to the channel
            })
            .catch(ex); {
                message.channel.send("Sorry, can't do that.")
            }

        }
    })

});

client.login('TOKEN-ID');

this next part of the code is an separate file

exports.run = (bot, message, args) => {

    db.get(message.author.id + message.guild.id)
    .then(i => { //Messages sent
        db.get(`userLevel_${message.author.id + message.guild.id}`)
        .then(o => { //Their level
            message.channel.send('Messages sent: `' + (i.value + 1) + '`\nLevel: `' + o.value + '`'); //Returns messages and level
        }
    ).catch(ex); {
        message.channel.send("Sorry, can't do that.")
    }

})}

and finally here is the error
                                                    ^
TypeError: db.add(...).then is not a function

A: Accordingly to quick.db docs db.add() doesnt return a promise, so you cant attach callbacks to it. The process is managed synchronously:
db.add(message.author.id + message.guild.id, 1)
// Continue your code here and the previous line is garantized to be finished already

Same for db.get() and all operations for quick.db. They are synchronous.


text:
Q: How to store Multiple list of objects in room - Android I have a doubt about creating tables for my network response.
My network response will be like:
    data class ProductsList(
        val next: String? = null,
        val perPage: Int? = null,
        val previous: String? = null,
        val count: Int? = null,
        val results: Results? = null
    )

    data class Results(
        val prices: List<PricesItem?>? = null,
        val products: List<ProductsItem?>? = null
    )

    data class ProductsItem(
        val image: String? = null,
        val content: List<Int?>? = null,
        val prices: List<Int?>? = null
    )

I'm confused the I should have one table or many tables. I'm beginner to room and SQL so if you have any resource to learn more about the room and data handling that will be very helpful for me.
Thanks in advance.


text:
Q: How to use map on json response returned by a REST API with ReactJs I've a json. The only thing I want is title from the json.
{
  "projects": [
    {
      "id": 1,
      "title": "Bike Servicing System",
      "language": "JavaFX",
      "requires": "JDK 8"
    },
    {
      "id": 2,
      "title": "Air Traffic Controller",
      "language": "JavaFX",
      "requires": "JDK 8"
    },
    {
      "id": 3,
      "title": "Program Counter",
      "language": "JavaFX",
      "requires": "JDK 8"
    }
  ],
  "profile": {
    "name": "typicode"
  }
}

I am using fetch and componentDidMount. I want to do it musing map method to iterate through. Though I don't need
 and
 tags really. I will remove them later. My React code is
import React, { Component } from "react";

class ProjectStack extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          items: json.projects
        });
      });
  }

  render() {
    var { isLoaded, items } = this.state;
    var i=0;
    if (!isLoaded) return
Loading...
;
    return (

        {
          items.map(item => (

              Projects: {item[i++].title}

          ))
        }

    );
  }
}

export default ProjectStack;

Apparently, there is something that I don't know because I am getting this error.
PS: This question is different from mine

A: The JSON of the URL you are fetching is this:
[
  {
    "id": 1,
    "title": "Bike Servicing System",
    "language": "JavaFX",
    "requires": "JDK 8"
  },
  {
    "id": 2,
    "title": "Air Traffic Controller",
    "language": "JavaFX",
    "requires": "JDK 8"
  },
  {
    "id": 3,
    "title": "Program Counter",
    "language": "JavaFX",
    "requires": "JDK 8"
  },
  {
    "id": 4,
    "title": "Dove Tail",
    "language": "JavaFX",
    "requires": "JDK 8"
  }
]

So for correctly set the data in the state you need to:
componentDidMount() {
    fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          items: json
        });
      });
  }

Besides correcting the error they have already told you related the map loop.

A: I found 2 mistakes from your code.
The first one is you didn't check the response data.
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
        .then(res => res.json())
        .then(json => {
          console.log(json); // it is an Array not object.
          this.setState({
            isLoaded: true,
            items: json
          });
        });

And the second is you didn't use the map() properly.
/*{
  items.map(item => (

      Projects: {item[i++].title}

  ))
}*/
// items has objects, so you should use map() like this.
{
  items.map(item => (

      Projects: {item.title}

  ))
}

The below code is one way to achieve what you want.

class ProjectStack extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        items: [],
        isLoaded: false
      };
    }

    componentDidMount() {
      fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
        .then(res => res.json())
        .then(json => {
          console.log(json);
          this.setState({
            isLoaded: true,
            items: json
          });
        });
    }

    render() {
      const {
        isLoaded,
        items
      } = this.state;
      console.log(items);
      if (!isLoaded) return (
 Loading...
);
        return ( <
          div >
          <
          ul > {
            items.map(item => ( <
              li key = {
                item.id
              } > Projects: {
                item.title
              }

            ))
          } <
          /ul> <
          /div>
        );
      }
    }
    ReactDOM.render( <
      ProjectStack / > , document.getElementById('root')
    )


text:
Q: Returning the number of lines in a .txt file This is my debut question here, so I will try to be as clear as I can.
I have a sentences.txt file like this:

Galatasaray beat Juventus 1-0 last night.
I'm going to go wherever you never can find me.
Papaya is such a delicious thing to eat!
Damn lecturer never gives more than 70.
What's in your mind?

As obvious there are 5 sentences, and my objective is to write a listSize method that returns the number of sentences listed here.
public int listSize()
{
// the code is supposed to be here.

return sentence_total;}

All help is appreciated.

A: To read a file and count its lines, use a java.io.LineNumberReader, plugged on top of a FileReader. Call readLine() on it until it returns null, then getLineNumber() to know the last line number, and you're done !
Alternatively (Java 7+), you can use the NIO2 Files class to fully read the file at once into a List<String>, then return the size of that list.
BTW, I don't understand why your method takes that int as a parameter, it it's supposed to be the value to compute and return ?

A: Using LineNumberReader:
LineNumberReader  reader = new LineNumberReader(new FileReader(new File("sentences.txt")));
reader.skip(Long.MAX_VALUE);
System.out.println(reader.getLineNumber() + 1); // +1 because line index starts at 0
reader.close();

A: use the following code to get number of lines in that file..
    try {
        File file = new File("filePath");
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        int totalLines = 0;
        while((line = reader.readLine()) != null) {
            totalLines++;
        }
        reader.close();
        System.out.println(totalLines);
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }

A: You could do:
Path file = Paths.getPath("route/to/myFile.txt");
int numLines = Files.readAllLlines(file).size();

If you want to limit them or process them lazily:
Path file = Paths.getPath("route/to/myFile.txt");
int numLines = Files.llines(file).limit(maxLines).collect(Collectors.counting...);


text:
Q: pytest + opencv + multiprocessing = segmentation error I am using opencv with multiprocessing. There is a module say a.py with class A inside which do something and another module b.py with class B which do something else. Module b has multiprocessing pool in it.
When I initialize instance of class B any number of time by importing the module in another file it works.
When I run pytest using class B as fixture it fails by giving segmentation error but when the scope of fixture is changed to module level it works. And also in pytest only when test case of class A is running first, class B gives segmentation error but if class B is first and class A is second in pytest it runs without error.


text:
Q: SQL Server NULLS: duplicate last known value in table I need some advice.
I have a column with nulls in a field at a particular time period.
Name     Date
-----    -----
Cat      1/1/2012
Dog      1/2/2012
Fish     1/3/2012
NULL     1/4/2012
Goat     1/5/2012
NULL     1/6/2012
Sheep    1/7/2012

In the example above, how would I write a SQL statement to select the last known value for column Name whenever there is a null value in the column?
For instance I'd like the table to look like this:
Name      Date
-----    -----
Cat        1/1/2012
Dog        1/2/2012
Fish       1/3/2012
Fish       1/4/2012
Goat       1/5/2012
Goat       1/6/2012
Sheep      1/7/2012

Would this pseudo-code work?
Select
isnull(Name, "Select Name from Table where Date = GetDate() - 1")
,Date
From Table

A: Try this [v is original, v2 is calculated new value] :
DECLARE @table table(v varchar(10), d varchar(10))
INSERT INTO @table
SELECT 'Cat','1/1/2012' UNION
SELECT 'Dog','1/2/2012' UNION
SELECT 'Fish','1/3/2012' UNION
SELECT NULL,'1/4/2012' UNION
SELECT 'Goat','1/5/2012' UNION
SELECT NULL,'1/6/2012' UNION
SELECT 'Sheep','1/7/2012'

SELECT A.v, A.d, ISNULL(A.v,B.v) V2
FROM @table A
OUTER APPLY (   SELECT TOP 1 *
                FROM @table
                WHERE d < A.d
                AND v IS NOT NULL
                ORDER BY d desc) B
order by d


text:
Q: If $f\colon X \to Y$ is one-to-one and a local diffeomorphism, then $f$ is diffeomorphic to an open subset of $Y$. This question is taken from the book "Differential Topology" by Allan Pollack. It is question 5 from section 1.3 and $X$ and $Y$ are manifolds. It is not for an assignment or a homework. I am just trying to self-teach differential topology.
First note that since $f$ is a local diffeomorphism, then for all $x \in X$ such that $f(x)  = y \in Y$, there exist open sets $U_x \subset X$ and $V_x \subset Y$, such that both contain $x$ and $y$, respectively, and $f \colon U_x \to V_x$ is a diffeomorphism. Moreover, $f$ is an open map and $f(U_x)$ is open in $Y$. The open subset of $Y$ we are looking for would be the union of all possible $f(U_x)$. Set $ U = \bigcup_{x \in X} U_x$ and $V =  \bigcup_{x \in X} f(U_x)$. Since $f$ is one-to-one then all such $f(U_x)$ are disjoint and, thus, $f \colon U \to V$ is bijective and by construction of $V$, $f^{-1}$ would be smooth on $V$. This would make $f$ a diffeomorphism.
I do not know if this approach is the correct, maybe not, but I would appreciate any possible feedback.


text:
Q: Find and replace with two strings between it with regular expression In Python, I tried to replace two strings in between a regular expression match.
import re

a = "("
b = ")"
string = "foo bar foo foo bar bar foofoofoo foo foo"

regex = "(foo(.[foo]{1,}))|foo"
print(re.sub(regex, a + string + b, string))

What I thought was going to print:
(foo) bar (foo foo) bar bar (foofoofoo) (foo foo)

What it actually printed:
(foo bar foo foo bar bar foofoofoo foo foo) bar (foo bar foo foo bar bar foofoofoo foo foo) bar bar (foo bar foo foo bar bar foofoofoo foo foo) (foo bar foo foo bar bar foofoofoo foo foo)

Should I use loops or is there a function for that?

A: re.sub is defined as
re.sub(pattern , <what to replace "pattern" with>, input_string)

Your code is asking re.sub to replace your matched pattern with your input_string surrounded by parenthesis which is not what you want.
If you just want to replace all foo's with parenthesis, try
regex = r"((foo){2,}|foo(\s+foo)*)"
a = "("
b = ")"
input_string = "foo bar foo foo bar bar foofoofoo foo foo"
print(re.sub(regex, a + r'\1' + b, input_string))

Output:
(foo) bar (foo foo) bar bar (foofoofoo) (foo foo)

A: You're not using a back reference to your original match. Instead you're replacing the match with the original string. This is why your string is getting longer. You need to use \1 to refer to the pattern matched in the first set of brackets.
I used the following code and got the output that you wanted:
print(re.sub(r"((foo){2,}|foo(\s+foo)*)",r'(\1)',string))

EDIT: I don't have the reputation to comment on the answer marked as correct (my account was reset after being dormant). However, the output is wrong based on the original question.
I got the output:
(foo) bar (foo foo) bar bar (foofoofoo) (foo foo)

EDIT: I corrected the original answer. I didn't think that I could with my reputation.

A: You need to read the documentation for re.sub again. This is its definition:
re.sub(pattern, repl, string, count=0, flags=0)

You are calling:
re.sub(regex, a + string + b, string)

No matter what matches, you are replacing the match with your entire original string surrounded by parens.
Your regex as written has two capture groups (defined by parens). You can refer to them inside the replacement string as \1 or \2. You need to replace a+string+b with something else that will print what you are looking for instead of the entire string.