Q:

Spring Batch - how many records are read & processed

Is it possible to tell how many records are read and/or processed once the job is executed completely? I've a job that reads data from the database and in the processor, I filter few records based on certain criteria and send them to the writer. I would like to know how many total records are read from the DB and how many are sent to the writer step.
Here is my batch config file.
<bean id="dbItemReader" class="....JdbcCursorItemReader">
    <property name="datasource" ref="datasource"/>
    <property name="sql" ref="select * from"/>
    <property name="rowMapper">
      <bean class="com.my.MyRowMapper"/>
     </property>
 </bean>

<bean id="itemProcessor" class="com.my.MyItemProcessor"/>
<bean id="itemWriter" class="com.my.MyItemWriter"/>

<batch:job id="myJob">
    <batch:step id="step1">
       <batch:tasklet transaction-manager="jobTransactionManager">
             <batch:chunk reader="dbItemReader" processor="itemProcessor" writer="itemWriter" commit-interval="100"/>
       </batch:tasklet>

A:

Spring Batch stores the number of items read, processed, skipped, written, etc in the job repository.  Assuming you're using a database job repository, you can view them there in the BATCH_STEP_EXECUTION table.
You can read more about the information stored in the job repository in the documentation here: http://docs.spring.io/spring-batch/reference/html/metaDataSchema.html

A:

import org.apache.log4j.Logger;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
/**
* Vaquar khan
*/
public class StepExecuListner implements StepExecutionListener {
    static Logger log = Logger.getLogger("badRecordLogger");

    @Override
    public void beforeStep(StepExecution stepExecution) {
        System.out.println("StepExecutionListener - beforeStep");
        log.error("StepExecutionListener - beforeStep " );

    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        System.out.println("StepExecutionListener - afterStep");
        log.error("------------------------------------------------------------------------------------");
        log.error("StepExecutionListener - afterStep:getCommitCount=" +  stepExecution.getCommitCount());
        log.error("StepExecutionListener - afterStep:getFilterCount=" +  stepExecution.getFilterCount());
        log.error("StepExecutionListener - afterStep:getProcessSkipCount=" +  stepExecution.getProcessSkipCount());
        log.error("StepExecutionListener - afterStep:getReadCount=" +  stepExecution.getReadCount());
        log.error("StepExecutionListener - afterStep:getReadSkipCount=" +  stepExecution.getReadSkipCount());
        log.error("StepExecutionListener - afterStep:getRollbackCount=" +  stepExecution.getRollbackCount());
        log.error("StepExecutionListener - afterStep:getWriteCount=" +  stepExecution.getWriteCount());
        log.error("StepExecutionListener - afterStep:getWriteSkipCount=" +  stepExecution.getWriteSkipCount());
        log.error("StepExecutionListener - afterStep:getStepName=" +  stepExecution.getStepName());
        log.error("StepExecutionListener - afterStep:getSummary=" +  stepExecution.getSummary());
        log.error("StepExecutionListener - afterStep:getStartTime=" +  stepExecution.getStartTime());
        log.error("StepExecutionListener - afterStep:getStartTime=" +  stepExecution.getEndTime());
        log.error("StepExecutionListener - afterStep:getLastUpdated=" +  stepExecution.getLastUpdated());
        log.error("StepExecutionListener - afterStep:getExitStatus=" +  stepExecution.getExitStatus());
        log.error("StepExecutionListener - afterStep:getFailureExceptions=" +  stepExecution.getFailureExceptions());
        log.error("------------------------------------------------------------------------------------");

        return null;
    }
}

inside of batch xml
<bean id="stepListener" class="com.test.listener.StepListner" />

<batch:job id="TestDataLoader">
        <batch:split id="split1" task-executor="taskExecutor">
        <batch:flow>
        <batch:step id="step1">
         <batch:tasklet task-executor="taskExecutor" throttle-limit="5">
                <batch:chunk reader="itemReader" writer="itemWriter" commit-interval="${commitInterval}" skip-limit="3">

                    <batch:skippable-exception-classes>
                        <batch:include class="java.lang.NumberFormatException" />
                    </batch:skippable-exception-classes>
                    <batch:listeners>
                        <batch:listener ref="skipListener" />
                            <batch:listener ref="stepListener" />
                    </batch:listeners>
                </batch:chunk>
            </batch:tasklet>
        </batch:step>
        </batch:flow>

        <batch:flow>
        <batch:step id="step2">
             <batch:tasklet task-executor="taskExecutor" throttle-limit="15">
                <batch:chunk reader="itemReaderToDelete"
                    writer="itemWriterToDelete" commit-interval="${commitInterval}" skip-limit="3">
                    <batch:skippable-exception-classes>
                        <batch:include class="org.springframework.dao.DataAccessException" />
                        <batch:include class="java.lang.NumberFormatException" />
                    </batch:skippable-exception-classes>
                    <batch:listeners>
                        <batch:listener ref="skipListener" />
                        <batch:listener ref="stepListener" />
                    </batch:listeners>
                </batch:chunk>
            </batch:tasklet>
        </batch:step>
        </batch:flow>

        </batch:split>
    </batch:job>


Q:

Delaying results of a database by 25 minutes

I'm new here and pretty much an eclectic coder at best so plz be gentle!
Data from a poker tournament is updated in realtime to a database, but we delay the video feed by 20-25 minutes because graphics (i.e. RFID card reader results, etc.) would result in viewers seeing things that players at the table themselves do not - like, everyone elses cards!
That's all handled by proprietary software called PokerGFX, so that part is fine.
But I would like to retrieve the data in the database (seperate from PokerGFX) at the same interval of delay as the video stream to implement a bot with Twitch API so people in Twitch chat can get relevent info like a particular players chip count, but what their chip count was 25 minutes ago, not the realtime data.
I can access the db with MySQL, php and use JS or whatever else is needed. It seems I'm wanting exactly opposite of what everyone else needs...SLOWER data retrieval, not persistent or FASTER LOL!
Thanks for any insight into this.
UPDATE: o but wait there's more: Things have changed, here's what I have:
SELECT * FROM table1
WHERE CurrTime > NOW() - INTERVAL 1 HOUR
LIMIT 1";
is giving less than accurate results +-  2 minutes, so I need the most recent record at least 1 hour old. I have tried all kinds of things, interestingly enough, every google result brings me right back here! All of this data loads into an html that auto refreshes every 10 seconds, and I'm finding that if the database is not updated every 60 seconds or so, the html requesting the data goes blank.

A:

You could store a snapshot of the data in an intermediary database. Retrieve it in real-time, timestamp it and then display the data from the older snapshot (25mins ago). Also, depending on the structure of the original database you may be able to achieve this with only the original database.


Q:

Scrapy referring back to original page instead of next page

I am having trouble using scapry to follow a "next page" link - according to the log it is referring back to itself instead of the "next page" url. Here is the code:
import scrapy

class QuotesSpider(scrapy.Spider):
name = "quotes2"
start_urls = [
        'http://search.jeffersondeeds.com/pdetail.php?instnum=2016230701&year=2016&db=0&cnum=20',
]

def parse(self, response):
    for quote in response.xpath('//div'):
        yield{
            'record' :  quote.select(".//span/text()").extract()
        }

    next_page = response.xpath('//*[@id="nextpage"]/a/@href').extract()

    if next_page is not None:
        print("GOOOO BUCKS!!")
        next_page = response.urljoin(next_page)
        yield scrapy.Request(next_page, callback=self.parse)
    else:
        print("Ahhh fooey!")

The xpath looks to be correct:

But the url in being captured as next_page is the original url (starts_urls)

A:

next_page isn't None, but it is an empty list.
Now the nextpage link being generated with a javascript inside '//table//script/text()'
you can get it with: response.xpath('//table//script/text()').re_first("href=\\'(pdetail.*)\\'>")


Q:

Styling lost on Bootstrap 3 nav li item inside a div

This is an excerpt from a normal bootstrap 3 nav item:

Action

I've left out the irrelevant stuff.
Now in my situation I need one of the menu items to be inside a div:

 Action

The problem with this is that it renders as just a plain unstyled link in the wrong place in the navbar, not styled or located in any way similar to the regular bootstrap menu items as in the first example.
That's all I need, to just be in a div, nothing more than what you see there.
I know I could probably edit the Bootstrap css and just add a rule that accommodates this but I really want to avoid that if possible.
The reason why I have to do this is to do with Angular.js and a dynamic menu option and the ng-if element but in short is there a relatively simple way to force the link in the div to style the same as the other bootstrap 3 nav items?

A:

The short answer is no, if you change the markup then you need to change the styles. Bootstrap uses many child selectors to do it's dirty business, but not many of them are likely to apply to your specific situation. For example, a single level nav might look like:

Home

Profile

Messages

So you'd have 3 styles to override:
.nav-tabs>li>div>a {
  margin-right: 2px;
  line-height: 1.42857143;
  border: 1px solid rgba(0, 0, 0, 0);
  border-radius: 4px 4px 0 0;
}
.nav>li>div>a {
    position: relative;
    display: block;
    padding: 10px 15px;
}
.nav-tabs>li.active>div>a, .nav-tabs>li.active>div>a:hover, .nav-tabs>li.active>div>a:focus {
  color: #555;
  background-color: #FFF;
  border: 1px solid #DDD;
  border-bottom-color: rgba(0, 0, 0, 0);
  cursor: default;
}

However, I would recommend attacking this at the source instead. If you're looking to use Bootstrap components in Angular then I'd try to leverage the Bootstrap UI.


Q:

Why does my input not work on mobile?

I am building a simple guessing game for a class I am taking, and I built it with Bootstrap and custom CSS and JavaScript. However, when I went to the webpage that is hosting the project on my iPhone 6S running iOS 9.2.1, the input where the user places their guess does not accept an argument. On desktop, the input works perfectly, and all of the other buttons work as expected on both desktop and mobile. Why might my input not work on my iPhone?
<input class="btn btn-default btn-lg input" type="text" id="guess" placeholder="Pick a number between 1-100">

My guessing game link
Screenshot: The input doesn't accept anything I try to type
UPDATE: I found a question similar to mine at this link. However, after going through the Bootstrap CSS and deleting the elements the question deemed would solve my problem, the problem remains.

A:

I had the same problem and after looking at Bootstrap "btn" styles I figured out that this style is breaking my input:
.btn {
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

So I changed it to:
input.btn {
  -webkit-user-select: initial;
  -khtml-user-select: initial;
  -moz-user-select: initial;
  -ms-user-select: initial;
  user-select: initial;
}


Q:

Ошибка при qsort по вектору структур

Добрый день. Имеется структура:
struct part
{
    std::string name;
    unsigned int number;
};

Из неё формируется не пустой вектор:
std::vector<part> arr(n);

Вызывается qsort для сортировки по полю number:
qsort(&arr, arr.size(), sizeof(part), comp);

Используя следующий компаратор:
int comp( const void* a, const void* b )
{
    return ((part*)a)->number - ((part*)b)->number;
}

Как мне подсказал гугл компаратор правильный, но из раза в раз я получаю SIGSEGV. Помогите понять в чём ошибка, мб оно ещё кому поможет.
Без сортировки всё работает. При включении в код сортировки в отладчике массив обозначается недоступным после неё.
Полный код:
#include <cstdlib>
#include <string>
#include <vector>

class Rank
{
public:
    static std::string nthRank(const std::string st, std::vector<int> we, int n);
};

struct part
{
    std::string name;
    unsigned int number;
};

int comp( const void* a, const void* b )
{
    return (    ((part*)a)->number - ((part*)b)->number   );
}

std::string Rank::nthRank(const std::string st, std::vector<int> we, int n)
{
    if(st.empty()) return "No participants";
    if(we.size()<(unsigned)n) return "Not enough participants";

    std::vector<part> arr(we.size());
    unsigned int com = 0;

    for(unsigned int i = 0; i < st.size() ; i++)
    {
          if(st[i]!=',')
          {
              arr[com].number +=  std::tolower(st[i])-96 + 1; //1 for length1
              arr[com].name += st[i];
          }
          else
          {
              arr[com].number *= we [com];
              ++com;
          }
    }
    qsort(&arr, arr.size(), sizeof(part), comp);
    return arr[n].name;
}

int main(void)
{
    std::string me("COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH");
    std::vector<int> arr={1, 4, 4, 5, 2, 1};
    me=Rank::nthRank(me, arr, 4);
}

Класс Rank - часть задания.

A:

qsort() — применима только для сортировки Си-массивов (вида strucr part foo [100]).
Для сортировки STL-контейнеров, в том числе и векторов используется std::sort(). На практике во всех распространённых реализациях это тот же qsort().
#include <vector>
#include <algorithm>

bool comp( const part & a, const part b )
{
    return a.number < b.number;
}

int main () {
    // ...
    std::vector<part> arr(n);

    // В классическом С++ стиле
    std::sort(arr.begin(), arr.end(), comp);
    // В C++11 стиле с лямдой
    std::sort(v.begin(), v.end(),
            [](const part &a, const part &b) { return a.number < b.number; });
    // ...
}

Вообще говоря, если элементами вектора являются объекты POD-типа (тривиального типа в терминологии С++11), то для сортировки оного формально можно использовать и qsort(), однако это крайне некрасиво и при последующем внесении изменений в код чревато ошибками.
struct part
{
    //! При замене на std::string с точки зрения стандарта в qsort () будет UB!
    char name[32];
    unsigned number;
};

int comp( const void* a, const void* b )
{
    const unsigned anum=((part*)a)->number, bnum=((part*)b)->number;
    return anum>bnum ? 1 : (anum == bnum ? 0 : -1);
}

// ...
std::vector<part> arr;
// ...
// Не надо так делать! Даже если формально ошибки нет.
qsort(&arr[0], arr.size(), sizeof(part), comp);


Q:

How to subtract numbers in binary

In this example, it is 5 - 2 which equals 3. How does the computer know that the outcome isn't negative though and why does it not think the answer is 35?
 0101 = 5
+1110 = -2
 -----------
10011 = 3

What does the 1 and the front of the answer represent?

A:

The leading one is called overflow.
You are operating on a 4 bit byte if the operation you are using does not move overflow to another byte it will be lost.
  0101 =  5
 +1110 = -2
-----------
  0011 =  3

Usually processors have a series of flags that can be set by operations in this case the overflow flag will be set to true. As the result exceeds what can be stored in a byte.


Q:

Yarden's River Name

The Torah refers (e.g. Numbers 33) to a river called ירדן. Why is it called ירדן?

A:

Name origin: Hebrew: ירדן (yardén, descender) < ירד (yarad, to descend)

via:
Klein, Ernest, A Comprehensive Etymological Dictionary of the Hebrew Language for Readers of English, The University of Haifa, Carta, Jerusalem, p.264
While שיורד מדן ("which descends from Dan") is a rather neat derivation and mnemonic, the Dan part would seem to be unnecessary, since the nun ending seems morphological; also, we would be reusing the daled. Also, we would need to grapple with Biblical references to "haYarden hazeh" (said to Yaakov), where it was surely not called Dan at that point, to spark the derivation. In sum, a nice derash, but I would favor Klein's related etymology.

A:

The book Mincha Belulah says, from the Gemara in Bechoros, that it's because יורד מדן, i.e. it flows down from the North part of Israel, that belongs to Dan.


Q:

English to Propositional Calculus: M. If M and T then P. If L then T.

I have the following collection of statements:

I have money. If I have money, and have time, I can buy a pizza. If I left home early enough, I have time.

The atomic sentences can be represented as the following symbols:

M: I have money.
T: I have time.
P: I can buy pizza.
L: I left home early enough.
T: I have time.

How would I express the statements in terms of propositional calculus?
The part I'm confused about is how to join '$M$', '$M\land T\Rightarrow P$' and '$L \Rightarrow T$'.

A:

Simply use the "$\land$" connective to join them, but note that since it has higher precedence than "$\to$" (by standard convention), you have to use brackets:

$M \land ( M \land T \to P ) \land ( L \to T )$".


Q:

Como inserir registros com PDO no MySQL sequencialmente

Estou enviando seis campos de um formulário para inserir em meu MySQL mas somente os três primeiros estão indo corretamente, preciso inserir os três primeiros e na sequência os outros três, mas estou com essa dificuldade em entender como fazer.
As variáveis são essas?

$IdCandidato = $_SESSION['IdCandidato'];
$IdArea1 = $_POST['Area1'];
$IdCargo1 = $_POST['Cargo1'];
$Experiencia1 = $_POST['Experiencia1'];

$Area2 = $_POST['Area2'];
$Cargo2 = $_POST['Cargo2'];
$Experiencia2 = $_POST['Experiencia2'];

$DataHoraAtualizacao = date('Y-m-d H:i:s');

As variáveis IdCandidato e DataHoraAtualizacao estou recuperando no momento da tentativa de gravação.
Vou colocar uma imagem para explicar melhor, o formulário é esse:

A estrutura da tabela está assim:

CREATE TABLE `crrAreaExpectativa` (
    `IdAreaExpectativa` INT(10) NOT NULL AUTO_INCREMENT COMMENT 'Código da area expectativa',
    `IdCandidato` INT(10) NOT NULL COMMENT 'Código do candidato',
    `Opcao` TINYINT(1) NOT NULL COMMENT 'Opção: 1 ou 2',
    `IdArea` INT(10) NOT NULL COMMENT 'Código da área',
    `IdCargo` INT(10) NOT NULL COMMENT 'Código do cargo',
    `DataHoraAtualizacao` DATETIME NOT NULL COMMENT 'Data/Hora da atualização',
    PRIMARY KEY (`IdAreaExpectativa`, `IdCandidato`),
    INDEX `IDXOpcao` (`Opcao`),
    INDEX `IDXIdArea` (`IdArea`),
    INDEX `IDXIdCargo` (`IdCargo`),
    INDEX `FK_AreaExpectativa_Candidato` (`IdCandidato`),
    CONSTRAINT `FK_AreaExpectativa_Candidato` FOREIGN KEY (`IdCandidato`) REFERENCES `crrCandidato` (`IdCandidato`) ON UPDATE NO ACTION ON DELETE CASCADE
)
COMMENT='Área e cargo onde o candidato deseja trabalhar'
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=14
;

O que estou tentando fazer é isso:

try {

    // INICIALIZA A TRANSAÇÃO
    $conexao->beginTransaction();

        try {

            // INSERT 3 PRIMEIROS CAMPOS
            $sql1 = 'INSERT INTO `crrAreaExpectativa` (`IdCandidato`, `Opcao`, `IdArea`, `IdCargo`, `DataHoraAtualizacao`) VALUES (?,?,?,?,?)';
            $stm = $conexao->prepare($sql1);
            $stm->bindValue(1, $IdCandidato, PDO::PARAM_INT);
            $stm->bindValue(2, $Experiencia1, PDO::PARAM_INT);
            $stm->bindValue(3, $IdArea1, PDO::PARAM_INT);
            $stm->bindValue(4, $IdCargo1, PDO::PARAM_INT);
            $stm->bindValue(5, $DataHoraAtualizacao, PDO::PARAM_STR);
            $retorno = $stm->execute();

            // INSERT 3 ÚLTIMOS CAMPOS
            $sql2 = 'INSERT INTO `crrAreaExpectativa` (`IdCandidato`, `Opcao`, `IdArea`, `IdCargo`, `DataHoraAtualizacao`) VALUES (?,?,?,?,?)';
            $stm = $conexao->prepare($sql2);
            $stm->bindValue(1, $IdCandidato, PDO::PARAM_INT);
            $stm->bindValue(2, $Experiencia2, PDO::PARAM_INT);
            $stm->bindValue(3, $IdArea2, PDO::PARAM_INT);
            $stm->bindValue(4, $IdCargo2, PDO::PARAM_INT);
            $stm->bindValue(5, $DataHoraAtualizacao, PDO::PARAM_STR);
            $retorno = $stm->execute();

            $conexao->commit();

        } catch (PDOException $erro) {

                // DESFAZ TRANSAÇÃO ATUAL
                $conexao->rollBack();
                $erro = $erro->getMessage();
                $retorno = array('codigo' => '0', 'mensagem' => ' Erro ao inserir o registro. Tente novamente [2]. ::$erro');
                $conexao = null;

                // RETORNO DE MENSAGEM
                echo json_encode($retorno);
                exit();

        }

} catch (Exception $e) {

    // DESFAZ TRANSAÇÃO ATUAL
    $conexao->rollBack();
    $retorno = array('codigo' => '0', 'mensagem' => ' Ocorreu um erro na gravação, tente novamente [5]. ::$erro');
    $conexao = null;

    // RETORNO DE MENSAGEM
    echo json_encode($retorno);
    exit();
}

$retorno = array('codigo' => '1', 'mensagem' => ' Registro inserido com sucesso');

// FECHA CONEXÃO
$conexao = null;

// RETORNO DE MENSAGEM
echo json_encode($retorno);
exit();

A:

As variáveis não estão iguais. Na parte onde você recebe os valores dos 3 últimos campos por $_POST está com o nome errado em relação ao seu insert no banco.
Como está:
$Area2 = $_POST['Area2'];
$Cargo2 = $_POST['Cargo2'];

Como deveria está:
$IdArea2 = $_POST['Area2'];
$IdCargo2 = $_POST['Cargo2'];

Assim, as variáveis ficaram iguais ás variáveis do seu insert:
$stm->bindValue(3, $IdArea2, PDO::PARAM_INT);
$stm->bindValue(4, $IdCargo2, PDO::PARAM_INT);


Q:

Change laptop 5.5mm barrel connector

I'm looking to replace the female 5.5mm barrel jack connector on my
laptop with a female USB C connector. The replacement USB C port need
only provide power and nothing further. I'm not sure how to go about
this. I've never modified anything electronic before, soldering is new
to me.
The model of the laptop is a
Lenovo X230t
My hope is that the scope of the project is just:

Open up laptop.
Remove old jack.
Solder on USB C jack.
Get USB-C AC adaptor with matching DC output for laptop.

What I want from y'all are:

An understanding of the difficulty of doing this: the time and money
costs of this project. Time covers any time spent doing the actual
task and learning skills that I'd need to learn to do it competently.
Is the project more complicated than the steps listed above? If so,
how?

Some suggested contributions to satisfy these goals are:

Pointing out difficulties that I will face outside of the above
listed hopeful project scope. For instance, saying that I'd have to
modify something on my motherboard, or I'd have to add something else
after the USB C female port so that power from the port can go to the
motherboard. This will help me ask further questions about both the
time and money costs of dealing with these problems.
Giving a solution to one of the pointed out difficulties and giving
some estimate of the time/money costs involved in carrying out the
solution.
Helping me understand the skills required to carry out this plan (I
assume soldering is one). If the project would involve more detailed
knowledge than "connect this wire to that other wire", then I'm out of
my depth, and I wouldn't know what to do or where to look to gain
those competencies.
Giving a the broad strokes of a plan to work this project, from
start to finish. That's

The steps of the plan, stated in general terms ("solder this",
"buy that", "attach blah blah thing"). I ask only for broad
strokes because detailed plans are time consuming to create, and
it would be easier to prepare some of these details in conjunction
with me, so you can get an idea of the sort of things I can
do/learn quickly.
A list of the materials involved and where to obtain them (as
best as you can). If you can't provide a location, please try to
provide an approximate price and/or the sort of retailer that may
sell the item (like "hobby shop" or "old pc parts store" or
something).

This is a somewhat similar question:
Replacing a 5V female barrel connector on USB hub with female USB micro
PS: Another possibility might be some sort of adaptor from USB C male
to 5.5mm barrel male that would provide the correct amount of power.
This is okay, but not desired. I have to replace the barrel jack
itself on my laptop anyway. The plug of my AC adaptors doesn't hold
well in them. But if this method is significantly easier than
replacing the connector altogether... then I'll probably do that.
Edit: My original intent was to get/construct a magnetic connector for an older laptop. To that end, I've found the following sources, which make these connectors for a barrel-jack-style plug:

https://www.instructables.com/id/MagSafe-for-the-Rest-of-Us-A-DIY-Magnetic-Power-A/
https://www.instructables.com/id/ThinkSafe:-A-Magnetic-Power-Connector-for-Thinkpad/
https://www.instructables.com/id/Magnetic-Laptop-power-connector/

I was surprised to find these, given that magnetic connectors for power cables are supposed to have a very broad patent on them.

A:

My hope is that the scope of the project is just:

There are several problematic points in your "scope of the project". Let's go point-by-point:

(1) Open up laptop.

Okay, no problem here.

(2) Remove old jack.

Okay, doable as well, with certain care and right tools like hot air pen (since the connector might have through-hole legs across a thick ~12-layer PCB.

(3) Solder on USB C jack.

Here the problems start. Type-C footprint is very tight, and there is 2500% probability that you can't fit the old footprint. You will need to use some interposer mini-board, and glue it somehow into the old place. Mechanical properties of this rework will be highly questionable, and the new Type-C connector will likely fall off after 10-15 insertions. But this is still doable. However it won't be functional unless you add proper pull-downs and other sophisticated electronics to it, see below.

(4) Get USB-C AC adaptor with matching DC output for laptop.

Now this is a real problem. Your laptop has likely something as 19-20-V input for normal operation. If you plan to get a "USB-C AC-DC adapter", this is not going to happen, even it would list "matching DC output" as one of its output options. The reason is that any Type-C adapter-charger must have a Power Delivery negotiation protocol in place, to move form the default-safe initial +5V level to higher power profiles. More, initially a Type-C charger-adapter won't output ANY VOLTAGE at all until the Type-C cable will see 5.1k pull-down on CC lines (which you should have after attaching your new Type-C connector).
The second hurdle will be PD, Power Delivery. Unless you get a set of special ICs, hook them up to CC line and program them for desired PD profile (19-20 V 3 A or something), a normal Type-C adapter won't give you the desired power.
One thing you can do is to get the fixed-voltage (your old) AC-DC adapter (19 V 3 A) and replace the native barrel plug with Type-C plug. However, in this case you are seriously risking to fry many other Type-C gadgets if somebody accidentally will plug your modified self-made Type-C charger into them, at least Type-C smartphones will be 98% fried, since they wouldn't have the tolerance to 20-V profile.
ONE MORE: The ThinkPad X230T laptop has three-pin connector,

The third (center) pin is used for power identification of the adapter. I am not sure which method is used, but you will need to emulate proper conditions (analog level or serial protocol) before your laptop will resort to full functionality.
I feel somehow that at this point you will abandon this project, so the IC sourcing and pricing won't be needed.


Q:

Rewrite existing file request to subdirectory

I have a php framework on a shared hosting and this is my directory structure:
root (can't change because of shared hosting; here's the .htaccess)
  vendor
  web (index.php, assets in subfolders like css, images or js)

My .htaccess looks like this:
<IfModule mod_rewrite.c>
   Options -MultiViews
   RewriteEngine On
   RewriteBase /
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^ web/index.php [L]
</IfModule>

Now the framework routing works, but I want Apache to search all existing files (${REQUEST_FILENAME} !-f) only in the web folder, not from the root level.
Example:
http://www.domain.tld/hello/world (virtual path) is rewritten to index.php
http://www.domain.tld/css/bootstrap.css is not found, because the file is in the web/css folder.
http://www.domain.tld/web/css/bootstrap.css would match, because of the RewriteCond %{REQUEST_FILENAME} !-f
Is it possible to combine RewriteCond %{REQUEST_FILENAME} !-f with a folder rewrite for existing files only? All other request must be rewritten to the index.php
All in all I want it similar as setting the VirtualHost->DocumentRoot to the web folder.
Thanks!

A:

You can use these rules in site root .htaccess:
<IfModule mod_rewrite.c>
   Options -MultiViews
   RewriteEngine On
   RewriteBase /

   RewriteRule ^/?$ web/index.php [L]

   # if file is found in web/ folder then route it
   RewriteCond %{DOCUMENT_ROOT}/web/$1 -f
   RewriteRule ^(.+)$ web/$1 [L]

   # otherwise route it to web/index.php
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^ web/index.php [L]
</IfModule>


Q:

How to pass different URL to webView from some buttons in swift?

I have some buttons in first view controller and a webView in second view controller. How to pass different url from different buttons to the webView? For example, the first button will leads to a google website and the second one is Facebook but using the same webView. Do I need to create different segues for each button or just one? If using just one, where should I start pulling that blue line (that line when you hold the control key)?
In first viewController:
class CafesView: UIViewController {

    @IBOutlet weak var topBar: UIView!
    @IBOutlet weak var button1: MDCFloatingButton!
    @IBOutlet weak var button2: MDCRaisedButton!
    @IBOutlet weak var button3: MDCRaisedButton!
    @IBOutlet weak var button4: MDCRaisedButton!
    @IBOutlet weak var button5: MDCRaisedButton!
    @IBOutlet weak var button6: MDCRaisedButton!
    @IBOutlet weak var button7: MDCRaisedButton!
    @IBOutlet weak var button8: MDCRaisedButton!
    @IBOutlet weak var button9: MDCRaisedButton!

    let cafes = [
        "Banana Joe's",
        "College Eight Cafe",
        "Global Village",
        "Iveta",
        "Oakes Cafe",
        "Perk Coffee Bar",
        "Stevenson Coffee House",
        "Terra Fresca",
        "Vivas"
    ]

    var urlToPass: String!

    override func viewDidLoad() {
        super.viewDidLoad()

        topBar.layer.shadowColor = UIColor.black.cgColor
        topBar.layer.shadowOpacity = 0.5
        topBar.layer.shadowOffset = CGSize(width: 0, height: 2)
        topBar.layer.shadowRadius = 5
        button1.layer.cornerRadius = 20
        button2.layer.cornerRadius = 20
        button3.layer.cornerRadius = 20
        button4.layer.cornerRadius = 20
        button5.layer.cornerRadius = 20
        button6.layer.cornerRadius = 20
        button7.layer.cornerRadius = 20
        button8.layer.cornerRadius = 20
        button9.layer.cornerRadius = 20

    }

    @IBAction func bananaJoes(_ sender: UIButton) {
        urlToPass = "https://dining.ucsc.edu/pdf/banana-joes-menu.pdf"
    }

    @IBAction func collegeEightCafe(_ sender: UIButton) {
        urlToPass = "https://dining.ucsc.edu/pdf/c8-menu.pdf"
    }

    @IBAction func globalVillage(_ sender: Any) {
        urlToPass = "https://www.foodbooking.com/ordering/restaurant/menu?restaurant_uid=d368abee-3ccc-40d7-be7f-3ca5d4cbd513&glfa_cid=1263531392.1571083521&glfa_t=1571083566919"
    }

    @IBAction func iveta(_ sender: UIButton) {
        urlToPass = "https://iveta.com/pages/iveta-ucsc-menu"
    }

    @IBAction func oakesCafe(_ sender: UIButton) {
        urlToPass = "https://dining.ucsc.edu/pdf/oakes-menu-2019-20.pdf"
    }

    @IBAction func perkCoffeeBar(_ sender: UIButton) {
        urlToPass = "https://google.com" //This url is just a placeholder
    }

    @IBAction func stevensonCoffeeHouse(_ sender: UIButton) {
        urlToPass = "https://dining.ucsc.edu/pdf/stevenson-coffee-house-menu.pdf"
    }

    @IBAction func terraFresca(_ sender: UIButton) {
        urlToPass = "https://dining.ucsc.edu/terra-fresca/pdf/terra-fresca-menu.pdf"
    }

    @IBAction func vivas(_ sender: UIButton) {
        urlToPass = "https://dining.ucsc.edu/pdf/vivas-menu.pdf"
    }

    @IBAction func dismiss(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        super.prepare(for: segue, sender: sender)
        guard let destination = segue.destination as? CafesMenu else { return }

        destination.detailURL = urlToPass
        urlToPass = nil
    }

}

In the second one:
import UIKit
import WebKit

class CafesMenu: UIViewController {

    @IBOutlet weak var webView: WKWebView!

    var detailURL: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        print("URL Requested: \(detailURL)")
    }

    override func viewWillAppear(_ animated: Bool) {
        let url = URL(string: detailURL!)
        let request = URLRequest(url: url!)
        webView.load(request)
    }

    @IBAction func dismiss(_ sender: UIBarButtonItem) {
        self.dismiss(animated: true, completion: nil)
    }

}

A:

What you need to do is use prepareForSegue:sender: to set a property in your destination view controller. prepareForSegue:sender: will be called before your initial view controller segues to any destination view controller. Within this function, we can check which button was pressed and set the appropriate URL in the destination view controller accordingly.
This approach will allow you to use any segue between your buttons and your destination view controller. This means, you simply have to drag the blue line from the buttons to the view controller you want to segue to.
1. Within your storyboard, create a segue between your first view controller and your destination view controller. This is done by holding control, clicking on the first view controller in the interface builder, and dragging over the destination view controller. Then choose a segue type:

Now, select this segue and give it the Identifier "InitialVCToDestinationVC" in the attributes inspector:

2. Make a property called urlToPass of type URL in your initial view controller:
class InitialViewController: UIViewController {
    var urlToPass: URL!

    @IBAction func googleButtonPressed(_ sender: Any) {
    }

    @IBAction func facebookButtonPressed(_ sender: Any) {
    }
}

3. Make a property called receivedUrl in the destination view controller:
class DestinationViewController: UIViewController {
    var receivedUrl: URL!

    @IBOutlet var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let request = URLRequest(url: receivedUrl)
        webView.load(request)
    }
}

