text:
Q: Memory management of large data from oracle database I am pulling out large data from oracle database using cx_oracle using below sample script:
from cx_Oracle import connect

TABLEDATA = []

con = connect("user/password@host")
curs = con.cursor()
curs.execute("select * from TABLE where rownum < 100000")

for row in curs:
    TABLEDATA.append([str(col) for col in list(row)])

curs.close()
con.close()

Problem with storing in list is that it ends up to about 800-900 mb of RAM usages.
I know I can instead save this in file and not store in list but I am using this list to display table using QTABLEVIEW and QABSTRACTTABLE MODEL.
Is there any alternate or more effient way where I can minimise memory usage of storing this data and also use it to display my table?

A: I have tried multiple possobilities, I don't think qsqltablemodel works for me. Though it load data directly from database, as you keep scrolling down it loads more and more data in table and hence the memory usage keep on increasing.
What I think will ideally work is being able to load set number of rows in model. As you scroll down it loads new rows but also at the same time unloads what's already there. So at any point of time we only have set number of rows loaded in model.

A: If you don't want to store all the data in RAM, then you need to use a model for you tableview that get's information from the database as needed. Fortunately, Qt natively supports this, and can connect to oracle databases.
You will want to look into:

*

*http://qt-project.org/doc/qt-4.8/sql-driver.html

*http://qt-project.org/doc/qt-4.8/sql-model.html

*http://qt-project.org/doc/qt-4.8/qsqltablemodel.html

*http://qt-project.org/doc/qt-4.8/qsqldatabase.html
Note this is c++ documentation, but it is fairly easy to translate to PyQt (I always use the c++ documentation despite never coding in c++). You may also want to subclass QSqlTableModel to provide slightly different behaviour to the standard interface!


text:
Q: Finding only rows with non-duplicated values within a window partition I want to look at why some descriptions are different for the same permit id. Here's the table (I'm using Snowflake):
create or replace table permits (permit varchar(255), description varchar(255));

// dupe permits, dupe descriptions, throw out
INSERT INTO permits VALUES ('1', 'abc');
INSERT INTO permits VALUES ('1', 'abc');

// dupe permits, unique descriptions, keep
INSERT INTO permits VALUES ('2', 'def1');
INSERT INTO permits VALUES ('2', 'def2');
INSERT INTO permits VALUES ('2', 'def3');

// dupe permits, unique descriptions, keep
INSERT INTO permits VALUES ('3', NULL);
INSERT INTO permits VALUES ('3', 'ghi1');

// unique permit, throw out
INSERT INTO permits VALUES ('5', 'xyz');

What I want is to query this table and get out only the sets of rows that have duplicate permit ids but different descriptions.
The output I want is this:
+---------+-------------+
| PERMIT  | DESCRIPTION |
+---------+-------------+
|       2 | def1        |
|       2 | def2        |
|       2 | def3        |
|       3 |             |
|       3 | ghi1        |
+---------+-------------+

I've tried this:
with with_dupe_counts as (
    select
        count(permit) over (partition by permit order by permit) as permit_dupecount,
        count(description) over (partition by permit order by permit) as description_dupecount,
        permit,
        description
    from permits
)
select *
from with_dupe_counts
where permit_dupecount > 1
and description_dupecount > 1

Which gives me permits 1 and 2 and counts descriptions whether they are unique or not:
+------------------+-----------------------+--------+-------------+
| PERMIT_DUPECOUNT | DESCRIPTION_DUPECOUNT | PERMIT | DESCRIPTION |
+------------------+-----------------------+--------+-------------+
|                2 |                     2 |      1 | abc         |
|                2 |                     2 |      1 | abc         |
|                3 |                     3 |      2 | def1        |
|                3 |                     3 |      2 | def2        |
|                3 |                     3 |      2 | def3        |
+------------------+-----------------------+--------+-------------+

What I think would work would be
count(unique description) over (partition by permit order by permit) as description_dupecount

But as I'm realizing there are lots of things that don't work in window functions. This question isn't necessarily "how do I get count(unique x) to work in a window function" because I don't know if that is the best way to solve this.
A simple group by I don't think will work because I want to get the original rows back.

A: One method uses min() and max() and count():
select *
from (select p.*,
             min(description) over (partition by permit) as min_d,
             max(description) over (partition by permit) as max_d,
             count(description) over (partition by permit) as cnt_d,
             count(*) over (partition by permit) as cnt,
            count(permit) over (partition by permit order by permit) as permit_dupecount
      from permits
     )
where min_d <> max_d or cnt_d <> cnt;

A: I would just use exists:
select p.*
from permits p
where exists (
    select 1
    from permits p1
    where p1.permit = p.permit and p1.description <> p.description
)

To handle the null values, we can use standard null-safe equality operator IS DISTINCT FROM, which Snowlake supports:
select p.*
from permits p
where exists (
    select 1
    from permits p1
    where
        p1.permit = p.permit
        and p1.description is distinct from p.description
)

A: Should work
SELECT DISTINCT p1.permit, p1.description
FROM permits p1
JOIN permits p2 ON p1.permit = p2.permit
WHERE p1.description != p2.description OR p1.description IS NULL AND p2.description IS NOT NULL

A: This is my go to:
with x as (
    select permit, count(distinct description) cnt
    from permits p1
    group by permit
    having cnt > 1
    )
select p.*
from x
join permits p
  on x.permit = p.permit;

redpajama_set_name: RedPajamaStackExchange


text:
Q: RabbitMQ DLQ: How to reprocess all messages in sequence of arrival across multiple queues? I am stuck with an issue where lot of messages have reached several rabbitMQ dead-letter queues. I have never had to reprocess bulk messages from DLQs earlier. The requirement now is to reprocess all these messages but in the exact sequence how they were pushed, irrespective of which DLQ it was. Is there a way to group all these failed messages from across all the DLQs and then process them one by one in FIFO basis?
Example:
Event1.DLQ: Message1 at T[1], Message2 at T[3]
Event2.DLQ: Message1 at T[2], Message2 at T[5]
Event3.DLQ: Message1 at T[4], Message2 at T[6]

(T[n] -> Timestamp; T[n] is less than T[n+1])
I would like to combine the failed messages from all these 3 DLQs into a common queue and reprocess them in the following sequence one by one (in order of Time):
Event1.Message1, Event2.Message1, Event1.Message2, Event3.Message1, Event2.Message2, Event3.Message2

Not sure if this question is too naïve, any help is appreciated.


text:
Q: Multiple Slideshow not working properly. Any Clue? So basically, I'm trying to create multiple slideshows on the page with dots to switch between the slides (because I've already tried the arrow type button and it doesn't workout for me idk), and the issue is that when I use more than one slideshow the dots on the first one either stop working or begin switching the below slideshows slides.
I have already seen a lot of threads about this issue and tried several answers to them, but none of them seem to work. So if anybody has any clue of what is happening in my code and knows the answer, it would be great. PD: I'm sorry if it contains any grammatic faults :c.
This is the code I'm using (originally from w3s: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_quotes_slideshow and https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_multiple)

/* Referencia miscelánea de assets
color cuadraos: #31572C
color fondo global: #B3B882
color fondo variable: #90A970
color fondo recuadros: #4F772D
color fondo titulo principal&Home: #132A13
color flechas: #000000
*/

* {
  font-family: 'Roboto', sans-serif;
  font-size:large;
}

details {
  border: 1px solid #d4d4d400;
  margin-top: 10px;
}

summary {
  font-weight: bold;
  font-size: 120%;
  margin: -.75em -.75em 0;
  padding: .75em;
  background-color:#31572C;
  color: #fff;
}

details[open] {
 padding: 10px;
}

details[open] summary {
  margin-bottom: 10px;
}

#chingue {
text-align: center;
}

/* Cuadrados principales*/
.TituloEleccion {
    color: #ffffff;
    background-color: #31572C;
    text-align: center;
    height: 99%;
    width:100%;
    margin-top:0%;
    line-height: 3.1;
}

body {
    background-color: #B3B882;
}

#titulogeneral {
    color: #ffffff;
    background-color: #132A13;
    border-style: ridge;
    border-color: #4eaa4e;
    margin-left: 20%;
    margin-right: 20%;
    height: 8.5%;
    text-align: center;
    line-height: 4.15;
    white-space: nowrap;
    overflow: hidden;
    white-space: initial;
  }

  .colordesconocido {
    background-color: #4F772D;
    width:100%;
    margin-top:0%;
    margin-bottom: 30px;
  }

#fondouniversal {
  background-color:#B3B882 ;
}

.divinformacion {
  width: 50%;
  display: block;
  float: left;
  padding: 20px;
  border: 2px solid rgb(0, 0, 0);
  border-style: double;
  border-radius: 10px;
}

.fondoeleccion {
  color: #000000;
  background-color: #4F772D;
  width:100%;
  margin-top:0%;
  border: 1.5px solid rgb(0, 0, 0);
  border-style: double;
  margin-bottom: 30px;
}

img{
  border:2px solid #000000;
}

body {
  font-family:"Pathway Gothic One", sans-serif;
}

.hidecontent {
  display: none;
}

#myaccordion label {
box-shadow:0 0 20px #d4d4d4;
display: block;
padding: 8px 22px;
margin: 1px 0px 1px 0px;
cursor: pointer;
background: #31572C;
color: #FFF;
transition: ease .5s;
text-align:center;
}
#myaccordion label:hover {
background: #31572C;
}
.content {
box-shadow:0 0 20px #d4d4d4;
background: #90A970;
padding: 1.5% 1.5%;
border: 1px solid #d4d4d4;
margin: -1 0 0 0;
}

#myaccordion input:checked + label + .content {
display: block;
-moz-animation: fadeIn 0.5s ease-out;
-o-animation: fadeIn 0.5s ease-out;
animation: fadeIn 0.5s ease-out;
}

#info1 {
  float:right;
}

#foto {
  float:left;
}

* {box-sizing: border-box}
body {font-family: Verdana, sans-serif; margin:0}

/* Slideshow container */
.slideshow-container0 {
  position: relative;
  background:#90A970;
}

.slideshow-container1 {
  position: relative;
  background:#90A970;
}

.slideshow-container2 {
  position: relative;
  background:#90A970;
}

/* Slides */
.mySlides0 {
  display: none;
  padding: 2px;
  text-align: center;
}

.mySlides1 {
  display: none;
  padding: 2px;
  text-align: center;
}

.mySlides2 {
  display: none;
  padding: 2px;
  text-align: center;
}

/* The dot/bullet/indicator container */
.dot-container0 {
    text-align: center;
    padding: 20px;
    background:#31572C;
}

.dot-container1 {
  text-align: center;
  padding: 20px;
  background:#31572C;
}

.dot-container2 {
  text-align: center;
  padding: 20px;
  background:#31572C;
}

/* The dots/bullets/indicators */
.dot {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.dot0 {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.dot1 {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}
.dot2 {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

/* Add a background color to the active dot/circle */
.active, .dot:hover {
  background-color: #717171;
}

.titulilloparque {
  text-align: center;
  color:#000000;
}

<title>PARQUES NATURALES Y NACIONALES. ANDALUCIA</title>
<link rel="stylesheet" href="CSSMAIN.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">

PARQUES NATURALES Y NACIONALES. ANDALUCIA

    <input type="checkbox" id="accordion1" class="hidecontent"/>

PARQUES NATURALES

PARQUE NATURAL DE SIERRA NEVADA

Imagen del parque

DATOS

                            GEOLOCALIZACIÓN: 37°05'19.8''N 3°10'18.7''O

                            Hotel, casa rural y cabaña.

                            Senderismo, alpinismo, rutas en bicicleta, esquí, snowboard,
                            clases de esquí y snowboard guiadas

                            Jabalí, gato montés, zorro, comadreja, garduña, gineta,
                            y el frecuente turón común

TURISMO

                            TOTAL

                            VIAJEROS 3712

                            PERNOCTACIONES 8430

                            EST. MEDIA 2,27 d

                            ESPAÑOLES

                            VIAJEROS 2235

                            PERNOCTACIONES 5558

                            EST. MEDIA 2,49 d

                            EXTRANJEROS

                            VIAJEROS 1477

                            PERNOCTACIONES 2872

                            EST. MEDIA 1,94 d

PARQUE NATURAL SIERRA DE LAS NIEVES

Imagen del parque

DATOS

                            GEOLOCALIZACIÓN: 36°44'N 4°59'O

                            Hotel y casa rural.

                            Rutas de senderismo, rutas en bicicleta,
                            rutas en 4x4 y observatorio de aves.

                            Íbice ibérico, gato montés, zorro, comadreja,
                            garduña, gineta, turón común.

TURISMO

                            TOTAL

                            VIAJEROS 2928

                            PERNOCTACIONES 5415

                            EST. MEDIA 1'85 d

                            ESPAÑOLES

                            VIAJEROS 1245

                            PERNOCTACIONES 2041

                            EST. MEDIA 1'64 d

                            EXTRANJEROS

                            VIAJEROS 1683

                            PERNOCTACIONES 3374

                            EST. MEDIA 2 d

PARQUE NATURAL DE LA BREÑA Y MARISMAS DE BARBATE

Imagen del parque

DATOS

                                    GEOLOCALIZACIÓN: 36°10'44''N 5°58'22''O

                                    Hotel y casa rural.

                                    Inmersión submarina, surf, observación de aves,
                                    rutas de senderimos y la destaca visita al tajo vertical de
                                    los Acantilados de Barbate.

                                    Principalmente fauna aviar; gaviota argéntea,
                                    garcilla bueyera, garcetas, vencejo, mirlo, cárabo, carbonero, etc.

TURISMO

                                    TOTAL

                                    VIAJEROS 2188

                                    PERNOCTACIONES 7363

                                    EST. MEDIA 3,37 d

                                    ESPAÑOLES

                                    VIAJEROS 1417

                                    PERNOCTACIONES 3744

                                    EST. MEDIA 2,64 d

                                    EXTRANJEROS

                                    VIAJEROS 771

                                    PERNOCTACIONES 3619

                                    EST. MEDIA 4,69 d

A: This code wont work because there's a problem with
your JavaScript as some variables are conflicting
I will suggest you to make separate JavaScript file first and include it in your index.html like this ;
<scritp src=" *your JavaScript file path* "> </script>

this way your code is separated and it'll be easy to determine problems in your code.
well after this follow the same pattern as per link you provided of w3cSchool.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_quotes_slideshow and https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_multiple)
commented out things that you should resolve according to your requirement;
these first two are the default one 3rd is my added one just like this you have to add yourself in the code

Slideshow 1:

      ❮
      ❯

Slideshow 2:

      ❮
      ❯

Slideshow 3:

 //NEW CLASS ADDED further more class can be added like this like 4 5 6....and so on

        here I added new number 2 as first two have 0 and 1 now 2 for third slide and 3 4 5.. and so on for more slides to be added watch out these should be added on y-axis as x-axis is responsible for no of jumps one slide should make

          ❮
          ❯


text: Q: How to convert Expression> into elasticsearch searchrequest? When using a restful api to deal with the search request from client, I created an Expression<func<T,bool>> expression to search from sql database, and now I am trying to use elasticsearch(NEST client), is there a way to convert this expression into searchrequest?


text:
Q: Error: No QueryClient set, use QueryClientProvider to set one I was trying react query for first time then i got this on start of my React app.
Although I added QueryClientProvider I top of the tree I am still facing : Error: No QueryClient set, use QueryClientProvider to set one
index.js
ReactDOM.render(
    <QueryClientProvider queryClient={queryClient}>
        <App />
    </QueryClientProvider>
  ,
  document.getElementById('root')

App.js
function App() {
  return (

       <Forms/>

  );
}

Form.js
function Forms() {
    const[createTodo,todoMutation]= useMutation((event) => {
        axios.post('/todos', event.target.elements.todo.value);
    })

    return (

            <form onSubmit={createTodo}>
                todo-item:
                <input id="todo" name="Add todo"/>
                <button>Submit</button>
            </form>

    )
}

Package.json
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-query": "3.12.1",
    "react-scripts": "4.0.0"

A: Prop name should be client instead of queryClient
 import { QueryClient, QueryClientProvider } from 'react-query'

 const queryClient = new QueryClient()

 function App() {

   return <QueryClientProvider client={queryClient}>...</QueryClientProvider>

 }

A: Downgrading the version from V3 to V2 fixed the issue.


text:
Q: Highlight streets in OpenStreetMap I'm working on a little project and I need to do the following:
It's an Android app and the user had to be able to highlight a street (or block, alternatively) and send that selection data to the main server. I'm wondering if this is possible, and how I can do it. Also, how can I store this information and show it on a private map?
Example: the user highlights the street on its map, sends a report to the server with that specific street, then the server updates the map with that report, showing this updated map to the other users.
I'm using OSMDroid.
Any help is appreciated.


text:
Q: Use different database for the npm test phase Environment: heroku, node.js - express, testing with mocha.
How can I configure heroku to launch the npm test with NODE_ENV="test" and invoke the server ("node server.js") with NODE_ENV="production" .
This means that I need two server invocations - once for testing (where I connect to my test db) and once for production (where I connect to my production db)
I want to use different db in the "npm test" phase since my tests also create fake data.
Here is how my test look like:
var supertest = require("supertest");
var should = require('chai').should();
var config = require('../server/config');

var server = supertest.agent(config.baseUrl);

describe("User controller", function () {
    describe("HTTP Verbs", function () {
         it("GET", function (done) {
              console.log(config.dbUrl);
              console.log(config.baseUrl);
              server.post("/api/user") {
                  .send(utils.createMockedUserPlainObject())
                  .end(function(err, res) {

                  server.get("/api/user/list")
                    .expect("Content-type", /json/)
                    .expect(200) // THis is HTTP response
                    .end(function (err, res) {
                        // HTTP status should be 200
                        res.status.should.equal(200);
                        res.body.should.have.length(1);

                        done();
                  });
              })
          });
    });
});

A: Well,
Its seems the magic lies inside supertest.
replace:
var server = supertest.agent(config.baseUrl);

with:
var app = require('../server');

var server = supertest.agent(app);


text:
Q: sun.security.validator.ValidatorException: PKIX path building failed, with java >1.6 I have a Java JAR application which connects to the Java web service running on a server behind HTTPS. If I run the JAR with Oracle Java 1.6, then the SSL handshake is successful. However, If I run it with Oracle Java 1.7 or newer, I always get the exception: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
I have imported the certificates to the cacert file, and have used VM variable javax.net.ssl.trustStore to set the path to the file.
I have found out that there are differences in jsse.jar in different Java version.
Also, this application works like expected on a Unix machine which has IBM version of Java installed: IBM J9 VM (build 2.7, JRE 1.7.0
And, it works correctly with IBM JRE on Widnows:
IBM J9 VM (build 2.8, JRE 1.8.0)

What could I do to fix this?

A: I solved this! Java has java.security file in jre/lib/security folder, and that file has a property keystore.type. This property was set to Windows-ROOT, but I have imported certificates in cacerts file, and the property should be set to jks so that Java reads the cacerts file!


text:
Q: Highcharts Stacked Column chart change legendItemClick function On legendItemClick, how do I prevent subtraction of legend item value from total and instead add the value to another legend item.
E.g. I would like the 'Other Fruit' series to contain all switched off fruit series (the same with 'Other Veg' series).
Here is the Fiddle
$(function () {
 $('#container').highcharts({
    chart: {
        type: 'column'
    },
    title: {
        text: 'Stacked column chart'
    },
    xAxis: {
        categories: ['Then', 'Now']
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Total consumption'
        },

        stackLabels: {
            enabled: true,
            style: {
                fontWeight: 'bold',
                color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
            }
        }
    },
    legend: {
        align: 'right',
        x: -30,
        verticalAlign: 'top',
        y: 25,
        floating: true,
        backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
        borderColor: '#CCC',
        borderWidth: 1,
        shadow: false
    },
    tooltip: {
        headerFormat: '{point.x}
',
        pointFormat: '{series.name}: {point.y}
Total: {point.stackTotal}'
    },
    plotOptions: {
     series: {
            events: {
                legendItemClick: function () {
                 //if fruit/veg is clicked then add value to other fruit/veg and keep the total unchanged
                  // return false;

                }
            }
        },
        column: {
            stacking: 'normal',
            dataLabels: {
                enabled: true,
                formatter:function() {
                  return this.series.name+' '+this.point.y;
                },
                color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
                style: {
                    textShadow: '0 0 3px black'
                }
            }
        }
    },
    series: [{
        name: 'Other Fruit',
        data: [8, 13]
    },{
        name: 'Other Veg',
        data: [16, 10]
    },{
        name: 'Tomatoes',
        data: [3, 7]
    },{
        name: 'Cucumbers',
        data: [5, 4]
    },{
        name: 'Apples',
        data: [5, 3]
    }, {
        name: 'Bananas',
        data: [3, 6]
    }, {
        name: 'Oranges',
        data: [3, 4]
    }]
});

});

A: Things we need to do

*

*Series should be categorized as fruit and vegetables, so that we know which others series("Other Fruit" or "Other Veg") to add/subtract value from.

*When the legend item is clicked, check if it's a fruit or a veggie and add the value to others.

*When clicked again, subtract the values from others.

*We should not be able to hide the others series.
series: [{
  name: 'Other Fruit',
  data: [{y:8}, {y:13}],
},{
  name: 'Other Veg',
  data: [{y:16}, {y:10}]
},{
  name: 'Tomatoes',
  data: [{y:3}, {y:7}],
  fruit: false
},{
  name: 'Cucumbers',
  data: [{y:5}, {y:4}],
  fruit: false
},{
  name: 'Apples',
  data: [{y:5}, {y:3}],
  fruit: true
},{
  name: 'Bananas',
  data: [{y:3}, {y:6}],
  fruit: true
},{
  name: 'Oranges',
  data: [{y:3}, {y:4}],
  fruit: true
}]

Added a property "fruit" to all series except "Other Fruit" and "Other Veg".
legendItemClick: function () {
    var isFruit = this.options.fruit;
    if(isFruit == undefined){ //property undefined for "Other fruit" and "Other Veg"
      return false; //returning false prevents hiding the series
    }
    var chart = this.chart;
    var othersSeries;
    if(isFruit){
      othersSeries = chart.series[0]; //if it's a fruit, get "Other Fruit" series
    }
    else{
      othersSeries = chart.series[1]; //else get "Other Veg" series
    }
    updateOthersData(this, othersSeries);
}

function updateOthersData(currentSeries, othersSeries){
    var othersData = othersSeries.options.data;
    if(currentSeries.visible){ //add values only when the series is already visible and is to be hidden
        othersData[0].y += currentSeries.options.data[0].y;
        othersData[1].y += currentSeries.options.data[1].y;
    }
    else{ //subtract values only when data is already hidden and is to be shown
        othersData[0].y -= currentSeries.options.data[0].y;
        othersData[1].y -= currentSeries.options.data[1].y;
    }
 othersSeries.update({data:othersData}); //update the series
}

Here is the fiddle.


text:
Q: Cor desse menu em android studio Olá, alguem me ajuda a colocar a cor preta nos textos? parece que está branca, ou transparente.Não estou achando onde é, obrigado.

<data />

<androidx.drawerlayout.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:id="@+id/map_layout"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:orientation="vertical"
                app:layout_constraintTop_toTopOf="parent">

                <fragment
                    android:id="@+id/map"
                    android:name="com.google.android.gms.maps.SupportMapFragment"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
            </LinearLayout>

            <com.arlib.floatingsearchview.FloatingSearchView
                android:id="@+id/search_place"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toTopOf="parent"
                app:floatingSearch_close_search_on_keyboard_dismiss="true"
                app:floatingSearch_dimBackground="true"
                app:floatingSearch_leftActionMode="showHamburger"
                app:floatingSearch_menu="@menu/search_view"
                app:floatingSearch_searchBarMarginLeft="8dp"
                app:floatingSearch_searchBarMarginRight="8dp"
                app:floatingSearch_searchBarMarginTop="8dp"
                app:floatingSearch_showSearchKey="false"
                app:floatingSearch_searchHint=""
                app:floatingSearch_suggestionsListAnimDuration="250" >

                <TextView
                    android:id="@+id/search_text"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/search_default"
                    android:ellipsize="marquee"
                    android:fadingEdge="horizontal"
                    android:singleLine="true"
                    android:layout_marginStart="56dp"
                    android:layout_marginEnd="150dp"
                    android:layout_marginLeft="54dp"
                    android:layout_marginRight="150dp"
                    android:layout_gravity="start"
                    android:layout_marginTop="25dp"/>
            </com.arlib.floatingsearchview.FloatingSearchView>

            <ImageView
                android:id="@+id/image_pickup"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="55dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:srcCompat="@drawable/marker_pickup"
                tools:ignore="ContentDescription" />

            <ImageView
                android:id="@+id/image_destination"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="55dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:srcCompat="@drawable/marker_destination"
                android:visibility="gone"
                tools:ignore="ContentDescription" />

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/button_confirm_pickup"
                style="@style/Widget.AppCompat.Button.Colored"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="16dp"
                android:text="@string/confirm_pickup_location"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent" />

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/button_confirm_destination"
                style="@style/Widget.AppCompat.Button.Colored"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="16dp"
                android:text="@string/confirm_destination_location"
                android:visibility="gone"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent" />
        </androidx.constraintlayout.widget.ConstraintLayout>

        <androidx.cardview.widget.CardView
            android:id="@+id/bottom_sheet"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:behavior_peekHeight="0dp"
            app:layout_behavior="com.innomalist.taxi.common.components.WABottomSheetBehavior">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <androidx.appcompat.widget.AppCompatButton
                    android:id="@+id/button_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    style="@style/Widget.AppCompat.Button.Colored"
                    android:drawableStart="@drawable/time"
                    android:drawableLeft="@drawable/time"
                    android:text="@string/pickup_time"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    android:layout_margin="8dp"
                    android:onClick="onSelectTimeClicked"/>
                <androidx.appcompat.widget.AppCompatButton
                    android:id="@+id/button_request"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    style="@style/Widget.AppCompat.Button.Colored"
                    android:text="@string/confirm_service_empty"
                    app:layout_constraintBottom_toBottomOf="parent"
                    android:layout_marginBottom="8dp"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    app:layout_constraintStart_toEndOf="@id/button_time"
                    app:layout_constraintEnd_toEndOf="parent"/>
                <com.innomalist.taxi.common.components.WrapContentViewPager
                    android:id="@+id/service_types_view_pager"
                    android:layout_width="match_parent"
                    android:layout_height="170dp"
                    android:clipToPadding="true"
                    app:layout_constraintBottom_toTopOf="@id/button_request"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent" />

                <com.google.android.material.tabs.TabLayout
                    android:id="@+id/tab_categories"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    <!app:layout_constraintBottom_toTopOf="@id/service_types_view_pager"/>
                    tools:context=".activities.main.MainActivityOld">

            </androidx.constraintlayout.widget.ConstraintLayout>
        </androidx.cardview.widget.CardView>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/drawer_header"
        app:menu="@menu/main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>

A: Você pode adicionar um android:textColor="#000000" para alterar a cor da fonte, esse código ficaria dentro do TextView, para ter maior visibilidade do que o layout está criando, você pode ativar nas opções de desenvolvedor a opção: Limites de layout, com essa opção você consegue ver todos os componentes da tela, ou ver pelo blueprint no editor de layout do android studio.


text:
Q: Boost graph: speeding up add_edge I have a boost graph application where I need to call the function add_edge( ) [documentation available here].
Profiling this application with KCachegrind reveals the following breakup of time spent:

As can be seen, the add_edge function call takes up roughly 21% of the time of the parent caller. Out of this 21%, 14.49% is simply some std::vector's reallocation.
The suggested way to prevent such vector reallocations seems to be to upfront reserve some amount of space. See for e.g., thread: How to prevent memory reallocation using std::vector
What is the equivalent way to do this reservation of some sufficient amount of space in boost graph?
The underlying graph object over which this repeated calls to add_edge are made is thus:
typedef adjacency_list<
    vecS, vecS, directedS,
    property<
    vertex_name_t, std::string,
    property<vertex_index_t, int,
    property<vertex_color_t, boost::default_color_type,
    property<vertex_distance_t, double,
    property<vertex_predecessor_t, Traits::edge_descriptor>
    > > > >,
    property<
    edge_index_t, int,
    property<edge_capacity_t, double,
    property<edge_weight_t, double,
    property<edge_residual_capacity_t, double,
    property<edge_reverse_t, Traits::edge_descriptor>
> > > > >
Graph;

Edited to add: Similar questions here and here.
Unfortunately for me, g.m_edges does NOT have function reserve.

Edited to add link to a minimal example (that is difficult to get to work fully) but compiles fine except for an undefined external reference that is not the main issue.

A:
Unfortunately for me, g.m_edges does NOT have function reserve

But m_vertices does.
#include <boost/graph/adjacency_list.hpp>

int main() {
    boost::adjacency_list<> g;
    g.m_vertices.reserve(1024);
}

Also, since you're using vecS you could almost equivalently just construct with a pre-allocated number of vertices:
boost::adjacency_list<> g(1024);

The difference is, of course, that this doesn't just reserve space for, but resizes the graph to contain 1024 vertices.


text:
Q: OR-Tools: Ensure group of nodes is visited by vehicles from the same depot I would like to use OR-Tools to solve a CVRP where each node has a label, and all the nodes that have the same label have to be visited by vehicles that originate from the same starting location. It does not matter which this starting location is, the only requirement is that it is the same for all the nodes with the same label. Is there a way to model this using the routing library?

A: I suggest the use of "SetAllowedVehiclesForIndex" method.


text:
Q: ¿Porqué las letras de un string se asignan así en los bucles? mi duda es la siguiente, este es el codigo:
print("Verificación de correos")
def listaCorreos():
    correo=[]
    condicion=""
    while True:
        correo.append(input("Introduce correo electrónico: "))
        condicion=input("Pulse 1 para salir enter para continuar.")
        if condicion=="1":
            break
    return correo

def comprobar(correo):
    listaComprobada=[]
    for i in correo:
        contadorArro=0
        contadorPunto=0
        for j in i:
            if j=="@":
                contadorArro+=1
            if j=="." and contadorArro==1:
                contadorPunto+=1
        if contadorArro==1 and contadorPunto==1:
            listaComprobada+=[i]
    return listaComprobada

Basicamente te permite crear una lista de correos y despues te verifica que estos estan bien, la duda me surje en la siguiente línea de la función comprobar():
listaComprobada+=[i]

¿Porqué la variable listaComprobada si la pongo asi  me crea la lista como yo quiero y si lo hago asi
listaComprobada+=i

me asigna en cada posición la letra de los correos que pasan?
Gracias de antemano.

A: La sintaxis lista += elementos es en el fondo una forma de invocar:
lista.extend(elementos)

y esta forma a su vez espera que elementos sea un tipo por el que se pueda iterar, y que contenga la serie de elementos que queremos añadirle a lista.
Por ejemplo, si lista = [1,2] y queremos añadirle los elementos 3 y 4, podríamos hacer:
lista.extend([3,4])

o, lo que es equivalente, lista += [3,4]. En ambos casos el resultado sería que lista pasaría a tener [1, 2, 3, 4].
Esto no es lo mismo que lista.append(elemento) que espera un solo elemento y lo añade al final de la lista.
Usando el mismo ejemplo de antes:
lista = [1, 2]
lista.append([3,4])

ahora el resultado sería que lista vale [1, 2, [3,4]], pues en este caso la lista [3,4] se trata como un solo elemento para añadirle a lista.
Esto que he dicho sobre listas, se aplica a cadenas. Observa la diferencia:
lista = ["Hola", "mundo"]
lista.append("que")
lista.extend("tal")

El .append() añade a la lista un nuevo elemento, la cadena "que", en cambio el .extend() añade una serie de elementos nuevos, los que obtenga al iterar por su argumento, que en este caso es una cadena. Al iterar por una cadena obtienes sus letras individuales. Por tanto al final la lista valdrá:
["Hola", "mundo", "que", "t", "a", "l"]

Y como hemos dicho lista.extend("tal") y lista += "tal" son lo mismo, lo que explica tu duda. Y eso explica también por qué lista += ["tal"] sí funciona como esperas, porque en ese caso es equivalente a lista.extend(["tal"]), y el argumento que le pasas a extend es una lista por la que itera para obtener los elementos a añadir, y en este caso encuentra sólo uno que es la cadena "tal".
Como moraleja, yo diría que deberías usar listaComprobada.append(i) que es mucho más claro que listaComprobada += [i]
Otras mejoras

*

*Elegir buenos nombres de variables ayuda mucho a leer el programa y entender lo que hace. El parámetro correo debería llamarse correos (pues es una lista de ellos). La variable i debería llamarse correo (pues es lo que contiene),  la variable j debería llamarse caracter.

*No necesitas implementar la cuenta de arrobas y puntos. Las cadenas python tienen el método count()
Mi propuesta es por tanto:
def comprobar(correos):
    listaComprobada=[]
    for correo in correos:
        if correo.count("@") == 1 and correo.count(".") == 1:
            listaComprobada.append(correo)
    return listaComprobada

o, si eres aficionado a los "one-liners", usando una comprensión de listas:
def comprobar(correos):
    return [correo for correo in correos if correo.count("@") == correo.count(".") == 1]


text:
Q: xv6 makefile says undefined reference to __printf_chk I'm trying to add a user space program in xv6, but when I try to compile it gives error: "/usr/include/bits/stdio2.h:104: undefined reference to __printf_chk". Any help?
My user program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/user.h>

int
main(int argc, char *argv[])
{
    setbuf(stdout, NULL);
    for (int i = 1; i < argc; i++)
    {
         printf("Print in user space: %s\n", argv[0]);
    }
    exit(0);

    return 0;
}

A: You've compiled the program with your host headers, which are from glibc, but you're trying to link it with the xv6 target libraries. That's not going to work. You need to be using a proper cross compiler and taking care not to pollute it with -I options that would bring in host headers or -L options that would bring in host libraries.

A: for future reference i will answer dont include normal C header files  you have to use headers provided by the xv6-libraries if u just include normal C headers you will get an error, more specifically delete the C headers and , if you are on RISC-V use #include "user/user.h"


text:
Q: Why does MongoDB map-reduce have implicit this The map-reduce usage is following
db.myCollection.mapReduce(function() {
  emit(this.smth);
},
function(key, values) {
  // return something done with key and values
});

My question is, why is the map part implemented to have implicit this that references the current document being processed? IMO, it would be cleaner to have the current document passed in as an argument to the map function (I prefer to write all my JavaScript without this).
In practice this also rules out the use of arrow functions in mongo scripts, since this reference does not work with them.

A:
why is the map part implemented to have implicit this that references the current document being processed?

MongoDB's Map/Reduce API was created in 2009, which is well before arrow functions were available in JavaScript (via ES6/ES2015). I can only speculate on the design intention, but much has changed in JavaScript (and MongoDB) since the original Map/Reduce implementation.
The this keyword in a JavaScript method refers to the owner or execution context, so setting it to the current document being processed was perhaps a reasonable convention (or convenience) for JavaScript usage at the time. The reduce function has a required prototype of function (key, values) so a map prototype of function (doc) might have been more consistent. However, once an API choice is made, any significant breaking changes become more challenging to introduce.
A more modern take on aggregation might look quite different, and this is the general path that MongoDB has taken. The Aggregation Framework introduced in MongoDB 2.2 (August, 2012) is a higher performance approach to data aggregation and should be preferred (where possible) over Map/Reduce.
Successive releases of the MongoDB server have made significant improvements to the features and performance of the Aggregation Framework, while Map/Reduce has not notably evolved. For example, the Aggregation Framework is written in C++ and able to manipulate MongoDB's native BSON data types; Map/Reduce spawns JavaScript threads and has to marshal data between BSON and JavaScript.

In practice this also rules out the use of arrow functions in mongo scripts, since this reference does not work with them.

Indeed. As at MongoDB 4.0, arrow functions are not supported in Map/Reduce. There is a feature request to support arrow functions which can you watch/upvote in the MongoDB issue tracker: SERVER-34281.


text:
Q: Pie Chart - Showing Currency Values - Excel VBA I think my doubt is simple. I'm trying to create a pie chart from VBA Excel that inform money values. I can only make them appear as raw numbers (not with $, R$ for example).
Here's my code:
With grafico_usp
    .Name = "Metrics USP - Quantidade"
    .ChartType = xlPieExploded
    .SetSourceData Source:=rng
    .ClearToMatchStyle
    .ChartStyle = 304
    .HasTitle = True
    .HasLegend = True
    .Legend.Format.TextFrame2.TextRange.Font.Size = 13
    .Legend.Height = 200
    .Legend.Position = xlLegendPositionRight
    .ChartTitle.Text = "Estatística Número de Cursos Ofertados - USP"
    .ApplyDataLabels (xlDataLabelsShowValue)
 End With

My cells are also formatted as Currency but the unit doesn't appear in the pie chart.
Thanks for your time!

A: It is trivial...
I just simply recorded a macro and it seems to work for the chart data labels. In the wizard I first added data tables. Then choose to format them under number format by choosing currency.
So in VBA, to achieve the same, you will have to apply number formatting to each of the data series, if you have multiples.
ActiveSheet.ChartObjects("Chart 1").SeriesCollection(1).ApplyDataLabels
With ActiveSheet.ChartObjects("Chart 1").SeriesCollection(1).DataLabels
    .NumberFormat = "$#,##0.00"
End With


text:
Q: BigQuery - Error : Unrecognized name at employees.name, employees.role, Department.name, employees.department_id I was following along with my instructor, and I can't seem to get pass a particular issue. The topic is using the JOIN function particularly the INNER JOIN to aggregate data from two tables in a dataset. I created a dataset(employee_data), in the dataset I also created two tables(employees, Department). This two tables have department_id column. The exercise was to get the list of employees and their department name, excluding any employee without a department_id using the INNER JOIN function. The employees table as the following columns(name, department_id, role), while the Department table as the following columns(name, department_id)
SELECT
employees.name AS employees_name,
employees.role AS employees_role,
Department.name AS department_name

FROM `employee_data.employees`
INNER JOIN
`employee_data.Department` ON
employees.department_id = department.department_id

I keep getting an error of unrecognized name at employees.name, employees.role, Department.name, employees.department_id

A: In BigQuery, when you are selecting a column in a specific table with a table_name.column, your table name must be specified with a dataset name (e.g. dataset.table.column).
SELECT
 `employee_data.employees`.name AS employees_name,
 `employee_data.employees`.role AS employees_role,
 `employee_data.Department`.name AS department_name
FROM
 `employee_data.employees`
INNER JOIN
 `employee_data.Department`
ON
 `employee_data.employees`.department_id =
 `employee_data.Department`.department_id;

Instead, give an alias name to the table and select a column using it.
SELECT
 e1.name AS employees_name,
 e1.role AS employees_role,
 d1.name AS department_name
FROM
 `employee_data.employees` AS e1
INNER JOIN
 `employee_data.Department` AS d1
ON
 e1.department_id = d1.department_id;


text:
Q: Ubuntu Shuts Down on Restart (v 14.04.1) I have recently installed Ubuntu 14.04.1 on my laptop and I am not able to restart it. Every time I press the restart button, the system logs me off as usual, then the ubuntu loading screen appears (with the 5 dots) and after the second dot is completed, the whole computer SHUTS DOWN. The laptop makes the sound of a HARD SHUT DOWN (like when I am holding the power button to hard shut down the computer). It appears as if the computer crashes right before it restarts.
Shut Down button on the other hand works just fine.
What could cause this problem?
I should also note that I am dual-booting Ubuntu with Windows 8.1
Here are my specs:
CPU: Intel Core i7 - 3630QM, 2.4 GHz
Memory: 6GB
HDD: 1TB
OS: Ubuntu 14.04.1
Graphics: nVidia GEFORCE 635M GT, 2GB
Installed Apps:

*

*Cpufreq Indicator

*Unity Tweak Tool

*nvidia-prime
Thank You

A: I had a similar problem with my desktop and I fixed it magically by changing some options on my computer BIOS. Here is my question
My specs and symptoms are similar to your so maybe this will help you out.


text:
Q: Google results link my site to a spammy Michael Kors site I tried using Google Webmaster tools to re-crawl the site and it hasn't helped.
Does anyone know why the link on Google might say 'halalgems.com', but redirect to another site?
The description is also incorrect.

A: Unfortunately, it appears as though your website has been hacked, and not a problem with Google.
After looking at the response from your website once someone goes to it from that google page, it is your website that does the redirecting.
I cannot determine the source of this issue, as that would likely require access to your server. Good luck with tracking it down!


text:
Q: How should I bridge a JAXB class and a POJO (domain object) used by a DAO? I want to use the same class as a JAXB class and a domain object for a DAO.  This way I can easily move data back and forth from incoming/outgoing XML web service calls to direct CRUD transactions on a database.  Is there a design pattern out there that I could use?  I am leaning towards AbstractFactory because I have some database util functions that prep the SQL parameters without having to know the table/column names.
@XmlRootElement( name = "labdata")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "labdata", propOrder = {"labId",
                                        "labDesc",
                                        "lastUpdateDatetime",
                                        "userId"})
public class LabData extends DbObject
{

    @XmlTransient
    private HashMap<String, Object> mappedFields;

    @XmlElement(name="lab_id", required = true)
    private Integer labId;

    @XmlElement(name="lab_desc", required = true)
    private String labDesc;

    @XmlElement(name="last_altered_dt", required = true)
    private Timestamp lastUpdateDatetime;

    @XmlElement(name="user_id", required = true)
    private String userId;

    @XmlTransient
    private final String labIdField = "TST_LAB_CD";

    @XmlTransient
    private final String labDescField = "LAB_DSC_TE";

    @XmlTransient
    private final String lastUpdateDatetimeField = "INS_GMT_TS";

    @XmlTransient
    private final String userIdField = "USR_ID";

    @XmlTransient
    private final String tableName = "TSTLAB";

    /**
     * Default constructor.
     */
    public LabData() {
        super();
        mappedFields = new HashMap<String, Object>();
    }

    /**
     * Constructor which takes all fields as parameters
     * and will update the protected hash map after setting all the fields.
     * @param labId {@link Integer}
     * @param labDesc {@link String}
     * @param lastUpdateDatetime {@link Timestamp}
     * @param userId {@link String}
     */
    public LabData(Integer labId, String labDesc, Timestamp lastUpdateDatetime, String userId) {
        super();
        this.labId = labId;
        this.labDesc = labDesc;
        this.lastUpdateDatetime = lastUpdateDatetime;
        this.userId = userId;
        updateHashMap();
    }

    public Object[] getFieldValues() {
        return new Object[] {this.labId, this.labDesc, this.lastUpdateDatetime, this.userId};
    }

    public Object[] getUpdateFieldValues() {
        return new Object[] {this.labDesc, this.lastUpdateDatetime, this.userId};
    }

    public void updateHashMap() {
        mappedFields.clear();
        mappedFields.put(this.labIdField, this.labId);
        mappedFields.put(this.labDescField, this.labDesc);
        mappedFields.put(this.lastUpdateDatetimeField, this.lastUpdateDatetime);
        mappedFields.put(this.userIdField, this.userId);
    }

    getters and setters...
}

Database Util:
public List<Object[]> createInsertBatchArgs(DbObject[] dbPojos){
    List<Object[]> args = new ArrayList<Object[]>();
    for(DbObject dbPojo: dbPojos) {
        args.add(dbPojo.getFieldValues());
    }
    return args;
}

public List<Object[]> createUpdateBatchArgs(DbObject[] dbPojos, String... updateFields){
    List<Object[]> args = new ArrayList<Object[]>();
    for(DbObject dbPojo: dbPojos) {
        Object[] fields = dbPojo.getUpdateFieldValues();
        Object[] values = Arrays.copyOf(fields, fields.length+updateFields.length);
        for(int i = 0; i < updateFields.length; i++) {
            values[values.length-updateFields.length+i] =
                      dbPojo.getFieldValue(updateFields[i]);
        }
        args.add(values);
    }
    return args;
}

public List<Object[]> createDeleteBatchArgs(DbObject[] dbPojos, String... deleteFieldName){
    List<Object[]> args = new ArrayList<Object[]>();
    Object[] values = new Object[deleteFieldName.length];
    for(DbObject dbPojo: dbPojos) {
        for(int i = 0; i < deleteFieldName.length; i++) {
            values[i] = dbPojo.getFieldValue(deleteFieldName[i]);
        }
        args.add(values);
    }
    return args;
}

If I remove the DbObject inheritance then the usage of the DAO methods by casting causes  java.lang.VerifyError: Bad type on operand stack.  Unfortunately I don't have the ability to implement a new framework that would easily do this.

A: There does not seem to be an answer outside of separating the two layers.  I used Dozer to map the JAXB and pojos to each other.  This framework also also has an implementation of direct JAXB bean mapping to pojos.


text:
Q: How do I pass data into an detailView? I have got an tableView, so when the cell is tapped it diverts to a DetailViewController. But it doesn´t have any data in it, such as images or text. How do I pass this data to my DetailView?
Code for controllers:
.h file

@interface Sushi : NSObject {
    IBOutlet UILabel *sushiDescription;
    IBOutlet UIImageView *sushiPicture; }
@property (nonatomic, retain) IBOutlet
  UILabel *sushiDescription; @property
  (nonatomic, retain) IBOutlet
  UIImageView *sushiPicture;
@end

.m file

@implementation Sushi
@synthesize sushiDescription,
  sushiPicture;
-(void)dealloc {  [sushiDescription release];     [sushiPicture release];
      [super dealloc]; }
@end

A: For sample do like this,
1) Store any value ex:the indexpath.row vale in appdelegate
2)In DetailViewController's viewDidLoad access the value and display it accordingly


text: Q: OverlayPanel no se oculta si cambio la ruta IONIC estoy trabajando en IONIC con un p-overlaypanel de primeng. Si se muestra el panel pero cambio de ruta mediante el router el p-overlaypanel no se oculta. Recalco que estoy trabajando en ionic.


text:
Q: C# functions with static data In VB.Net, I can declare a variable in a function as Static, like this:
Function EncodeForXml(ByVal data As String) As String
    Static badAmpersand As Regex = new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)")

    data = badAmpersand.Replace(data, "&")

    ''// more processing

    return data