4. Set the urlToPass depending on which button is pressed and use the prepareForSegue:sender: function to set the destination view controller's url accordingly. Then, make use of performSegue(withIdentifier:sender:) to perform the segue with identifier InitialVCToDestinationVC.
class InitialViewController: UIViewController {
    var urlToPass: URL!

    @IBAction func googleButtonPressed(_ sender: Any) {
        urlToPass = URL(string: "www.google.com")
        performSegue(withIdentifier: "InitialVCToDestinationVC", sender: nil)
    }

    @IBAction func facebookButtonPressed(_ sender: Any) {
        urlToPass = URL(string: "www.facebook.com")
        performSegue(withIdentifier: "InitialVCToDestinationVC", sender: nil)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        super.prepare(for: segue, sender: sender)

        guard let destination = segue.destination as? DestinationViewController else { return }

        destination.receivedUrl = urlToPass
        urlToPass = nil
    }
}

5. (optional) Make use of the shouldPerformSegueWithIdentifier:sender: method within InitialViewController and check whether or not urlToPass is valid. If urlToPass is valid, perform the segue, else present an alert.
class InitialViewController: UIViewController {

    ...

    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
        if let urlToPass = urlToPass {
            // check if your application can open the NSURL instance
            if !UIApplication.shared.canOpenURL(urlToPass) {
                let alertController = UIAlertController(title: "Cannot open URL.", message: "This is an invalid URL.", preferredStyle: .alert)
                let ok = UIAlertAction(title: "Okay", style: .cancel, handler: nil)
                alertController.addAction(ok)
                present(alertController, animated: true, completion: nil)
            }
            return UIApplication.shared.canOpenURL(urlToPass)
        }
        return false
    }
}