End Function

Note that I need to use the keyword Static, rather than Shared, which is the normal way to express this in VB.Net.  How can I do this in C#?  I can't find its equivalent.

A: Personally I'm glad that C# doesn't have this. Logically, methods don't have state: types and instances do. C# makes that logical model clearer, IMO.

A: There is no equivalent in C# unfortunately.
You will need to use a class level variable.
This is one of the few things that VB has that I wish C# had.

A: Ha! In posting the question, I found the answer!  Rather than googling for C# I should have been looking for details on how VB.Net implements it, and typing up the question made that apparent to me.  After applying that insight, I found this:
http://weblogs.asp.net/psteele/articles/7717.aspx
That article explains that it's not really supported by the CLR, and the VB compiler creates a static (shared) variable "under the hood" in the method's class.  To do the same in C#, I have to create the variable myself.
More than that, it uses the Monitor class to make sure the static member is thread-safe as well.  Nice.
As a side note:  I'd expect to see this in C# sometime soon.  The general tactic I've observed from MS is that it doesn't like VB.Net and C# to get too far apart feature-wise.   If one language has a feature not supported by the other it tends to become a priority for the language team for the next version.

A: You have to declare this on the class level:
private static readonly RegEx badAmpersand = new RegEx("...");


text:
Q: Jquery table filter I am trying to filter table results from Table B by clicking on a field in Table A using jquery.  Table B contains all the data from a specific database and Table A just contains one of the fields. For example,
Table A
MFG_Name |Count
Dell | 15
Gateway|10
Clicking on Dell would filter all the results from Table B where MFG_Name = Dell and show them below Table A as follows:
Table B
Inventory_No | MFG_Name | Model_Name | Description
0001          | Dell     |Inspiron    |Desktop
0002          | Dell     |Optiplex    |Desktop
how can I go about doing this? I've looked at using plugins that filter tables but my goal is not to have to print Table B until I have filtered it as it could contain 100000+ inventory numbers.