End result:

Here's a link to the Xcode project I made the above gif from: https://github.com/ChopinDavid/PrepareForSegue


Q:

use global config object in react app

I have config.js file defined by generator;
'use strict';

import baseConfig from './base';

let config = {
  appEnv: 'dev',  // feel free to remove the appEnv property here,
  baseUrl:'https://mod970274.sharepoint.com',//'http://maliye.milliemlak.gov.tr',
  listName:''
};

export default Object.freeze(Object.assign({}, baseConfig, config));

and here how I call it.
import config from 'config';

class FooterState {
    @observable items =[];
    constructor(){
        config.listName = 'FooterMenu';
        this.getItems();
    }
    getItems() {
  fetch(`${config.baseUrl}/_api/web/lists/getbytitle('${config.listName}')/items`, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',

but eventhough using examples looks same it throws undefined exception in constructor. this is how it looks:

how can I use config object everywhere in project

A:

export default Object.freeze(Object.assign({}, baseConfig, config));

This line freezes the object, which means you can't reassign any of its properties:

The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed.  The method returns the object being frozen.

If you want to change the data on this object, you should remove the Object.freeze:
export default Object.assign({}, baseConfig, config) // Or just: export default {...baseConfig, ...config}


Q:

Why can't the instance bound to an event be collected by the GC?

This Question based on this question:
How to dispose the local variable that contains event
Someone said:one event handler to an instance,the reference count of the instance will added? why?

A:

Your linked question, as Jon Skeet states, has it backwards. The only thing keeping watcher alive is perhaps its own internal implementation where it may (or may not) register an event with a lower-level object that is responsible for feeding back "ticks". -but this is just conjecture.
Clicking the button twice will yield two separate watcher instances, each with one subscriber to the PositionChanged event (which just happens to be the same method on the same instance).
Importantly, it isn't the PositionChanged subscriber that is keeping watcher alive after the method quits - it is something else (I suspect buried within the GeoCoordinateWatcher implementation). When the method exits, a reference to a particular instance of watcher is correctly popped off the stack, but due to another reference being held on watcher the effective reference count in the eyes of the CLR is still greater than zero - therefore, not eligible for garbage collection.
Because of this, it will continue on to fire the PositionChanged event. As nothing in the event stops the watcher from continuing, I'm going to guess you may have a memory leak because each button click will create and leave alive a watcher instance.
You either need to store and use only one GeoCoordinateWatcher class, or close-off / dispose / stop it each time you handle the event.

The usual consideration with events and subscriptions is being mindful of short-lived objects subscribing to long-lived objects.
Delegates hold references to a particular method in a particular instance of a class (or just the type itself if it were a static method). Subscribing to an event causes the event publisher to inadvertently hold a reference to the subscriber instance via the subscription's delegate.
Obviously, if you register a static method as an event handler, you won't get this reference count because there is no instance.
A memory leak can occur if the subscriber is short-lived and the event publisher is long-lived, if you don't unsubscribe. Assume the subscriber would like to be eligible for GC, because it has an active subscription against an event somewhere and that object still lives, it cannot be eligible until it is removed from that subscription list.


Q:

How to find or install themes tkinter ttk for Python

I've been making a bot for the past 3 months and it works perfect just with code. Now my next goal is to make a GUI for it, however I've been finding some obstacles and the main one is the ability to not look like a 30years old program.

I am on Windows 7.
I am using Python 3.3.2 only (no packages, addons, plugins, other programs, etc. Just what it gets installed from http://www.python.org/download/).
Python 3.3.2 includes the abbility (as far as i know) to use Tkinter and ttk.

However, while tkinter works fine for my tests, I've been unable to find a way to display all availible themes or a way to download more new themes.
This won't work and i have no idea why:
from tkinter import *
from tkinter.ttk import *
s=Style()
s.theme_names()

So... can anyone tell me how to display all availible themes just from IDLE 3.3.2 without installing anything else? Or where I could get more themes, since I'm looking for a modern one.

A:

ok, i had to install ttk from https://pypi.python.org/pypi/pyttk


Q:

Windows form distance measuring program acts up after multiple images opened up

I have a program which allows the user  to open an image and measure it by dragging the mouse over it. The image opens up in a picture box when you press a button. The program works after two images are opened, but not after three images are opened. After the third image, the measurements are grossly overestimated.
Here is the part of my code which opens the image:
private void openPlan_Click(object sender, EventArgs e)// open plan folder
    {
        pictureBox1.Image = null;

        // open file dialog
        OpenFileDialog open = new OpenFileDialog();
        open.InitialDirectory = @"C:\Users\Admin\Documents\complete Lumber Estimation Tool\Plans\";
        // image filters
        if (open.ShowDialog() == DialogResult.OK)
        {

            trackBar1.Value = 4;
            zoom = 1.0F;
            imgOriginal = null;
            // display image in picture box
            imgOriginal = new Bitmap(open.FileName);

            pictureBox1.Image = imgOriginal;
       }
  }

Is this mainly a problem with how a windows form program stores data?
If so, how do I make sure the program isn't using any data or parameters from the previous image?

A:

As in my comment:
Always dispose images, specially with open file handles.
Use:
imgOriginal?.Dispose();
pictureBox1.Image?.Dispose();

instead of: .Image = null
...in a greater detail:
The Image class is using GDI, which causes to open handles. These handles are not closed automatically by just loosing the reference in your application. They are not collected by the garbrage collector (docs.microsoft.com Garbrage-Collection).
This can result in unpredictable behavior of your application or beyond.
e.g: If you load an image from a file, the open handle results in a filelock(!) also if you just wand to display the image.
For that cases, you can load the whole image into a intermediate System.IO.MemoryStream object.
Encapsulate the image from the original source like this:
var stream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(filepath));
var Image = Image.FromStream(stream);

This will load the file into the memory and the image out of it.
Take care to Dispose the stream and the Image after your use or when loading a different image.


Q:

Run and stop a monitoring command as sudo for s seconds every m minutes

I want to run sudo airodump-ng -w myfile every ten minutes or so, for m  minutes. It does not matter if the running time shifts (that it, if it runs m minutes later each time).
Notice that this is a monitoring program, which won't just output and exit. I suppose the solution for this one question is also valid for similar monitoring programs.
I was thinking about putting something like:
*/10 * * * * airodump-ng mon0 -w myfile
into crontab. There is no need to change the myfile name, airodump can correctly check whether myfile exists and create a myfile-02 and so on.
However, how should I stop it running after s secs? pkill airodump is the only thing I can think of. Is this the best for running it 1 minutes twice an hour?
20,40 * * * * airodump-ng mon0 -w myfile
21,41 * * * * pkill airodump-ng

A:

Don't use pkill. Instead, run your app under the timeout command from the coreutils package:
*/10 * * * * timeout 5m airodump-ng mon0 -w myfile

(Where here 5m means to run for 5 minutes.) Use --signal if you need something other than TERM.


Q:

Web hosting deciding to pay for hosting or host your own?

Is there a guide out there on how to choose when to pay for web hosting vs. hosting your own? Assuming that root access is a must I would like to compare things like cost, scalability and personal stress.
Here is what I could come up with.
Paying for web hosting:
Benefits:

Much cheaper for a small scale.  I assume anything under $50 a month would be cheaper than paying for the bandwidth of hosting.
No stress in dealing with power outages, server restarts or internet going down.
For the most part less busy work involved with setting up.

Negatives:

Cost goes way up when higher specs are needed (for example monthly cost triples with ability to use 8gb of ram that you can buy for $90 ).  This means you have to target a particular ram usage and monitor so your instance stays within the threshold.
root access for the most part is a premium.
You may get tied into a vendor specific deployment process.

Hosting on own :
Positives:

100% control of specs and software.
When you get past paying for the bandwidth you get much more bang for your buck by building your own machine.

Negatives:

Doesn't make financial sense if bandwidth costs are more than web hosting costs.
Having to deal with power outages, server restarts or internet going down.

I think the best of both worlds would be if there was a place that dealt with bandwidth, power outages and server restarts but you provided your own server.  Kind of like a 24 hour day care for a server.  Does anything like that exist?

A:

The 24x7 care are looking for is called Managed Hosting -- many firms exist that do that in various capacities for various fees. I'll note it is nice but it still won't necessarily replace having a good, knowledgeable engineer who knows your application and stack around to put out fires -- the host often can do little more than tell you your database server has locked up but they likely can't fix it.
In 2013, if you are building an internet facing application, there is very, very little reason to burden yourself with hosting the production instances yourself unless you happen to have in your possession a data center with all the typical niceties they come with like redundant power, redundant internet connections, 24x7 skilled labor around to support your box. If you've got those you'd also probably appreciate what stuff like that costs and why it seems dramatically more expensive.

A:

I would say "paid" hosting has many many different flavors (shared, dedicated virtual, dedicated, etc..). And those comparisons are most likely available all over. When comparing that to hosting your own (I'm assuming in your home / garage), there is no comparison for any real world application if uptime, security and reliability are a concern.
Hosting your own machine is okay for information websites that wont sue you for going down, but you take on all the risk for uptime and security. both of which can drive your clients away (if that's your model), or compromise your customers data (if you're hosting their data).
you can get a basic hosting plan for very cheap, even free, and will require much less pain so it doesnt really make sense
if you want full control and 100% of the resources, then I would recommend getting a dedicated box from a hosting company, generally you just have to pay for the OS license if that even applies.. then you can RDP in and do whatever you want to it, you'll still have to worry about local security, but the power company wont be shutting you down during the day for their normal maintenance.
Amazon offers some free virtual instances, and I would recommend starting there.. the machines are pretty weak, but the price justifies the performance you get.


Q:

Android how to play different sound for each item in recyclerview

I build app with images of animals, and after you click on animal, its play sound for that animal.
I use Recyclerview for displaying all animals items.
My problem is that i do not know how to handle click event for playing sounds for each animal. I do know how to play same sound for each item in recyclerview but i do not know how to handle specific sound for each item.
this is code for my class where i handle data, where i put all animal names, images and sounds for each object.

package com.example.android.animalsoundsforchildren;

import java.util.ArrayList;

public class Zivotinje {
    private String mAnimal_name;
    private int mAnimal_slika;
    private int mSound;

    public Zivotinje(String animalName, int slika, int sound) {
        this.setmAnimal_name(animalName);
        this.setmAnimal_slika(slika);
        this.setmSound(sound);
    }

    public String getmAnimal_name() {
        return mAnimal_name;
    }

    public void setmAnimal_name(String mAnimal_name) {
        this.mAnimal_name = mAnimal_name;
    }

    public int getmAnimal_slika() {
        return mAnimal_slika;
    }

    public void setmAnimal_slika(int mAnimal_slika) {
        this.mAnimal_slika = mAnimal_slika;
    }

    public int getmSound() {
        return mSound;
    }

    public void setmSound(int mSound) {
        this.mSound = mSound;
    }

    //putting data
    public static ArrayList<Zivotinje> createZivotinjeList() {
        ArrayList<Zivotinje> animals = new ArrayList<Zivotinje>();

        animals.add(new Zivotinje("Sheep", R.drawable.domestic_sheep, R.raw.gun));
        animals.add(new Zivotinje("Sparrow", R.drawable.birds_sparrow, R.raw.birds_sparrow));
        animals.add(new Zivotinje("Dolphin", R.drawable.sea_dolphin, R.raw.dolphin));
        animals.add(new Zivotinje("Bumblebee", R.drawable.insects_bumblebee, R.raw.bumblebee));
        animals.add(new Zivotinje("Tractor", R.drawable.cars_tractor, R.raw.tractor));
        animals.add(new Zivotinje("Baby Cry", R.drawable.laugh_baby_cry, R.raw.baby_cray));
        animals.add(new Zivotinje("Wind", R.drawable.nature_wind, R.raw.wind));
        animals.add(new Zivotinje("Golf", R.drawable.effects_golf, R.raw.golf));
        animals.add(new Zivotinje("Clock", R.drawable.others_clock, R.raw.clock));

        return animals;
    }
}

This is code for Adapter, and here i handle click and when i click on item, it play the same sound but how to play different sound for each animal, not the same sound like here. Here i always play sound R.raw.clock

package com.example.android.animalsoundsforchildren;

import android.content.Context;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class ZivotinjeAdapter extends RecyclerView.Adapter<ZivotinjeAdapter.ViewHolder> {

    @Override
    public ZivotinjeAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        // Inflate the custom layout
        View contactView = inflater.inflate(R.layout.item_zivotinje, parent, false);

        // Return a new holder instance
        ViewHolder viewHolder = new ViewHolder(contactView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ZivotinjeAdapter.ViewHolder viewHolder, int position) {

        Zivotinje zivotinjeIme = mZivotinje.get(position);

        // Set item views based on the data model
        TextView textView = viewHolder.nameTextView;
        textView.setText(zivotinjeIme.getmAnimal_name());

        ImageView slika_source = viewHolder.imageView;
        slika_source.setImageResource(zivotinjeIme.getmAnimal_slika());

    }

    @Override
    public int getItemCount() {
        return mZivotinje.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public ImageView imageView;
        public TextView nameTextView;

        public ViewHolder(final View itemView) {
            super(itemView);

            nameTextView = (TextView) itemView.findViewById(R.id.zivotinjaIme_id);
            imageView = (ImageView) itemView.findViewById(R.id.slika_id);

            //It works when i play for each item sound but how to play specific sound for each animal
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MediaPlayer mediaPlayer = MediaPlayer.create(v.getContext(), R.raw.clock);
                    mediaPlayer.start();
                }
            });

        }
    }

    private List<Zivotinje> mZivotinje;

    public ZivotinjeAdapter(List<Zivotinje> animals) {
        mZivotinje = animals;
    }
}

A:

Refer the link https://gist.github.com/grantland/cd70814fe4ac369e3e92
you can refer to the item click event and how to get the item on click  event
please refer the code below. i have made the changes
public class ZivotinjeAdapter extends RecyclerView.Adapter<ZivotinjeAdapter.ViewHolder> {