A: You could set a click event on table A, extract the text you clicked on and then you this jQuery plugin on table B: http://plugins.jquery.com/project/uiTableFilter
EDIT
Wrote a small demo using tableFilter: http://jsfiddle.net/VjdLV/2/

A: Given mark-up similar to the following:

            Manufacturer name

            Dell

            Packard Bell

            Manufacturer name
            Model number

            Dell
            Vostro

            Dell
            E1405

            Dell
            Inspiron 1525

            Packard Bell
            F7305

            Packard Bell
            Easy Note A7

            Hewlett Packard
            Touchpad

            Hewlett Packard
            Pavilion Elite

The following jQuery seems to work:
$('#manufacturers td').click(
    function(){
        var m = $(this).text();
        $('#computers tr')
            .hide()
            .filter(
                function(){
                    if ($(this).find('td:first-child').text() == m){
                        return this;
                    }
                })
            .show();
    });

JS Fiddle.

A: You can try code like this:
$("table.a td.mfg_name").click(function(){

    var mfg_name = $(this).text();

    $("table.b tr").each(function(){

        if($(this).find("td.mfg_name").text().indexOf(mfg_name) != -1){
            $(this).show();
        }
        else{
            $(this).hide();
        }
    });
});


text:
Q: Getting Friend list data with less read in Firestore My project is in Ionic3, Angular2 and Firestore.
As Firestore costing depends on the number of reads I have the following concern.
I have the following structure for users.
User(collection)
    ->User ID(Doc)   -> Name:
                     -> Photo URL:
                     -> Friend (collection)
                            ->Friend ID (Doc) -> statue: Active
                            ->Friend ID (Doc) -> statue: Inactive
    ->User ID(Doc)  -> ...

Following this structure, if I want to show my friend list...

*

*I will query the Friend collection for all active friends. (This is one read)

*I have to loop through (read) all the IDs to get their Name and Photo URL.

So If a user has 200 friends. It will cost me 200 reads just to display the data.
Is there any better approach?

A: A solution is to use database denormalization: you duplicate the information you need (e.g. name and photoURL) in your Friend documents. This way, upon reads, you have all data for displaying what you want. For sure, there is a tradeoff. Upon friend updates, you have to either update all related documents or live with outdated information. However, it seems your use case has more reads than writes. As a consequence, it should not be a big issue to apply denormalization.


text:
Q: Error:(29, 17) Failed to resolve: junit:junit:4.12 Android Studio 2.1.2 I'm using Android Studio 2.1.2 and it is giving error "Error:(29, 17) Failed to resolve: junit:junit:4.12" Similar error for any third party library. I have tried removing and adding the junit library from Project Settings but still it giving same error. I'm not sure whether this proxy issue? I have checked connection from Studio for maven link and it is showing successful.  Following is my build.gradle
  apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.0"
    repositories {
        maven { url 'http://repo1.maven.org/maven2' }
    }
    defaultConfig {
        applicationId "com.example.administrator.myapplication"
        minSdkVersion 17
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.0.0'
}