    @Override
    public ZivotinjeAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        // Inflate the custom layout
        View contactView = inflater.inflate(R.layout.item_zivotinje, parent, false);

        // Return a new holder instance
        ViewHolder viewHolder = new ViewHolder(contactView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ZivotinjeAdapter.ViewHolder viewHolder, int position) {

        Zivotinje zivotinjeIme = mZivotinje.get(position);

        // Set item views based on the data model
        TextView textView = viewHolder.nameTextView;
        textView.setText(zivotinjeIme.getmAnimal_name());

        ImageView slika_source = viewHolder.imageView;
        slika_source.setImageResource(zivotinjeIme.getmAnimal_slika());

       viewHolder.setItem(mZivotinje[position]);

    }

    @Override
    public int getItemCount() {
        return mZivotinje.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public ImageView imageView;
        public TextView nameTextView;
        private Zivotinje mItem;

        public ViewHolder(final View itemView) {
            super(itemView);

            nameTextView = (TextView) itemView.findViewById(R.id.zivotinjaIme_id);
            imageView = (ImageView) itemView.findViewById(R.id.slika_id);

 public void setItem(Zivotinje item) {
            mItem = item;

        }

            //It works when i play for each item sound but how to play specific sound for each animal
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                      // here you will get mItem and from that you can get the sound
                    MediaPlayer mediaPlayer = MediaPlayer.create(v.getContext(), R.raw.clock);
                    mediaPlayer.start();
                }
            });

        }
    }

    private List<Zivotinje> mZivotinje;

    public ZivotinjeAdapter(List<Zivotinje> animals) {
        mZivotinje = animals;
    }
}


Q:

What term means "to imagine one is someone else"?

I am looking for a professional term, used to describe a situation in which a person imagines that they are someone else. E.g., someone playing a first-person game will imagine that they are within the game, and "super-impose" their personality onto that character. Or, a child might imagine they are a superhero from their favorite story and consider what they would do with the superhero's abilities.
The term "role-play" is related, but not precisely what I am looking for. "Role-play" seems to emphasize the "playing" or "acting" aspect. I want a term that just means, "imagining you are someone else".

A:

Impersonate:
to assume the character or appearance of; pretend to be; to act or play the part of; (Archaic.) to represent in personal or bodily form; personify.
Less common is
Personate:
to act or portray; to assume the character or appearance of; personify.
Impersonate is often used in a negative sense where deception is involved, but this definition shows that personate can be used the same way in legal terms.
UPDATE
Another word that might come across is immersion. The linked article is somewhat convoluted (which is no surprise given that it is posted under the heading "The Gaming Philosopher"), but the general meaning is here:

Fictional identification with a character (immersion) is helped by mechanics that give total authorship over the character's beliefs, desires, decisions and so forth to one player.

So a person having an immersion experience has total control over the traits of the character they are imagining or pretending to be.
UPDATE 2
I have come across another term that is more about one's state of mind (imagination) rather than ones actions (role-playing).
Escapism

The avoidance of reality by absorption of the mind in entertainment or
  in an imaginative situation, activity, etc.

Escapism is more a state-of-mind than an action, as it attests to the mental state that may drive one to actually escape their current circumstances. It begins with the visualization of alternative conditions. These conditions might be the environment (a vacation escape usually begins with the visualization of that other place), but one can also turn to an alternative identity.
From this article on the subject, the writer discusses escapism and identity in both positive and (clinically) negative terms. Here is an excerpt:

From a psychology perspective, Baumeister (1991) commented that
  individuals may be trying to escape their current ideas of “self”. He
  also suggested that escape may be temporarily achieved by “shrinking”
  down the self to its bare minimum. … The feeling of flow experience
  has been described as an enjoyable and focused concentration in which
  one experiences a loss of self-consciousness (Csikszentmihalyi, 1990).
  Hence, being in flow means temporarily escaping one’s ideas of self.
  From a psychology perspective, Baumeister (1991) commented that
  individuals may be trying to escape their current ideas of “self”. He
  also suggested that escape may be temporarily achieved by “shrinking”
  down the self to its bare minimum. … being in flow means temporarily
  escaping one’s ideas of self.

It’s not a great leap to say that imagining that one is someone else is a form of escapism. This would be the case whether it's as a short-term entertaining diversion or as a short- or long-term means to avoid reality in one's personal life.
Since escapism covers more than imagining about one's identity, I suggest a phrase such as identity escapism might meet your needs.

A:

This can be described as role-projection.  I.e. "imagining oneself in the role of another".
This usage isn't common, but it exists in the psychology literature.  E.g.:

Hirschman (1983) and others (d'Astous & Deshenes 2005) posit that
  certain traits can influence participation in fantasy-related consumption behaviours,
  including role-projection and escapism
  (i.e., to get away from one's everyday life)
  or other activities involving visualization.
  Specifically, an individual's preference for using imagination,
  can predict a tendency to engage in a certain types of fantasy,
  including both role-projection and escapism.

link

Imaginal Responses mainly refer to role projection and escapism.

link

A:

I don't see why Roleplay isn't considered valid here...but if you are looking for another term...
"Acting" or "to act" describes how one can pretend to be another person, and does not necessarily have to mean in media or otherwise.
The word "avatar" describes such a person that one uses to act as another or as a representation of themselves, but doesn't act as a verb.
"Impersonate" can be used if you are acting like a specific person, though not if they are an imaginary person such as a made-up superhero, or if you are acting through them like in a video game.
If you're looking for another hyphenated term, "to act something out" describes the way in which one portrays a certain personality, activity, or other imagined thing.
Hopefully one of these are what you are looking for.


Q:

How do I break an arbitrary TCP/IP connection on Linux?

Is there any command that can be used to break an existing TCP/IP connection from some program?
Is there anything in a TCP connection the OS is aware of, or do the OS only see TCP transfer on local sockets and doensn't know which request is served to which socket?
For example, if Firefox sends a request to some server's port 80 and is waiting for the answer. Is it possible then to find Firefox listening port and trick Firefox into showing ERR_CONNECTION_REFUSED or something similar.
I would like a solution that does not prevent the data flow and lets the application handle this situation in its way, but rather close the socket or the TCP/IP connection (which should be possible as the socket is something the OS is responsible for I think? Is the connection also a OS property or just something the application does?) so the application would react immediately.

A:

Use tcpkill.


Q:

Python Square Root Calculator Error

I wanted to make a simple square root calculator.
num = input('Enter a number and hit enter: ')

if len(num) > 0 and num.isdigit():
    new = (num**0.5)
    print(new)
else:
    print('You did not enter a valid number.')

It doesn't seem as if I have done anything wrong, however, when I attempt to run the program and after I have input a number, I am confronted with the following error message:
Traceback (most recent call last):
File "/Users/username/Documents/Coding/squareroot.py", line 4, in <module>
new = (num**0.5)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'float'

Process finished with exit code 1

A:

You can use this solution. Here try and catch is capable of handling all kinds of input. So your program will never fail. And since the input is being converted to float. You won't face any type related error.
try:
    num = float(input('Enter a positive number and hit enter: '))
    if num >= 0:
        new = (num**0.5)
    print(new)

except:
    print('You did not enter a valid number.')


Q:

Show that $\tau _f$ \ $\tau_{st}$ is uncountable.

Consider $\mathbb R $ with the standard topology $\tau _{st}$. Suppose $\tau _ f$ is a topology on $\mathbb R $ such that $\tau _{st} \subset \tau_f$ (and not equal). Show that $\tau _f$ \ $\tau_{st}$ is uncountable.
Approach: Take $V \in \tau_f$ \ $\tau_{st}$. Then $V$ cannot be written as the union of open intervals $(a,b)$ in $\mathbb R $. What's the next step?? Can someone give me a hint? I have to make uncountable new open sets with the intervals $(a,b)$ and V, I think.

A:

Take $V \in \tau_f \setminus \tau_{st}$. Then, note that there must be some interval $I = (a, a+1)$, where $a \in \mathbb R$, such that $V \cap I \notin \tau_{st}$, because you can check whether $V$ is an open set "locally". Yet, $V \cap I \in \tau_f$, because $I \in \tau_f$.
Then, for each $b > a + 1$, the set
$$
(V \cap I) \cup (b,\infty) \in \tau_f
$$
and this set does not lie in $\tau_{st}$. This gives $\mathbb R$-many elements in $\tau_f \setminus \tau_{st}$.


Q:

Select text of QLineEdit on focus

I have created a dialog using QtDesigner. There is a QLineEdit object in the dialog with some default content. When the dialog initializes and the focus goes to the QLineEdit, I want the default content to be auto selected, so once the user start writing, the previous content will be overwritten.
EDIT:
In constructor:
dialog->accept();

and
connect( dialog, SIGNAL(accepted()), QlineObj, SLOT( selectAll() ) );

A:

This is an older question, but nevertheless, I ended up here searching for a solution this exact problem. It can be solved in the following way:
Create a class derived from QLineEdit and override the focusInEvent in the header:
virtual void focusInEvent(QFocusEvent *event) override;

Then implement it like so:
void MyLineEdit::focusInEvent(QFocusEvent *event)
{
    // First let the base class process the event
    QLineEdit::focusInEvent(event);
    // Then select the text by a single shot timer, so that everything will
    // be processed before (calling selectAll() directly won't work)
    QTimer::singleShot(0, this, &QLineEdit::selectAll);
}

Just in case anybody else wonders how this can be done ;-)

A:

Call
lineEdit->selectAll();

after you set the default text. (In the dialog constructor, perhaps.)

A:

There is a simpler method to get almost the same behaviour, which is to set the default content using setPlaceholderText() instead of setText(). This will show the default content grayed out and as soon as the QLineEdit gains focus, it will disappear.


Q:

duplicity list-current-files doesn't ask for password

I use duplicity to create symmetrically encrypted backups to some server space I get from my ISP. When creating the backups I of course set a password and when I want to restore my files, duplicity asks for that password.
What I don't understand is that when I want to see which files are backed up and I run
duplicity list-current-files ftp://user@host/BACKUP

duplicity doesn't ask for the password, but just gives my the file list.
However, when I look at the files that are in that remote location, they all end in .gpg and thus seem to be encrypted. When I download one of those files and want to open them with tar tvf it fails. I can however decrypt the file with gpg and then look at it with tar.
Why doesn't duplicity list-current-files ask for the password? Couldn't this be considered a weakness?
EDIT:
I did some more testing and it seems that duplicity asks me for the password only the first time I try to list-current-files
I downloaded the archive/backup files created by duplicity on the remote server to my local machine. When I ran duplicity list-current-files file:///path/to/directory, it asked for the password. When I ran the command again, it didn't ask.
When restoring the files duplicity always asks for the password.
I did the same with a newly created (local) backup and the result was the same.

A:

It turns out duplicity keeps data around in ~/.cache/duplicity. These files are unencrypted manifest and signature files, but not the actual data.
I found something about this in the man page, but it only became clear to me after some further testing and looking at the cache. (See my EDIT of the question.)
So, it seems to me this doesn't represent a weakness like I originally thought.


Q:

Gallery and fullscreen ImageView, problem in putting them together

I will try to be as clear as possible.
Here What I am trying to do
An Image Viewer, where Image would be display as big as they can on the device screen.
For this purspose and for a better user experience, I thought of a Gallery.
Untill there everything is OK!
The problem
The problem is that in the function getView of my Adapter, it uses only the Gallery.LayoutParams of the first Image I have in my Gallery. Which means that if the first picture is a landscape and the second one a portrait the second one will be display as landscape, with the same dimension as the first one. I do reset the Gallery.LayoutParams but it does not matter, it still have the LayoutParams of the first ImageView.
The code
public View getView(int position, View convertView, ViewGroup parent) {

        ImageView im = new ImageView(mContext);

        Bitmap bm = BitmapFactory.decodeByteArray(gallery.get(position).mContent, 0, gallery.get(position).mContent.length);
        im.setImageBitmap(bm);

        int width = 0;
        int height = 0;

        if (bm.getHeight() < bm.getWidth()) {
            width = getWindowManager().getDefaultDisplay().getWidth();
            height = bm.getHeight() * width / bm.getWidth();
        }
        else {
            height = getWindowManager().getDefaultDisplay().getHeight();
            width = bm.getWidth() * height/ bm.getHeight();
                }

        Gallery.LayoutParams lp = new Gallery.LayoutParams(width, height);
        im.setLayoutParams(lp);

        return im;
}

If any of you see why I would be really please to know the answer,

A:

Gallery forces all children to have the same size. Also, you are creating a new View every time getView() is called and it's a terrible idea. You should use the convertView when it's not null. There's currently a missing feature in Gallery so convertView is always null, but to benefit from it in a future version of Android, use the convertView anyway. It's also a good practice that you must apply in every Adapter you write.


Q:

ReDim in Subroutine VBA

Sub testCov()
    Rng2 = Sheets("20 Asset Model").Range("b3:f48")
    Dim covMatrix() As Variant
    ReDim covMatrix(1 To Rng2.Columns.Count, 1 To Rng2.Columns.Count)
    Call constructCovMatrix(Rng2, covMatrix)
    MsgBox (covMatrix)
End Sub

Sub constructCovMatrix(rng, ByRef covMatrix)
    '@rng The Range of the return series.

    Dim i As Integer
    Dim j As Integer
    For i = 1 To rng.Columns.Count
        For j = 1 To rng.Columns.Count
            covMatrix(i, j) = Application.WorksheetFunction.Covar(rng.Columns(i), rng.Columns(j))
        Next
    Next
End Sub

The code stops at the line ReDim, saying object missing. Why is this? Thanks

A:

Try this to set your range as a range object be declaring it: (comments in-line)
Sub testCov()

    Dim Rng2 As Range '- Declare variable
    Set Rng2 = Sheets("20 Asset Model").Range("b3:f48") '-Set range
    Dim covMatrix() As Variant
    ReDim covMatrix(1 To Rng2.Columns.Count, 1 To Rng2.Columns.Count)
    Call constructCovMatrix(Rng2, covMatrix)
    MsgBox (covMatrix)

    Set Rng2 = Nothing '- Cleanup anytime 'Set' is used
End Sub

Note:
You may want to go to the VBA editor's setting sand click tools > options > Declare varible decleration > checked
This will ensure that you need to declare all your variables.
As is, the above code did not declare Rng2 as a range. So when Excel first sees the name Rng2 it creates a Variant type variable and sets it equal to the range of the sheet in the first line. Excel notices that Sheets("20 Asset Model").Range("b3:f48") is an array of cells, and it treats the variant Rng2 as an array type variable going forward for the rest of your code. Assuming that you want to use the variable named Rng2 as a range, we can declare it as such and use the Set command to assign it.
When you don't declare your variable types its easy for a mix-up like this to happen.


Q:

Why am I getting a reading of 119.7 volts neutral to ground?

el. contractor has left (residential house) - checking the branch outlets:
Hot to neutral: 118.8V // Hot to Ground: 0V // Neutral to Ground: 119.2V??
How come? should I be getting such voltage perhaps on Hot to Ground and Neutral to Ground some fractions, perhaps 2V or less?? Briefly looking into the breaker panel box - blacks wire (hot) to breaker - white (neutral) to side conn.- green (ground), above white wire connectors to a similar connector?
Did they switch somehow hot for neutral? Maybe I mistakenly believe that the right hand opening in in the outlet is neutral? (although black wire goes there?

A:

Hot and Neutral reversed - as the "hot to ground = 0V" reading confirms.
The Brass-colored screw gets the black/hot wire, the Silver-colored screw gets the white/neutral wire, and the wider blade looking at the outlet is neutral. That's left if the ground is down, right if the ground is up.
The Green-colored screw gets the green/bare ground wire.
A $5 or so plug in outlet tester (might as well get the GFCI-Testing version) will confirm these things easily without needing three tests and without potential for error in what is supposed to be what.


Q:

C# SSL соединение xNet, WebRequest

Доброго времени суток, помогите решить проблему : при попытке сделать запрос на сайт sscasino.online дает ошибку xNet.HttpException" в xNet.dll ("Не удалось установить SSL-соединение с HTTP-сервером 'sscasino.online'.") xNet.HttpException (xNET)
и
System.Net.WebException" в System.dll ("Базовое соединение закрыто: Непредвиденная ошибка при передаче.") System.Net.WebException (WebRequest)
request.UserAgent = useragent;
request.IgnoreProtocolErrors = true;
request.SslCertificateValidatorCallback += (sender, certificate, chain, sslPolicyErrors) => true;

var result = request.Get(link);

и
  WebRequest req = WebRequest.Create(Url);
  WebResponse resp = req.GetResponse();
  Stream stream = resp.GetResponseStream();
  StreamReader sr = new StreamReader(stream);
  string Out = sr.ReadToEnd();
  sr.Close();

При этом, если включить http debbuger pro, то запросы идут нормально. Тестил на
 нескольких машинах

A:

xNet не будет работать из коробки:

xNet основан на SslStream и использует протокол по умолчанию: sslStream.AuthenticateAsClient(address.Host); xNet GitHub
протокол SslStreamу должен быть уcтановлен так:
sslStream.AuthenticateAsClient(address.Host, null, SslProtocols.Tls12, true); MSDN

Два варианта:

внести вклад в GitHub xNet с изменением выше
cкомпилировать xNet локально с изменением выше

ТАКЖЕ:
Можно попытаться установить протокол по умолчанию где-нибудь вначале (Global.asax -> Startup если есть):
System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
или
ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;
Я не пытался проверить, работает ли этот последний вариант


Q:

C++ Code that manipulates CSV file outputs correctly via Sublime Text Command Palette...but not in Terminal

For my latest lab I was given a fairly basic assignment - take a CSV file with population data and output various details, like the country with the largest population. For the sake of brevity, I've included a truncated version of my code below:
#include <iostream>
#include <fstream>
using namespace std;

  struct Country {
    string name;
    double pop1950;
    double pop1970;
    double pop1990;
    double pop2010;
    double pop2015;
  };

  struct World {
    int numCountries;
    Country countries[229]; // plugged this value with the number of countries from the CSV file.
  } myWorld;

  int main()
  {
     ifstream csvStream;
     csvStream.open ("population.csv");

        double vpop1950;
        double vpop1970;
        double vpop1990;
        double vpop2010;
        double vpop2015;
        string conName;

        int counter = 0;

       while (csvStream >> vpop1950 >> vpop1970 >> vpop1990 >> vpop2010 >> vpop2015)
       {
        getline(csvStream, conName);
        // instantiate a country structure per line.

        myWorld.countries[counter].name = conName;
        myWorld.countries[counter].pop1950 = vpop1950;
        myWorld.countries[counter].pop1970 = vpop1970;
        myWorld.countries[counter].pop1990 = vpop1990;
        myWorld.countries[counter].pop2010 = vpop2010;
        myWorld.countries[counter].pop2015 = vpop2015;
        counter++;

        // cout << conName << endl;
       }

       // For task 2, where are going to get the top 3 countries. Let's start with the top country, and repeat the loop below 2 more times.

       // Figure out the biggest population.
       double placeVal = myWorld.countries[0].pop2015; // use this to compare and store the top 100
       string topCon = " ";

       for (int i = 0; i < 229; i++)
       {
        if (placeVal < myWorld.countries[i].pop2015)
        {
            placeVal = myWorld.countries[i].pop2015;
            topCon = myWorld.countries[i].name;
        }
       }

       cout << "The largest country is" << topCon << " which had " << placeVal * 1000 << " people in 2015." << endl; // Multiplied by 1000 as per lab instructions.

     return 0;

     csvStream.close();

  }

When I type Command+Shift+B in sublime text and have the file compile and execute, I get this output:
The largest country is China
 which had 1.37605e+09 people in 2015.
[Finished in 0.3s]

Execute that same executable in terminal, and I get the following (on both mac and ubuntu):
The largest country is  which had 0 people in 2015.

My actual code is a fair bit longer, and I perform various other calculations in that original version of my program, but the same bug persists - the output shows in sublime text but not in the actual terminal. Any thoughts?

A:

Your program assumes that population.csv is in the current working directory. If the current directory does not contain that file, then that file won't be able to be read in.
SublimeText most likely sets the current directory when executing your program to the directory where that program is located.
When running commands from a terminal, the executed program inherits the current directory from the terminal. For example, if your program is in ~/src/my_program, but the current directory in the terminal is your home directory, then the current directory for your program will be your home directory, not ~/src/my_program.
If you change the current directory in the terminal to the directory where your program is located, then the file should be read in correctly.


Q:

How to select row values for max(2 columns)

I am working out a query in MS SQL Server. I have my table like this
Table( Level int, Stage int, values varchar)
Level Stage Value
1     1
1     2
1     3
2     1
2     2

I need to find the row having maximum value by level and then by stage. ie., I need to get the result as
Level  Stage
2      2

When I try the below query I get the value 22 and in one column. I need that in 2 distinct columns as specified above.
SELECT MAX(CAST(wfLevel as varchar(2)) + CAST(approvalStage as varchar(2)))
  FROM [AuditReporterDB].[dbo].[RequestHistory]

Can anyone help.

A:

SELECT TOP 1 Level,Stage
FROM tableName
ORDER BY Level Desc,Stage Desc


Q:

Determinant of matrix defined by binomial coefficient

Let $m,n$ be a positive integers and $A=(a_{ij})$ be $n\times n$ matrix defined by $a_{ij}=\binom{m+i}{j}$
(if $m+i<j ,\binom{m+i}{j}=0)$. Find det$A$.
I think det $A= \binom{m+n}{m}$,but I can't prove it.
How to prove (not using combinatorial approach) ?

A:

One can use the Van der Monde identity
$$
\binom{m+I}{K}=\sum_{J=0}^I \binom{I}{J} \binom{m}{K-J}
$$
Putting $i=I+1,j=J+1,k=K+1$ (we need to do this because matrix indices start
from $1$ not $0$) and using $\binom{m+i-1}{k-1}=\frac{k}{m+i}\binom{m+i}{k}$, the above identity becomes
$$
\binom{m+i}{k}=\sum_{j=1}^i (m+i)\binom{i-1}{j-1} \frac{1}{k}\binom{m}{k-j}
$$
This identity tells us that $A=LU$ where $L=(l_{ij})$ is defined by  $l_{ij}=(m+i)\binom{i}{j}$ and $U=(u_{jk})$ is defined by $u_{jk}=\frac{1}{k}\binom{m}{k-j}$. Now $L$ is lower-triangular so $\det(L)=\prod_{t=1}^n l_{tt}=\frac{1}{n!}$. Similarly $U$ is upper-triangular so $\det(U)=\prod_{t=1}^n u_{tt}=(m+1)\ldots (m+n)$, qed.
I admit that this is cheating because the Van der Monde identity is rather combinatorial in nature, but the proof was so simple I couldn't resist. If you insist on a 100% non-combinatorial proof, you can prove the Van der Monde identity by induction.


Q:

Generate a stub or mocking a method in .NET

I am writing a unit test that performs logic as the following:
SomeObject obj1 = new SomeObject();
obj1.SomeMethod(args);

Inside SomeMethod:
public void SomeMethod(*Some Args*){
    AnotherObject obj2 = new AnotherObject();
    Obj2.OtherMethod();
}

In my testing I dont care about what Obj2.OtherMethod() really does, and I want the testing to overlook it. So I think generating a stub will fix it for me, but I'm not sure how to do it.

A:

Here's one approach.  If you had an interface which AnotherObject implemented (say IAnother, which as a minimum has AnotherMethod as a method), your normal execution path would pass in an instance of AnotherObject to SomeMethod.
Then for testing, you could pass a mock object which implements the IAnother interface - either by using a mock framework or coding one yourself.
So you'd have:
Public void SomeMethod(IAnother anotherObject)
{
  anotherObbject.OtherMethod();
}

and
Public class MyMock : IAnother...

for testing -
IAnother another = new MyMock();
..SomeMethod(myMock)

but in the real code
IAnother = new AnotherObject()...

you get the idea.


Q:

Limit number of events per time period

I need to cap the number of events n permitted during a time period deltaT. Any approach I can think of, space is O(m), where m is the maximum number of eventrequests sent per deltaT, or O(deltaT/r), where r is an acceptable resolution.
Edit: deltaT is a sliding time window relative to the timestamp.
For instance: Keep a circular buffer of event timestamps. On event crop all earlier timestamps than t-deltaT. Deny event if the number of timestamps exceeds n. Add timestamp to the buffer.
Or, init a circular bucket buffer of integers of size deltaT/r indexed by time relative to the current with resolution r. Maintain pointer i. On event, increment i by time since last event divided by r. Zero the buffer between the original i and the new one. Increment at i. Deny, if the sum of the bugger exceeds n.
What's a better way?

I just implemented my second suggestion above in c# with a fixed deltaT of 1 s and a fixed resolution of 10 ms.
public class EventCap
{
    private const int RES = 10; //resolution in ms

    private int _max;
    private readonly int[] _tsBuffer;
    private int p = 0;
    private DateTime? _lastEventTime;
    private int _length = 1000 / RES;

    public EventCap(int max)
    {
        _max = max;

        _tsBuffer = new int[_length];
    }

    public EventCap()
    {
    }

    public bool Request(DateTime timeStamp)
    {
        if (_max <= 0)
            return true;

        if (!_lastEventTime.HasValue)
        {
            _lastEventTime = timeStamp;
            _tsBuffer[0] = 1;
            return true;
        }

        //A
        //Mutually redundant with B
        if (timeStamp - _lastEventTime >= TimeSpan.FromSeconds(1))
        {
            _lastEventTime = timeStamp;
            Array.Clear(_tsBuffer, 0, _length);
            _tsBuffer[0] = 1;
            p = 0;
            return true;
        }

        var newP = (timeStamp - _lastEventTime.Value).Milliseconds / RES + p;

        if (newP < _length)
            Array.Clear(_tsBuffer, p + 1, newP - p);

        else if (newP > p + _length)
        {
            //B
            //Mutually redundant with A
            Array.Clear(_tsBuffer, 0, _length);
        }
        else
        {
            Array.Clear(_tsBuffer, p + 1, _length - p - 1);
            Array.Clear(_tsBuffer, 0, newP % _length);
        }

        p = newP % _length;
        _tsBuffer[p]++;
        _lastEventTime = timeStamp;

        var sum = _tsBuffer.Sum();

        return sum <= 10;
    }
}

A:

What about having these variables: num_events_allowed, time_before, time_now, time_passed
At init time you will do: time_before = system.timer(), num_events_allowed = n
When an event is received you do the following:
  time_now = system.timer()
  time_passed = time_now - time_before
  time_before = time_now

  num_events_allowed += time_passed * (n / deltaT);

  if num_events_allowed > n
      num_events_allowed = n

  if num_events_allowed >= 1
      let event through, num_events_allowed -= 1
  else
      ignore event

Whats nice about this algorithm is the num_events_allowed is actually incremented by the time that has passed since the last event and the rate of which events can be received, that way you get an incrementation of the number of events you can send per that time_passed in order to stay in the limit of n. So if you get an event too soon, you will increment it by less than 1, if its after too much time you will increment it by more than one. Of course if the event goes through you decrement the allowance by 1 as you just got an event. If the allowance passes the max events which is n , you return it back to n as you cant allow more than n in any time phase. If the allowance is less than 1, you cant send a whole event, dont let it through!
This is the leaky bucket algorithm: https://en.wikipedia.org/wiki/Leaky_bucket

A:

One way to keep the sliding window and still have it O(1) + very small O(n) for each incoming request is to make a suitable sized array of ints and keep it as a circular buffer and discretize incoming requests (the requests as integrated as with the sampled levels as in a A/D-converter, or as a histogram if you are a statistican) and keep track of the sum of the circular buffer, like this
assumptions:
"there can be no more than 1000 request per minute" and
"we discretize on every second"

int[] buffer = new zeroed int-array with 60 zeroes
int request-integrator = 0 (transactional)
int discretizer-integrator = 0 (transactional)

for each request:
    check if request-integrator < 1000 then
         // the following incs could be placed outside
         // the if statement for saturation on to many
         // requests (punishment)
         request-integrator++                     // important
         discretizer-integrator++
         proceed with request

once every second:                    // in a transactional memory transaction, for God's saké
    buffer-index++
    if (buffer-index = 60) then buffer-index=0    // for that circular buffer feeling!
    request-integrator -= buffer[buffer-index]    // clean for things happening one minute ago
    buffer[buffer-index] = discretizer-integrator // save this times value
    discretizer-integrator = 0                    // resetting for next sampling period

Note that the increase of the request-integrator "could" be done just once every second, but that leaves a hole open for saturating it with 1000 requests or worse in one second about once every minute depending on punishment behaviour.


Q:

How can I indicate result ambiguity with Resharper CodeAnnotation attributes?

Using Resharper's code-annotation attributes, I'm trying to write a ContractAnnotation attribute for a method that will always return null if the input is null, but will return either null or a value if the input is not null. Something like:
[ContractAnnotation("null => null; notnull => null||notnull")]

I would just write this on its own:
[ContractAnnotation("null => null")]

Except that according to Contract Annotations in ReSharper 7, this would be automatically complemented with something that is invalid:

null => null omits the parameter name in cases there is only one parameter. Basically, null => null means that if the parameter has the value null, the method return value is also null. Note also that this annotation is automatically complemented with notnull => notnull.

How might I write the ContractAnnotation attribute to indicate that it cannot be certain what the return value is when the input is notnull?
Or alternatively, how can I stop it from automatically complementing my null => null annotation with notnull => notnull

Bonus question:
How could I write something like the following:
[ContractAnnotation("null => true; notnull => true||false")]

Or in that case, would this be sufficient, since it is not automatically complemented with the inverse?
[ContractAnnotation("null => true")]

A:

You could use canbenull:
[ContractAnnotation("null => null; notnull => canbenull")]

The full grammar is:
FDT      ::= FDTRow [;FDTRow]*
FDTRow   ::= Input => Output | Output <= Input
Input    ::= ParameterName: Value [, Input]*
Output   ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}
Value    ::= true | false | null | notnull | canbenull

As for the bonus question, [ContractAnnotation("null => true")] should be sufficient. Saying that a bool-returning function can return true or false is redundant, as it can't possibly return anything else.


Q:

Questions about bikes and astronomy

Where can I ask questions about these two topics:

Motorbikes [should I ask it on Bicycles SE?]
Astronomy

A:

You seem to mean "motorcycles". In that case there was a proposal which has been closed. It never seems to have come out of the commitment phase.  However, it's been reopened as Motorcycling to give that community a second chance.
However, as suggested by @random, the Mechanics SE seems to house some questions tagged "motorcycle". So perhaps have a look there.
The bicycles SE is not on-topic for questions about motorcycles it seems.
A proposal and beta for an Astronomy SE didn't make it. It was closed in public beta. It seems the number of visits and questions per day was not sufficient for it to survive. As it says on that page, you can download the dump here And it has been merged into the Physics SE, so perhaps you can try your luck there. I don't participate though, so check the faq first.


Q:

Adding a leading zero to some values in column in MySQL

I have a CSV file sent to me in CSV. The field of interest is 8 digits. Some of those started with a 0. The field was sent numeric. So, I now have dropped some leading zeros.
I already converted the field to varchar. I now need to do this:
I have this now:
12345678
1234567

I need to have this:
12345678
01234567

A:

Change the field back to numeric and use ZEROFILL to keep the zeros
or
use LPAD()
SELECT LPAD('1234567', 8, '0');

A:

Possibly:
select lpad(column, 8, 0) from table;

Edited in response to question from mylesg, in comments below:

ok, seems to make the change on the query- but how do I make it stick (change it) permanently in the table? I tried an UPDATE instead of SELECT

I'm assuming that you used a query similar to:
UPDATE table SET columnName=lpad(nums,8,0);

If that was successful, but the table's values are still without leading-zeroes, then I'd suggest you probably set the column as a numeric type? If that's the case then you'd need to alter the table so that the column is of a text/varchar() type in order to preserve the leading zeroes:
First:
ALTER TABLE `table` CHANGE `numberColumn` `numberColumn` CHAR(8);

Second, run the update:
UPDATE table SET `numberColumn`=LPAD(`numberColum`, 8, '0');

This should, then, preserve the leading-zeroes; the down-side is that the column is no longer strictly of a numeric type; so you may have to enforce more strict validation (depending on your use-case) to ensure that non-numerals aren't entered into that column.
References:

lpad().

A:

I had similar problem when importing phone number data from excel to mysql database. So a simple trick without the need to identify the length of the phone number (because the length of the phone numbers varied in my data):
UPDATE table SET phone_num = concat('0', phone_num)

I just concated 0 in front of the phone_num.


Q:

Find UTC time zone using offset

I find rawoffset from google API(https://maps.googleapis.com/maps/api/timezone/json?location). Now i want to find UTC timezone not UTC time.
For example: I have New York City rawoffset and Wana to result UTC-5:00.
It is possible in php or javacript?

A:

You can use moment-timezone. Then you can use like this to get timezone
moment.tz([2012, 0], 'America/Denver').format('Z z');
It will results -> -07:00 MST


Q:

Gmsh exporting wrong mesh DATA

so hopefully I'll be using gmsh to make meshes out of 2-D cross sections with o thickness. I tried to make a structured mesh with quad elements of a rectangular cross-section, but when I checked the .mesh file to see if it had the correct number of elements and nodes, it hadn't and I can't seem to figure out why...
I'll post the .geo and .mesh files here:
.geo file:
`// Gmsh project created on Mon Apr 09 15:44:32 2018
Point(1) = {0, 0, 0, 1};
Point(2) = {6, 0, 0, 1};
Point(3) = {6, 2, 0, 1};
Point(4) = {0, 2, 0, 1};
Line(1) = {1, 2};
Line(2) = {2, 3};
Line(3) = {3, 4};
Line(4) = {4, 1};
Physical Line("left") = {4};
Physical Line("right") = {2};
Physical Line("top") = {3};
Physical Line("bottom") = {1};
Line Loop(1) = {4, 1, 2, 3};
Plane Surface(1) = {1};
Transfinite Surface {1} = {1, 2, 3, 4};
Transfinite Line {4, 2} = 3 Using Progression 1;
Transfinite Line {1, 3} = 7 Using Progression 1;
Recombine Surface {1};

.mesh file:
$MeshFormat
2.2 0 8
$EndMeshFormat
$PhysicalNames
4
1 1 "left"
1 2 "right"
1 3 "top"
1 4 "bottom"
$EndPhysicalNames
$Nodes
16
1 0 0 0
2 6 0 0
3 6 2 0
4 0 2 0
5 0.999999999995645 0 0
6 1.99999999999205 0 0
7 2.999999999988572 0 0
8 3.999999999992324 0 0
9 4.999999999996161 0 0
10 6 0.9999999999973842 0
11 5.000000000006331 2 0
12 4.000000000003875 2 0
13 3.000000000008324 2 0
14 2.000000000005607 2 0
15 1.000000000002804 2 0
16 0 1.000000000004119 0
$EndNodes
$Elements
16
1 1 2 4 1 1 5
2 1 2 4 1 5 6
3 1 2 4 1 6 7
4 1 2 4 1 7 8
5 1 2 4 1 8 9
6 1 2 4 1 9 2
7 1 2 2 2 2 10
8 1 2 2 2 10 3
9 1 2 3 3 3 11
10 1 2 3 3 11 12
11 1 2 3 3 12 13
12 1 2 3 3 13 14
13 1 2 3 3 14 15
14 1 2 3 3 15 4
15 1 2 1 4 4 16
16 1 2 1 4 16 1
$EndElements

`
I was supposed to get 12 elements and 21 nodes, but I'm getting 16 elements and 16 nodes... Would be really grateful if anyone can help me with this.
Thanks in advance!
PS: I just need a quad-only mesh generator, if you know any open source one besides gmsh let me know!

A:

You have specified the wrong things to be Physical. If you just want to obtain 2-D elements, there is no need to specify the lines to be physical. However, you certainly need to specify your surface to be physical.
Also, you may want to specify the #points in the structured mesh for transfinite lines before announcing the Surface to be transfinite.
Please, see the corrected code attached that produces exactly 12 2-D elements and 21 nodes.
Point(1) = {0, 0, 0, 1};
Point(2) = {6, 0, 0, 1};
Point(3) = {6, 2, 0, 1};
Point(4) = {0, 2, 0, 1};
Line(1) = {1, 2};
Line(2) = {2, 3};
Line(3) = {3, 4};
Line(4) = {4, 1};
Line Loop(1) = {4, 1, 2, 3};
Plane Surface(1) = {1};
Transfinite Line {4, 2} = 3 Using Progression 1;
Transfinite Line {1, 3} = 7 Using Progression 1;
Transfinite Surface {1} = {1, 2, 3, 4};
Recombine Surface {1};
Physical Surface(1) = {1};


Q:

Defining an Inner class member function template with a (non type) enum argument

I'm having difficulty defining and specializing a member function update() of an inner class Outer<T1>::Inner that is templated on a non-type (enum) argument.
#include <cstdlib>

template<typename T1>
struct Outer
{
    struct Inner
    {
        enum Type{ A , B , C };

        template<Type T2>
        void update();
    };
};

// Definition
template<typename T1>
template<Outer<T1>::Inner::Type T2>
void Outer<T1>::Inner::update()
{
}

// Specialization
template<typename T1>
template<Outer<T1>::Inner::A >
void Outer<T1>::Inner::update()
{
}

int main()
{
    return EXIT_SUCCESS;
}

I'm getting the following error message in GCC 4.5.3
prog.cpp:17:28: error: ‘Outer::Inner::Type’ is not a type
prog.cpp:18:6: error: prototype for ‘void Outer<T1>::Inner::update()’ does not match any in class ‘Outer<T1>::Inner’
prog.cpp:11:15: error: candidate is: template<class T1> template<Outer<T1>::Inner::Type T2> void Outer<T1>::Inner::update()
prog.cpp:24:28: error: ‘Outer::Inner::A’ is not a type
prog.cpp:25:6: error: prototype for ‘void Outer<T1>::Inner::update()’ does not match any in class ‘Outer<T1>::Inner’
prog.cpp:11:15: error: candidate is: template<class T1> template<Outer<T1>::Inner::Type T2> void Outer<T1>::Inner::update()

BTW, unlike GCC, Visual Studio 2008 is unable to compile the following
template<typename T1>
struct Outer
{
    struct Inner
    {
        enum Type{ A , B , C };

        template<Type T2>
        struct Deep;
    };
};

template<typename T1>
template<typename Outer<T1>::Inner::Type T2>
struct Outer<T1>::Inner::Deep
{
};

A:

First of all, you're missing a typename before Outer<T1>::Inner::Type. You have to have it, even in a template type list, because Type is a dependent type.
Secondly, your specialisation syntax is wrong (the type goes in <> after the function name before the parentheses, not in the template<>), but even if it was correct, it would not be legal. You have to specialise the outer template Outer before you can fully specialise update, according to an unfortunate rule regarding explicit template specialisation.