Project Level build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
repositories {
    jcenter()
    mavenCentral()
}
allprojects {
    repositories {
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Please let me know if I'm missing something and how to resolve this.

A: After lot of efforts I was able to resolve this issue. Issue lies with the proxy settings, I have added following lines in gradle.properties file and gradle synced successfully with dependencies resolved
systemProp.http.proxyHost=x.x.x.x
systemProp.https.proxyPort=xxxx
systemProp.https.proxyHost=x.x.x.x
systemProp.http.proxyPort=xxxx


text:
Q: Facebook JavaScript SDK share dialog title with special characters I've been trying to use Facebook's JavaScript SDK to share. This is an example of the the API function I used.
FB.ui({
  method: 'feed',
  link: '',
  title: '',
  description: '',
}, function(response){});

In the title field, I have a string with the ™ symbol, but in the dialog, it's displayed a invalid character '?'. I've tried '™' or encodings like '%E2%84%A2', '%26trade%3B'. Nothing works.
Has anyone run into this kind of problem before? Any help would be appreciated. Thanks in advance.


text:
Q: Iphone simulator not getting location Am getting users longitude and latitude in AppDelegate it asked for permission once when i deleted\Uninstall the app after reinstalled again on simulator it didn't ask for permission so the app keep crashing here is my code
 func initLocationManager() {

    if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse ||
        CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized){

        seenError = false
        locationFixAchieved = false
        locationManager = CLLocationManager()
        locationManager.delegate = self
        //        locationManager.locationServicesEnabled = true
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
        locationManager.requestAlwaysAuthorization()

    }
}

// Location Manager Delegate stuff

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    locationManager.stopUpdatingLocation()
    if ((error) != nil) {
        if (seenError == false) {
            seenError = true
            print(error)
        }
    }
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if (locationFixAchieved == false) {
        locationFixAchieved = true
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as! CLLocation
        var coord = locationObj.coordinate

        LATITUDE = coord.latitude
        LONGITUDE = coord.longitude

        print(coord.latitude)
        print(coord.longitude)
    }
}

func locationManager(manager: CLLocationManager!,
                     didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    var shouldIAllow = false

    switch status {
    case CLAuthorizationStatus.Restricted:
        locationStatus = "Restricted Access to location"
    case CLAuthorizationStatus.Denied:
        locationStatus = "User denied access to location"
    case CLAuthorizationStatus.NotDetermined:
        locationStatus = "Status not determined"
    default:
        locationStatus = "Allowed to location Access"
        shouldIAllow = true
    }
    NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
    if (shouldIAllow == true) {
        NSLog("Location to Allowed")
        // Start location services
        locationManager.startUpdatingLocation()
    } else {
        NSLog("Denied access: \(locationStatus)")
    }
}

A: try to get user location at didFinishLaunchingWithOptions for first time then call this method for getting updated user location.
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()

func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
println("locations = \(locations)")
gpsResult.text = "success"
}


text:
Q: wxPython: centering an image in a panel I have a GridSizer with StaticBitmap images in it. I want to put each of the images in their own panels so I can change the background color to highlight an image if it has been selected. When I try to do this, however, the images are not centered in their panels and the highlighted background color is only present on two borders. How can I make the images in the center of their panels so there is an equivalent border around all sides of each?
sizer = wx.GridSizer(rows=row,cols=cols,vgap=5)
for fn in filenames:
    p = wx.Panel(self.panel)
    img = wx.Image(fn, wx.BITMAP_TYPE_ANY)
    img2 = wx.StaticBitmap(p, wx.ID_ANY, wx.BitmapFromImage(img))
    img2.Bind(wx.EVT_LEFT_DOWN, self.OnClick, img2)
    sizer.Add(p)
self.panel.SetSizer(sizer)

A: You need to add your image to a boxSizer with a border.
You could write an imagePanel class to implement this.
You should then be able to call  SetBackgroundColour on your ImgPanels to change the borders (panels) colour when ever you need to.
Here's a very rough example for an ImgPanel class
class ImgPanel(wx.Panel):
    def __init__(self, parent, image):
        wx.Panel.__init__(self, parent)

        img = wx.Image(image, wx.BITMAP_TYPE_ANY)
        self.sBmp = wx.StaticBitmap(self, wx.ID_ANY, wx.BitmapFromImage(img))

        sizer = wx.BoxSizer()
        sizer.Add(item=self.sBmp, proportion=0, flag=wx.ALL, border=10)
        self.SetBackgroundColour('green')
        self.SetSizerAndFit(sizer)


text:
Q: does android.intent.action.PACKAGE_ADDED requires users permission? I am implementing HeyZap and it requires me to add
<receiver android:name="com.heyzap.sdk.ads.PackageAddedReceiver">
 <intent-filter>
  <data android:scheme="package"/>
  <action android:name="android.intent.action.PACKAGE_ADDED"/>
 </intent-filter>
</receiver>

Do these lines in AndroidManifest.xml require user permission for update or will update my Google Play users automatically?
Usually user permission is not a problem. But Admob voluntaristicaly changed the rules without prior notification and force me to use "New Admob" and I wish to move as much users as possible from Admob.
Does following permission is required?
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_ADDED" />

There is only BROADCAST_PACKAGE_REMOVED permission in SDK and HeyZap does not mention that permission but some users on StackOverflow mention it.

A: You don't need to add permission. Read How can I get Actions: PACKAGE_REMOVED and PACKAGE_ADDED thread for more.

You can try one more thing is, add exported and enable option as true for Receiver into Manifest, and then try.
Like
<receiver android:name="com.heyzap.sdk.ads.PackageAddedReceiver" android:exported="true" android:enabled="true">


text:
Q: Deploying Ruby on Rails app that require node.js as well I am trying to install a ruby on rails app on AWS via elastic beanstalk (end goal is zero downtime deployment) but the problem i am getting errors while running the "AppDeployPreHook/11_asset_compilation.sh" step
I have selected ruby platform with passenger and at AppDeployPreHook/11_asset_compilation.sh step when it reaches following step
> @ build:client /var/app/ondeck/client
> npm run ensure-node-version && webpack --config webpack.client.config.js

I get following error code
  npm ERR! Linux 4.14.88-72.76.amzn1.x86_64
  npm ERR! argv "/opt/elasticbeanstalk/support/node-install/node-v4.6.0-linux-x64/bin/node" "/opt/elasticbeanstalk/support/node-install/node-v4.6.0-linux-x64/bin/npm" "run" "ensure-node-version"
  npm ERR! node v4.6.0
  npm ERR! npm  v2.15.9
  npm ERR! file sh
  npm ERR! code ELIFECYCLE
  npm ERR! errno ENOENT
  npm ERR! syscall spawn
  npm ERR! @ ensure-node-version: `check-node-version --package`
  npm ERR! spawn ENOENT
  npm ERR!
  npm ERR! Failed at the @ ensure-node-version script 'check-node-version --package'.
  npm ERR! This is most likely a problem with the  package,
  npm ERR! not with npm itself.
  npm ERR! Tell the author that this fails on your system:
  npm ERR!     check-node-version --package
  npm ERR! You can get information on how to open an issue for this project with:
  npm ERR!     npm bugs
  npm ERR! Or if that isn't available, you can get their info via:
  npm ERR!
  npm ERR!     npm owner ls
  npm ERR! There is likely additional logging output above.

  npm ERR! Please include the following file with any support request:
  npm ERR!     /var/app/ondeck/client/npm-debug.log

  npm ERR! Linux 4.14.88-72.76.amzn1.x86_64
  npm ERR! argv "/opt/elasticbeanstalk/support/node-install/node-v4.6.0-linux-x64/bin/node" "/usr/bin/npm" "run" "build:client"
  npm ERR! node v4.6.0
  npm ERR! npm  v2.15.9
  npm ERR! code ELIFECYCLE
  npm ERR! @ build:client: `npm run ensure-node-version && webpack --config webpack.client.config.js`
  npm ERR! Exit status 1
  npm ERR!
  npm ERR! Failed at the @ build:client script 'npm run ensure-node-version && webpack --config webpack.client.config.js'.
  npm ERR! This is most likely a problem with the  package,
  npm ERR! not with npm itself.
  npm ERR! Tell the author that this fails on your system:
  npm ERR!     npm run ensure-node-version && webpack --config webpack.client.config.js
  npm ERR! You can get information on how to open an issue for this project with:
  npm ERR!     npm bugs
  npm ERR! Or if that isn't available, you can get their info via:
  npm ERR!
  npm ERR!     npm owner ls
  npm ERR! There is likely additional logging output above.

I have tried to install and set the npm just before the execution of this script
  v7.8.0 is already installed.
  Now using node v7.8.0 (npm v4.2.0)
  Now using node v7.8.0 (npm v4.2.0)

but for some unknown reason, the version of node and npm gets reset in the very next task
I have tried all possible solutions that i could think of my so far i haven't managed to solve it.
Any help in this regard would be really helpful


text:
Q: Initializing and Constructing Arrays of Objects in C++ When declaring an array of objects, are all the objects constructed at initialization, or do they have to be constructed after initialization? Here is an example of what I am trying to explain:
Lets say I have this class:
class Object{
public:
    int x = 4;
};

And this array:
Object objects[8];

If I was to access any of the variables within the objects, would I have to construct the objects first, or was that done in the array? So if I did this:
cout << objects[4].x;

Would it print out 4?

A: In C++11 your code is perfectly valid, it performs in-class initialization, and indeed, cout << objects[4].x; will print out 4. In previous C++ versions (C++98/03), the code is invalid, and you'd need a default constructor to initialize the variable x, like
class Object{
public:
    int x;
    Object(int x = 4): x(x){}
}

A:

*

*are all the objects constructed at initialization

Yes, all of elements of array will be default initialized.

if T is an array type, every element of the array is default-initialized;

And

if T is a non-POD (until C++11) class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object;

And

*Would it print out 4?

Yes. For class Object, the implicitly-declared default constructor will be invoked here. And the member x is not initialized by the member initializer list (in default constructor), the default member initializer is applied, then x will be initialized with value 4.


text:
Q: How to return the index corresponding to the person with the biggest time The below code has an array for names (racers in a marathon) and in the other array I have the time array for each (racer) to finish the race ...
I want to return the index corresponding to the person with the biggest time.
My code does return the biggest time but it returns the biggest time for all names (racers) ... The biggest time should be returned for one racer ...
class Marathon {

        public static void main (String[] arguments) {
            int biggest = 0;
            String[] names = {
                "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex",
                "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda",
                "Aaron", "Kate"
            };

            int[] times = {
                341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299,
                343, 317, 265
            };

            for (int i = 0 ; i < names.length ; i++) {
                if (times[i] > biggest) {
                    biggest=times[i];
                }
                System.out.println(names[i]+":"+biggest);

           }
         }
       }

The output I got is :
Elena:445
Thomas:445
Hamilton:445
Suzie:445
Phil:445
Matt:445
Alex:445
Emma:445
John:445
James:445
Jane:445
Emily:445
Daniel:445
Neda:445
Aaron:445
Kate:445

A: A couple of issues :

*

*you assume the result before computing it

*you are looking for a maximum so the initial value should be as small as possible (0, for example, because it is a time)

*you should store the index of the largest time, not only the largest time itself

*you should not print in your loop since you only want to print the name of the runner with the longest time (so a single print)


text:
Q: Linq To Sql - Reading DB with old schema I have a DB (SQL CE 3.5) and i am using code first to write into a database (say version-1).
  Over time one of the table (SAY TABLE1) signature has changed (one new attribute added- say ATTRIB1), now when i try to read the old database using the new table signature (schema in code), the code understandably throws an exception complaining about the new ATTRIB1 (which is present in code but not in DB).
List<TABLE1> list= this.dataContext.TABLE1.ToList(); --> throws exception

*

*Is there any way i can ignore columns that dont exist in linq to sql.

*Read the DB table into an "entity" and query the value of the columns i need explicitly.

*Any ideas about how best to handle DB versioning.

thanks

A: Code First Migrations surely would have been a complete approach.
I was looking for something cheap and cheerful :), did that by basically saving an upgrade script for each increment of the database version.
So while reading an old schema, i first upgraded it to the current version by applying the upgrade scripts progressively (this was something my project could live with).


text:
Q: Azure Repos restrict push to branch from all branches except one Imagine, we have branch policy on Story branch and it is impossible to push to this branch without completed PR.
But is it possible to allow push to Story branch only if name of the branch is Dev.
So I need to restrict pushing for all branches except one with particular name


text:
Q: What is the difference between this two selectors in CSS? I have a question about this selectors in CSS.
What's the difference between :
.dropdown:hover .dropbtn {background-color: #3e8e41;}

AND
.dropdown:hover, .dropbtn {background-color: #3e8e41;}

I don't understand why in the first example we don't use a comma. What is the difference between using a comma or not

A: Well, as per the snippet below:

*

*.dropdown:hover .dropbtn {background-color: #3e8e41;} does means that, when mouse is hovered over .dropdown, the child element .dropbtn should change it's color

*.dropdown:hover, .dropbtn {background-color: #3e8e41;}. If .dropdown:hover, then its color should be #3e8e41, and always the color of .dropbtn should be #3e8e41.
So the difference is that, first one selects its child when mouse is hovered over, and apply the color, while the second one will always apply color to .dropbtn instead of mouse hovered over or not on the .dropdown.

.sample:hover span {
  background-color: #3e8e41;
}
.sample:hover,
span {
  background-color: red;
}

  Hellow
  Hello

  Hellow
  Hello

A: .dropdown:hover, .dropbtn {background-color: #3e8e41;}
The property will applied to both the classes.
.dropdown:hover .dropbtn {background-color: #3e8e41;}
The property is only applied to .dropbtn class elements when it's a descendant of the former class


text:
Q: How to integrate Facebook chat into php website or application I want to know about, how to integrate facebook chat into my application,
i did a lot of R&D and read and implement a lot of example but  didn't work.
so please if you have a sure shot idea or application or anything that make it happen please reply on it..
Thanks in Advance..

A: You may want to look at the live stream plugin:
http://developers.facebook.com/docs/reference/plugins/live-stream/


text:
Q: How do I allow the user to choose between two options? So as of now, I need to write a script prompting a user to select either
1 or 2, 1 creates makes the turtle draw a triangle, and 2 makes it draw a square, so far what I have is.
import turtle
window = turtle.Screen()

rex = turtle.Turtle()
rex.pensize(2)
rex.pencolor("black")
rex.fillcolor("white")
rex.pendown()
rex.begin_fill()

print (40 * '-')
print ("Click Either 1 or 2 To Chose Which To Draw")
print (40 * '-')
print ("1. Triangle")
print ("2. Square")

choice = input('Enter your choice [1-2] : ')
choice = int(choice)

if choice == 1:
    rex.forward(90)
    rex.left(120)
    rex.forward(90)
    rex.left(120)
    rex.forward(90)
    rex.left(120)
    rex.end_fill()
    rex.penup()
elif choice == 2:
    rex.forward(100)
    rex.left(90)
    rex.forward(100)
    rex.left(90)
    rex.forward(100)
    rex.left(90)
    rex.forward(100)
    rex.left(90)
    rex.end_fill()
    rex.penup()

I run the script, and what comes out in the shell is:
Click Either 1 or 2 To Chose Which To Draw
1. Triangle
2. Square
Enter your choice [1-2] :

however, after the colon if you type 1 or 2, nothing on turtle happens?

A: Your program works correctly but it ends before displaying the output. You should pause the control of the program so that user can see the output first. Best way is to add the following one line of code at the end of your program -
window.exitonclick()

Here is the documentation.


text:
Q: Прочтение тела http-запроса в golang Я посылаю запрос на сервер и получаю ответ от него:
// Some code
queryUrl, err := url.Parse(someValidStringUrl)
resp, err := client.Get(queryUrl.String())

Проверим err:
if err != nil {
    log.Panic("Responce:", resp, "\nError:", err)
}

После этого я хочу получить тело моего ответа. Я делаю это следующим образом, но получаю пустой слайс байтов:
var bytes []byte
n, err := resp.Body.Read(bytes)
if err != nil {
    log.Panic(err)
}
log.Println(n, string(bytes))

Лог вывода:

2017/07/13 16:32:36 0

Здесь я нашёл другое решение:
// Some code
queryUrl, err := url.Parse(someValidStringUrl)
resp, err := client.Get(queryUrl.String())
if err != nil {
    log.Panic("Responce:", resp, "\nError:", err)
}
defer resp.Body.Close()

if resp.StatusCode == 200 { // OK
    bodyBytes, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Panic(err)
    }
    log.Println(string(bodyBytes))
}

Пример вывода:

<html lang='en'>
<head>
</head>
<body>
<title>Hello world</title>
</body>
</html>

В чём различия между этими примерами?
Почему мой вариант не работает?

A: 0 возвращается потому, что у вас длина массива bytes равна 0. А функция Read(p []byte) (n int, err error), которую вы используете считывает в массив p до len(p) байт( в вашем случае 0) и возвращает количество прочитанных байт (0 <= n <= len(p)). Описание Reader. И, кстати, вызов  defer resp.Body.Close() тоже очень важно делать, чтобы не допустить утечки ресурсов. Подробнее тут.
Как бы должен был выглядеть ваш код:
import (
    "log"
    "io"
    "net/http"
)

func main() {
    tr := &http.Transport{DisableKeepAlives: true}
    client := &http.Client{Transport: tr}
    resp, err := client.Get("http://ident.me")
    if err != nil {
        log.Panic("Responce:", resp, "\nError:", err)
    }
    defer resp.Body.Close()
    bytes := make([]byte, 100)
    for {
        bytes = bytes[:cap(bytes)]
        n, err := resp.Body.Read(bytes)
        if err != nil {
            if err == io.EOF {
                break
            }
                log.Panic(err)
        }
        bytes = bytes[:n]
    }
    log.Println(string(bytes))
}


text:
Q: jquery mobile slider with knockout components I'm trying to to bind values from jquery mobile slider using knockout components. But I failed to do that. Is there any solution yo it, except custom bindings?
My js-code:
 ko.components.register('slider', {

            viewModel: {

                createViewModel: function (componentInfo) {
                    $(componentInfo.element).slider("refresh");

                }

            },

            template: { element : 'netval'}

        });

        var viewModel = function (value) {
            var self = this;
            self.value = ko.observable(value);
            self.id = ko.observable("slider-new");
            self.min = ko.observable(10);
            self.max = ko.observable(100);
        };
        var Model = new viewModel(50);
        ko.applyBindings(Model);

My fiddle


text:
Q: Accessing one class from another using id as parameter The association between class are as below
class Level < ActiveRecord::Base
     has_many :levels_users
end

class LevelsUser < ActiveRecord::Base
    belongs_to :level
    has_many :schedules
end

class Schedule < ActiveRecord::Base
    belongs_to :levels_user
end

I know the value of level.id. How do I find all schedules belonging to that level.id. level.id is the id of one of the level. I tried something like this:
Level.find(level.id).levels_users.schedule

But it won't work.

A: You could use through property of has_many association.
class Level < ActiveRecord::Base
  has_many :levels_users
  has_many :schedules, through: :levels_users
end

Now you can use
level.schedules


text:
Q: What is the "raw HTTP header"? What is the difference between "HTTP header" and "raw HTTP header"? In Zend Framework in Response Class there are two different arrays for storing headers: _headers[] and _headersRaw[]. And there are appropriate methods for setting each one:
setHeader(), getHeaders(), clearHeader() and
setRawHeader(), getRawHeaders(), clearRawHeaders().
What is the reason to have "header" and "raw header"? Is there some special kind of usage in practice for each of these headers?

A: using setHeader you set key vale pair without worrying about there formatting e.g
$this->getResponse()->setHeader('Content-type','json');

while in case of setRawHeader() you put the whole/full header as it is with  proper formating

A: I'm a bit late here...
Raw means that the header is not URL-encoded, whereas if the word "raw" is omitted, the header is encoded. For example:
$header = 'http://www.mywebsite.com?q=string'; // this is raw, no encoding

echo $header; // no encoding so output is -> http://www.mywebsite.com?q=mystring

echo rawurlencode($header); // URL-encoded so output is -> http%3A%2F%2Fwww.mywebsite.com%3Fq%3Dstring

The special characters  : / ? = have been URL-encoded as
%3A
%2F
%3F
%3D
respectively.


text:
Q: Evaluation in lambda function If I have a function, that returns a function, for example:
f[a_] := a^2 * # &

then
f[3] == 3^2 # &

Is there a way to tell mathematica that I want part of the function evaluated, so that
f[3] == 9 # &

Obviously this example is quite simple, but in general the evaluation may be slow, and better if it's only performed once. I tried wrapping the important part (in this case, a^2) in 'Evaluate', but that didn't help.
Thanks!

A: Leonid already named the big one, With, but there are a few more approaches I'd like to outline.  First of all you can use Evaluate if you wish to evaluate the entire body of the Function, and if the Function isn't part of some larger held expression.  I fully agree with Leonid however that With is more general and less prone to surprises here.  Nevertheless for reference:
f[a_] := Evaluate[a^2 #] &
f[7]

49 #1 &

Likewise you can Apply Function to a List (or any other inert Head without a hold attribute):
f[a_] := Function @@ {a^2 #}
f[7]

49 #1 &

For spot evaluation in a deeper expression (like With) you can use a replacement rule in an inverted fashion. (See this Q&A for more examples.)
f[a_] := a^2 /. x_ :> (x # + 2 + 2 &)
f[7]

49 #1 + 2 + 2 &

Note that 2 + 2 is not evaluated.  Also note the placement of ( ) to group the right-hand-side of RuleDelayed, because & has low operator precedence.

A: The general way to construct functions with partially evaluated pieces is to use With, which is a general device for injecting evaluated pieces in otherwise unevaluated or held expressions. In your case, it would look like
f[a_] := With[{sqa = a^2}, sqa * # &]

The method based on Evaluate is generally less powerful, since evaluation of the entire body may be not desirable, while more deeply nested Evaluate will not result in what you want, due to the (local) way of how Evaluate works (because Function does not evaluate its body at the time it is constructed, the evaluation process, associated with the construction of the function, simply won't come to more deeply nested Evaluate instructions).


text:
Q: E: Malformed entry 1 in list file /etc/apt/sources.list.d/docker.list (URI parse), E:The list of sources could not be read I am using Ubuntu 16.04 but I'm not a computing professinal at all and I'm trying to resolve an issue I have since several months know. It is know becoming a real problem for me as I'd like to install new packages.
3 months ago, I did some manipulations in my terminal. I don't even remember what I was trying to do but it had something to do with implementing a database dump for one of my applications.
Here is the history of the commands I've run and that ruined everything:
 1072  sudo apt-get update
 1073  deb http://ppa.launchpad.net/jonls/redshift-ppa/ubuntu 16.04 main
 1074  sudo apt-get install redshift
 1075  sudo apt install redshift
 1076  sudo apt install redshift-gtk
 1077  HiSuite
 1078  sudo apt-get update
 1079  sudo apt-get install fakeroot
 1080  sudo apt-get build-essential
 1081  deb http://de.archive.ubuntu.com/ubuntu/ saucy-updates main restricted
 1082  sudo apt-get build-essential
 1083  sudo apt-get update
 1084  sudo apt-get build-essential
 1085  sudo vi /etc/apt/sources.list
 1086  deb http://ftp.debian.org/debian wheezy main
 1087  echo "deb http://ftp.debian.org/debian wheezy main" | sudo tee /etc/apt/sources.list.d/docker.list
 1088  echo "deb deb-src http://ftp.debian.org/debian wheezy main" | sudo tee /etc/apt/sources.list.d/docker.list
 1089  sudo apt-get update
 1090  sudo apt-get build-essential
 1091  echo "deb http://ftp.debian.org/debian wheezy main"
 1092  echo "deb deb-src http://ftp.debian.org/debian wheezy main"
 1093  sudo apt-get update
 1094  apt-get
 1095  sudo apt-get update
 1096  cat -n /etc/apt/sources.list | grep "55"
 1097  cat -n /etc/apt/sources.list
 1098  lsb_release -c -s
 1099  sudo rm /etc/apt/sources.list
 1100  sudo -i software-properties-gtk
 1101  sudo sed -i "s/xenial/$(lsb_release -c -s)/" /etc/apt/sources.list
 1102  sudo -i software-properties-gtk
 1103  sudo sed -i "s/xenial/$(lsb_release -c -s)/" /etc/apt/sources.list
 1104  sudo mv /etc/apt/sources.list /etc/apt/sources.list.old
 1105  sudo apt-get install gksu
 1106  sudo sed -i "s/xenial/$(lsb_release -c -s)/" /etc/apt/sources.list
 1107  sudo rm /etc/apt/sources.list
 1108  sudo sed -i "s/xenial/$(lsb_release -c -s)/" /etc/apt/sources.list
 1109  sudo -i software-properties-gtk
 1110  /etc/apt/
 1111  ls
 1112  source
 1113  ..
 1114  sudo cp /etc/apt/sources.list  /etc/apt/sources.list.old
 1115  sudo gedit /etc/apt/sources.list
 1116  ls
 1117  cd home
 1118  ls
 1119  cd kenza
 1120  ls
 1121  sudo apt-get update
 1122  cat -n /etc/apt/sources.list
 1123  sudo -i software-properties-gtk
 1124  sudo apt-get update
 1125  ..
 1126  /etc/apt/
 1127  source
 1128  sudo gedit /etc/apt/sources.list
 1129  ..
 1130  cd home/kenza
 1131  sudo apt-get update
 1132  apt-get
 1133  sudo apt-get uprade
 1134  /etc/apt/
 1135  ls
 1136  sudo gedit /etc/apt/sources.list.old
 1137  sudo gedit /etc/apt/sources.list.save
 1138  ..
 1139  cd home/kenza
 1140  curl https://repogen.simplylinux.ch/txt/xenial/sources_ae6942a4ca69e6ca95d89a755f6959aa12396478.txt | sudo tee /etc/apt/sources.list
 1141  sudo apt-get update
 1142  sudo gedit /etc/apt/sources.list
 1143  sudo gedit /etc/apt/sources.list.d/docker.list
 1144  sudo apt-get update
 1145  sudo gedit /etc/apt/sources.list.d/docker.list

Now each time I try to run an apt-get command I have this result :
E: Malformed entry 1 in list file /etc/apt/sources.list.d/docker.list (URI parse)
E: The list of sources could not be read.

At the moment, I need to install libsqlite3-dev which is impossible.
Thanks a lot for your help!

A: I met the same problem when I was installing Bazel.
And I found it was because I missed a space when typing the following command
echo "deb [arch=amd64] http://storage.googleapis.com/bazel-apt stable jdk1.8" | sudo tee /etc/apt/sources.list.d/bazel.list

When running apt-get update or apt-get upgrade, the sources enumerated in /etc/apt/sources.list are read. It will show the error which you mentioned above.
Hope this will help.
reference

A: I use  after sudo apt update && sudo apt install -y bazel-1.2.1


text:
Q: Is there an abstract way to get all properties of an entity in java? I am using Netbeans 7.2.1 on windows 7.
I am trying to get all the properties of an entity and store them in a String array. I want to do this in the most general way I can think of, so a method like the one in jCSV:
public void writeAll(List<E> data) throws IOException {
    for (E e : data) {
        write(e);
    }
}

You can find that package here: https://code.google.com/p/jcsv/
public String[] getProperties( E e ){

    String [] properties = new String[ e.numberOfProperties ];
    int i = -1;

    for ( P p : e ) {

        i += 1;
        properties[i] = p.toString(); // OR properties[i] = e.getProperty[i].toString();

    }

    return properties;
}

I feel like there should be some way of doing this with the Properties class but I can't figure out a way to use it to get properties from an entity. I think it's just something simple, but I can't see where.

A: As @Ian Roberts alluded to check out the java Introspector class here. The class is only useful if you are using standard Java beans naming conventions for accessing the properties of your entity.
What you'll want to do is get the BeanInfo of the class using the Introspector#getBeanInfo(Class beanClass) method then use the getMethodDescriptors() method of the BeanInfo to retrieve all of the "getter" methods of the bean. From there you can iterate over them and get the properties of your entity and call toString() on them.
One of the advantages of using this class as opposed to just using plain old reflection is that it caches the BeanInfo of the class after it has introspected on it allowing for a performance gain. You also do not have to hardcode anything like get or set in your reflective code.
Here's an example of what your getProperties method would look like using the introspector:
public <T> String[] getProperties(T entity){
    String[] properties = null;
    try {
        BeanInfo entityInfo = Introspector.getBeanInfo(entity.getClass());
        PropertyDescriptor[] propertyDescriptors = entityInfo.getPropertyDescriptors();
        properties = new String[propertyDescriptors.length];
        for(int i = 0 ; i < propertyDescriptors.length ; i++){
            Object propertyValue = propertyDescriptors[i].getReadMethod().invoke(entity);
            if(propertyValue != null){
                properties[i] = propertyValue.toString();
            } else {
                properties[i] = null;
            }
        }
    } catch (Exception e){
        //Handle your exception here.
    }
    return properties;
}

This example compiles and runs.
Keep in mind Apache Commons also has a library BeanUtils which can be very helpful with things like this as well specifically (Javadoc here).


text:
Q: Why is 'static lifetime required for references returned from methods in an impl for a trait object? When I don't include the + 'static in this code, rustc complains. Why?
// adapted from rust-analyzer https://github.com/rust-analyzer/rust-analyzer
trait Upcast<T: ?Sized> {
    fn upcast(&self) -> &T;
}

trait DefDatabase {}
trait HirDatabase: Upcast<dyn DefDatabase> {}

struct RootDatabase{}
impl Upcast<dyn DefDatabase> for RootDatabase {
    fn upcast(&self) -> &(dyn DefDatabase + 'static) {
        &*self
    }
}

`impl` item signature doesn't match `trait` item signature
expected `fn(&RootDatabase) -> &(dyn DefDatabase + 'static)`
   found `fn(&RootDatabase) -> &dyn DefDatabase`
the lifetime requirements from the `impl` do not correspond to the
requirements in the `trait`
verify the lifetime relationships in the `trait` and `impl` between the
`self` argument, the other inputs and its output

Why is 'static lifetime required?
It seems like the dyn is essential to the example. rustc does not complain about this impl, which doesn't mention 'static:
impl Upcast<RootDatabase> for RootDatabase {
    fn upcast(&self) -> &Self {
        self
    }
}

A: You need to explicitly state what the lifetime of the Trait Object &'dyn DefDatabase is so that the borrow checker knows what the lifetime of any references held by the struct behind the pointer are. 'static is the default if you do not define it, or it cannot otherwise be determined from the context. See default trait object lifetimes in the rust language reference for more information.
Adding a lifetime to your Upcast trait definition allows you to drop 'static.
trait Upcast<'a, T: ?Sized + 'a> {
    fn upcast(&self) -> &T; // 'a is not necessary here because the generic `T` may or may not be a trait object
}

trait DefDatabase {}

struct RootDatabase{}
impl DefDatabase for RootDatabase {}

impl<'a> Upcast<'a, dyn DefDatabase> for RootDatabase {
    fn upcast(&self) -> &(dyn DefDatabase + 'a) { // now we can replace 'static with 'a
        &*self
    }
}

impl<'a> Upcast<'a, RootDatabase> for RootDatabase {
    fn upcast(&self) -> &Self { // &Self is not a trait object, so no trait object lifetime is necessary
        self
    }
}

Edit:
It should be noted that this lifetime is not the lifetime of the reference to the trait object, which can be declared separately and is the reason for why the lifetime must be disambiguated with parenthesis.
impl<'a> Upcast<'a, dyn DefDatabase> for RootDatabase {
    fn upcast<'b>(&'b self) -> &'b (dyn DefDatabase + 'a) { // 'b is elided
        &*self
    }
}