text:
Q: Instanciar uma classe que herda uma classe interface Tenho uma classe que herda muitas classes interfaces, e quero instanciá-la para usar apenas um método, como devo fazer? È possível fazer sem passar todos os parâmetros necessários?
public class PontoSituacaoService : IPontoSituacaoService,
        IMessageHandler<DespachoCreatedEvento, bool>,
        IMessageHandler<OcorrenciaAssociadaEvento, bool>,
        IMessageHandler<OcorrenciaDesassociadaEvento, bool>,
        IMessageHandler<PartilharOcorrenciaEvento, bool>,
        IMessageHandler<GrupoDespachosCreatedEvento, bool>,
        IMessageHandler<AlteracaoEstadoOcorrencia, bool>,
        IMessageHandler<NotificacaoManualEvento, bool>,
        IMessageHandler<OcorrenciaImportanciaModificadaEvento, bool>,
        IMessageHandler<AtualizarPOSITOcorrencia112, bool>,
        IMessageHandler<DanoHabitacionalCriadoEvento, bool>
{
    private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    private readonly IRepository<PontoSituacao> _pontoSituacaoRepository;
    private readonly IRepository<SumarioPontoSituacao> _sumarioPontoSituacaoRepository;

    private readonly IOcorrenciaService _ocorrenciaService;
    private readonly ILookupService<TipoPontoSituacao> _tipoPontoSituacaoService;
    private readonly IModuloInterfacePortal _moduloInterfacePortal;

    private readonly ILookupService<TemplateNotificacaoSINOP> _templateService;

    private readonly IMessageBus _bus;

    public PontoSituacaoService(IRepository<PontoSituacao> pontoSituacaoRepository,
                IOcorrenciaService ocorrenciaService,
                ILookupService<TipoPontoSituacao> tipoPontoSituacaoService,
                IMessageBus bus,
                IModuloInterfacePortal moduloInterfacePortal,
                IRepository<SumarioPontoSituacao> sumarioPontoSituacaoRepository,
                ILookupService<TemplateNotificacaoSINOP> templateService)
    {
        _pontoSituacaoRepository = pontoSituacaoRepository;
        _sumarioPontoSituacaoRepository = sumarioPontoSituacaoRepository;
        _ocorrenciaService = ocorrenciaService;
        _tipoPontoSituacaoService = tipoPontoSituacaoService;
        _bus = bus;
        _moduloInterfacePortal = moduloInterfacePortal;
        _templateService = templateService;
    }

public ActionConfirmation SaveOrUpdate(PontoSituacao pontoSituacao)
    {
        return SaveOrUpdate(pontoSituacao, true, false);
    }
}

A: Classe e interface são coisas bem distintas, ou é classe ou é interface. Classes e interfaces tem em comum que são tipos, só isso.
A instanciação de uma classe independe das interfaces que elas implementam (note que não usei o termo "herdam" que não é correto). É igual a qualquer caso. Nesse caso o problema é o construtor que exige que objetos sejam instanciados para criar o objeto. Até é necessário por causa das interfaces implementadas, mas isso é colateral.
Após a edição percebe-se uma classe extremamente complexa e que pode-se questionar se precisa disso tudo. Passa a impressão que está pegando algo pronto (tem cara de ser DDD) e que não entende o que está fazendo. Isso é um problema. Em coisas complexas assim precisa um grande domínio de programação, orientação a objeto, arquitetura, etc. Não use metodologias que não domina, não dá certo. Qualquer metodologia, boa ou ruim, só funciona quando a pessoa a domina. Por mais que uma metodologia possa ser maravilhosa, e muitas são mais marketing do que realidade, se não entender completamente como usá-la é pior que usar uma coisa mais básica. E essa parece ser bem complexa, tanto que talvez nem seja vantajosa para seu problema.
Eu até iria dizer que é preciso observar se é necessário implementar tantas interfaces assim nessa classe, ou até mesmo se esse método deveria fazer parte dessa classe. Se ele deve ser usado tão isoladamente assim, ou ele deveria ser estático, ou deveria fazer parte de outra classe. Mas parece que isso é uma questão de arquitetura.
Eu sou crítico à arquiteturas complexas, como essa. Esse é um exemplo muito claro do que eu sempre falo. Para consumir algo muito simples é necessário um código muito complexo. Me desculpe, mas esse código é uma atrocidade. Ele exige tanto para usá-lo que é melhor nem usar e fazer outra coisa, o que mataria o motivo de tê-lo criado.
Pior, pelo que entendi, o grosso desse objeto serve mais de controle da arquitetura do que do domínio do problema, e se for DDD seria irônico.
Sem mudar toda a arquitetura não tenho uma solução melhor, instancie o objeto com tudo o que ele exige e use o método que precisa em seguida. E sim, terá que criar pelo menos 7 objetos de classes que implementam essas interfaces só para consumir um método que talvez nem tenha relação com o que precisa.
Por outro lado pode estar fazendo tudo isso de forma tão errada que o problema esteja em outro lugar ou talvez não deva chamar este método que deseja e sim outra coisa. Pode ser que não deva chamar este método. A arquitetura pode ter essa classe para uso interno e não para seu consumo.
Se eu conhecesse o problema como um todo talvez dese para ajudar mais, mas esse problema resolve-se baixando a complexidade artificial da aplicação.


text:
Q: Regex of validating must contain alphanumerics I want to make a regex that must have atlease one number and one alphabet.
onlyText will not math. But onlyText123 matches.

A: Here you go
^(?=.*[a-zA-Z])(?=.*[\d]).*$

The key is to use a technique called lookaround

A: You can try something like this
String p= "\\w*([a-zA-Z]\\d|\\d[a-zA-Z])\\w*";

System.out.println("1a".matches(p));//true
System.out.println("a1".matches(p));//true
System.out.println("1".matches(p));//false
System.out.println("a".matches(p));//false

([a-zA-Z]\\d|\\d[a-zA-Z]) == letter then number OR number then letter
and before and after it can (but don't have to) be letters and digits (\\w)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is $\{x\in R\mid A \cap Rx=\emptyset\text{ and }A \cap xR=\emptyset\}$ infinite in a ring? Assume  $R$ is a ring and $A\subseteq R$ contains $0$. Let
$$B=\{x\in R\mid A \cap Rx=\emptyset\text{ and }A \cap xR=\emptyset\}$$
Can $B$ be nonempty?
If $B$ is nonempty, is it infinite?

A: Note that $0\in A\cap Rx$ and $0\in A\cap xR$ for all $x\in R$. This is because $$0x=(0+0)x=0x+0x,$$ so $0=0x\in Rx$ for all $x\in R$. Similarly, $0\in xR$ for all $x\in R$. Hence, for any $x\in R$, we have $A\cap Rx\neq\emptyset$ and $A\cap xR\neq\emptyset$, so $x\notin B$. Thus $B$ is empty.
Logically speaking, if $B$ is non-empty (that is, assuming a false statement), then $B$ is infinite by Principle of Explosion. Of course, $B$ is also a baby unicorn, but that's less interesting (or at least less relevant).


text:
Q: How to catch event when user clicks outside of bootstrap modal dialog? Scenario:

*

*I click on a button

*Ajax call is made to the server

*data is returned and modal is shown

Problem:
When user clicks on the close button or the "X" in the corner I catch this event by assigning a class to these two elements and assigning an event to this class.
Code:
$(document).on("click", ".dialogTankClose", function() {
    //some code
})

My problem is that i can't figure out how to catch when the user clicks outside of the dialog or presses "escape".
$(document).on("click", "modalCloseEvent",function(){
// how to catch this?
})

How can I catch this?

A: The Bootstrap modal raises an event when it closes, which you can hook to: hidden.bs.modal. This event fires no matter how the modal is closed. Try this:
$('#bootstrapModal').on("hidden.bs.modal", function() {
    $.automation.worker.bindIntervalEvent("#TanksContent", "/Tank/GetTanks", function () {
        $.automation.tanks.tableInit();
    });
});

You can use a delegated event handler if the modal is dynamically added to the DOM:
$(document).on("hidden.bs.modal", '#bootstrapModal', function() {
    $.automation.worker.bindIntervalEvent("#TanksContent", "/Tank/GetTanks", function () {
        $.automation.tanks.tableInit();
    });
});

More information in the Bootstrap documentation

A: You can use 'hidden.bs.modal' modal method to run custom code while modal is getting unload / hide from document.
$('#your-modal-ID').on('hidden.bs.modal', function (e) {
  console.log("Hey !! I am unloading... ");
});


text:
Q: How to convert string VCard into a vcf file How can I convert this into a vcf file?
BEGIN:VCARD
VERSION:3.0
FN:Nicolas Rizzo
MAIL;TYPE=home:nizzoeh@hotmail.com
END:VCARD

I generated the above VCard by doing this:
j = vobject.vCard()
        o = j.add('fn')
        o.value = rowr.name

        o = j.add('mail')
        o.type_param = "email"
        o.value = rowr.email

        vcard = j.serialize()

A: simply write it into a text file.
Here is a fully working example :
import vobject

from types import SimpleNamespace # for testing
list_person = [SimpleNamespace(name="test1", email="test1@contoso.com"),SimpleNamespace(name="test2", email="test2@contoso.com")]

vcf_file_path = 'rep_tel.vcf'

with open(vcf_file_path , 'w',encoding='utf8') as file_vcard:
    for rowr in list_person:
        vcard = vobject.vCard()
        o = vcard.add('fn')
        o.value = rowr.name

        o = vcard.add('email')
        o.type_param = 'INTERNET'
        o.value = rowr.email

        file_vcard.write(vcard.serialize())


text:
Q: Exception Specification more or less restrictive Based on this

Incidentally, you can do this kind of assignment of a pointer to a
  function as long as the target's exception specification is no more
  restrictive than the source's

class A{};
class B{};
class C{};

void f() throw(A,B,C) {}

void (*pf)() throw(A,B);

int main()
{
    pf = f; // pf is more restrictive than that of f. I expect an error here!
}

The last statement should not pass the compiler. However, I have tried VS2010 and GCC latest version. Neither or them complain about it.
Question> Why?

A: This looks like a bug in GCC and VS2010. Clang won't compile it, and it should not compile according to [except.spec]/5:

... A similar restriction applies to assignment to and initialization of pointers to functions, pointers to member functions, and references to functions: the target entity shall allow at least the exceptions allowed by the source value in the assignment or initialization.

The standard also includes the following example:
class A { /*...*/ };
void (*pf1)(); // no exception specification
void (*pf2)() throw(A);
void f() {
    pf1 = pf2; // OK: pf1 is less restrictive
    pf2 = pf1; // error: pf2 is more restrictive
}

A: It's a long-standing bug in g++: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=12255

The underlying issue is that G++ just ignores exception-specifications on
  non-function declarations.  I think this choice originated in the uncertainty
  about whether or not the exeception-specification would become part of a
  function type rather than remain associated with the declaration.

It wouldn't surprise me if VS was similar in this regard.


text:
Q: Переход к предыдущим фрагментам по нажатию на кнопку "Back" У меня имеется контейнер,в который подгружаются фрагменты. Изначально в контейнер подгружается NavigationFragment - панель с кнопками (категориями),при нажатии на какую -либо из них происходит  переход либо к подкатегориям ,либо к контенту(ChildItemFragment), который содержит категория.
Мне нужно реализовать логику возврата к предыдущей подкатегории при нажатии на программную кнопку "Back" или же к навигационной панели,если категория не имеет подкатегорий.
я пробовал такие варианты :
FragmentManager manager = MainActivity.this.getFragmentManager();
    int count = manager.getBackStackEntryCount();
if (count > 0) manager.popBackStack()
else  .... transaction.replace .....commit  NavigationFragment

но этот подход не работает (при начале транзакции прописывал .addToBackStack(null) )
еще пробовал при создании моего ChildItemFragment передавать из него в MainActivity список с элементами
 list.remove(list.size() - 2);
ChildListFragment fragment = new ChildListFragment();
        Bundle args = new Bundle();
 args.putParcelableArrayList(ChildListFragment.ARG_CHILD_ITEMS, childs);
        fragment.setArguments(args);
        getFragmentManager().beginTransaction()
                .setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right)
                .replace(R.id.fragment_container, fragment)
                .commitAllowingStateLoss();

но в этом случае получается какой-то непонятный костыль,который работает с переменным успехом и иногда бывают вылеты в зависимости от количества подкатегорий.
подскажите,как правильно реализовать возврат к предыдущим экранам в контейнере при нажатии на  программную Back button

A: Если я вас правильно понял, то у вас есть фрагменты в активити, а так же в некоторых из них есть дочерние фрагменты добавляющиеся через getChildFragmentManager() родительского фрагмента. По скольку что вы подразумеваете под "этот подход не работает" вы не уточнили, предположу что у вас откатываются изменения только фрагментов размещенных в активити. Происходит это от того что вы в обработчике кнопки назад проверяете только бэкстек FragmentManager'а активити (getBackStackEntryCount() и popBackStack()), соответственно вам просто нужно проверять и бэкстек дочерних FragmentManager'ов фрагментов.


text:
Q: Getting "{{component}} refers to to a value, but is being used as a type" error when attemping to identify an argument that refers to a Vue Component I have a function that takes as a parameter a Vue Component.
dothings.ts
import App from 'src/app';

export default class DoThings {
  public static fetch(liveApp: App) {
    liveApp.updateMe = 'updated';
  }
}

I would like to pass the App component into the fetch function so I can manipulate its state as a part of the function. The App component looks like this:
app.vue
import Vue from 'vue';
import DoThings from 'dothings';

export default Vue.extend({
  data() {
    return {
      updateMe: '',
    }
  },
  methods: {
    fetch() {
      DoThings.fetch(this);
    }
  },
});

My attempts to refer to the "App" component, exported by app.vue, are failing with the error:
  TS2749: 'App' refers to a value, but is being used as a type here.

with a pointer to the line public static fetch....
What is the proper way to indicate the Type I am expecting to be passed into a function is an exported Vue component?
Particularly, I'm not clear how Typescript can know that Vue maps all values on its data() method returned object to properties of the Vue component itself. Same for methods. I tried using just Vue.Component as the type, but obviously that threw errors about things like updateMe not existing on the type Vue.Component.

A: The solution is to use the typescript typeof operator.
import App from 'src/app';

export default class DoThings {
  public static fetch(liveApp: typeof App) {
    liveApp.updateMe = 'updated';
  }
}


text:
Q: jQuery MULTIPLE TABLES hover and click I have (10+) tables that all have the same format, trying to get page to display the header and make it so when you hover over the head it display they body and when you click that head (or body) it will keep that individual head/body displayed. Also keep other ones that have already been clicked.
Only beginner jQuery-er.
Have put 15+ hours just on this element so it's time to call for help.
Ignore pictures.
Some mess I've created: http://jsfiddle.net/XE6AG/159/
Very similar to this:http://jsfiddle.net/gRSXZ/1/ except I need tbody to be hidden then expanded on hover, stay expanded on click!

One

Two

Three

Four

- Jquery
$(".ActiveTableAwards")
    .hover(function() {
        $(".ActiveTableAwardsHead") .toggleClass('hover') .toggle("fast", function showNext(){

          $(".TextTbody").show("slow", showNext);
          });
});

A: You need to use $(".ActiveTableAwardsHead") instead of $("ActiveTableAwardsHead")

A: $(".ActiveTableAwardsHead").hover(function() {
            $(this).children('tr').toggleClass('hover').show();
                     }
          ).hover(function() {
           $(this).fadeIn();
                      },
           function() {
            $(this).fadeOut();
                      });

$(".TextTbody").children('tr').addClass('hover').click(function(){
          $(this).addClass('hover').fadeOut();
});


text:
Q: addEventListener function doesn't work properly in js I want to add an event listener to a list of objects but when i use the following code it works like this. the function only happens only one time when i run the app ( without clicking on the element) and then it stops working.
js :
             const checkIcons = document.getElementsByClassName("checkIcon");
             var checkIconFunction = function(img){

                console.log(img.src)
                var filename = img.src.replace(/^.*[\\\/]/, '');
                console.log(filename)
                if (filename == "cheack-icon.svg" ){
                    img.src = "../svg/color/cheack-icon-filled.svg";
                }else{
                    img.src = "../svg/color/cheack-icon.svg";
                };

            };
            Array.from(checkIcons).forEach(function(element) {
                element.addEventListener('click', checkIconFunction(element));
            });

html:

Activity:

                        time

                        directory

                        select

                        19 May

                        ali/ali/ali

                        19 May

                        ali/ali/ali

i


text:
Q: PythonAnywhere trying to upload my website I am trying to upload my web-app on PythonAnywhere, but I am not able to do that.I have tried many ways and also searched on google but I am unable to solve it. Please tell me what I am lacking in or what more information should I add here. I have also added the Error Log from PythonAnywhere. Please someone explain me the error also if possible as what I am doing wrong.
my file structure
|-mysite/
    flask_app.py
    |-templates/
        index.html

run.py
from flask import render_template
from bs4 import BeautifulSoup, element
import urllib2
from flask import Flask
app = Flask(__name__)

@app.route('/')
  def index():
  i=1
  count =1
  items = []
  heads = []
  bodys = []
  writers = []
  dates=[]
  m = 0
  while(i<21):
      url = 'http://www.goal.com/en-gb/rumours/last/168?page='+str(i)+'&ICID=OP'
      response = urllib2.urlopen(url)
      html = response.read()
      soup = BeautifulSoup(html)
      i +=1

      # Collect rumors posts
      rumour_post_tags = soup.find_all("div", {"id":"rumours"})

      for rumour_tags in rumour_post_tags:
          content_tags = rumour_tags.find_all("div",{"class":"rumour-content"})
          for rumour in content_tags:
             items.append(count)
             count +=1
             heads.append(rumour.find("h3",{'class':'column'}).text)
             bodys.append(rumour.find('p').text)
             for sources in rumour.find_all('span',{'class':'column'}):
                 for source in sources:
                     if m % 2 == 0:
                         writers.append(source)
                         m += 1
                     else:
                         dates.append(source)
                         m += 1
  return render_template('index.html',allitems=zip(items,heads,bodys,writers,dates))

index.html
<!DOCTYPE html>

  <title>Goal's Transfer Talks</title>

Transfer Talks

    {% for item,head,body,writer,date in allitems %}

{{ item }}. {{ head }}

{{ body }}

{{ writer }}

{{ date }}

    {% endfor %}

I am getting an error when I am trying to open my website through http://rahul3103.pythonanywhere.com/ which is:
Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

Error Log:
2015-07-29 11:17:57,179 :Exception on / [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1360, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1358, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1344, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/rahul3103/mysite/flask_app.py", line 19, in index
    response = urllib2.urlopen(url)
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 403: Forbidden

WSGI Configuration file:
# This file contains the WSGI configuration required to serve up your
# web application at http://<your-username>.pythonanywhere.com/
# It works by setting the variable 'application' to a WSGI handler of some
# description.
#
# The below has been auto-generated for your Flask project

import sys

# add your project directory to the sys.path
project_home = u'/home/rahul3103/mysite'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

# import flask app but need to call it "application" for WSGI to work
from flask_app import app as application

A: It's because you have a free account and PythonAnywhere only allows access to the internet for a whitelist of sites.


text:
Q: jQuery loop. Adding one to prev digit How can I add to last number +1, every time document does interval?
I'm getting this: jsfiddle.net/zAt7C/1/
$(document).ready(function () {
    // verification
    $('title').text('jQuery is working!');

    // loop
    setInterval(function () {
        for (var i = 1; i < 2; i++) {
            $('.repeat').append(i + ' ');
        };
    }, 1000);
});

A: LIVE DEMO
var i = 0;
setInterval(function () {
    $('.repeat').append(' '+ (i++) );
}, 1000);

A: jsFiddle demo
The answer actually lies in the use of variable scope. The variable i only exists for the scope of the setInterval callback function. Before and after that function the variable doesn't exist, so it can't hold a value… it just gets re-initialized every time the function starts. If we move the variable outside of the setTimeout function, it becomes part of a larger scope, that of the $(document).ready event handler. It will remain available for both that scope and all other scopes inside of that scope (in this case, the setTimeout callback).
A good book to read about Javascript is Douglas Crockford's Javascript: The Good Parts. There's also a good post explaining scope and closures at How do JavaScript closures work?

A: $(document).ready(function () {
    // verification
    $('title').text('jQuery is working!');

    (function func (i) {
        setTimeout(function () {
            $('.repeat').append(i + ' ');
            i += 1;

            if (i <= 10) {
                func(i);
            }
        }, 1000);
    }(0))
});

Fiddle


text:
Q: Name rotated auditd logs with date Can auditd use a date instead of an integer to name its rotated audit logs? Right now I have
audit.log
audit.log.1
audit.log.2
...

When audit.log fills up all of the files are rotated one number higher. I have a script that backs up the audit logs, and tar gets confused when it sees all the files move underneath it. I'd like to name the files by date so that they don't all get moved when audit.log fills up.

A: auditd can't do this. Its built in log rotation works by size, not by date.
You should be able to turn off auditd's built in log rotation, and then configure logrotate to rotate its logs. It does name files by date. In /etc/audit/auditd.conf:
num_logs = 0

In /etc/logrotate.d/auditd (tune as you wish):
/var/log/audit/audit.log {
    daily
    missingok
    notifempty
    sharedscripts
    rotate 2
    compress
    delaycompress
    postrotate
        /usr/bin/systemctl kill -s USR1 auditd.service >/dev/null 2>&1 || true
    endscript
}

(The USR1 signal tells auditd to rotate its logs. Since it is configured not to rotate its logs itself, this just causes it to open a new log, which occurs just after logrotate has rotated the log.)


text:
Q: Azure App service with or without docker I have some experience in using azure app services without docker. I did worked on k8 with docker. Now I am seeing an option to deploy containers in azure app services. As per my understanding app services internally use container and orchestration engine. Now someone can explain why this new docker option in azure app services? How it is going to help? When to use this option? Why I should bundle it as docker(extra effort eventhough it trivial)?

A: Azure App Service on Linux (Web App with built-in images)
The built-in image option running on Linux is an extension of a current Azure App Service offering, catering to developers who want to use FTP or GIT, deploy .NET Core, Node, PHP or Ruby applications to Azure App Service running on Linux
All of the built-in Docker images are open sourced on GitHub and available on DockerHub

Now someone can explain why this new docker option in the azure app
services?

Web App for Containers is catered more towards developers who want to have more control over, not just the code, but also the different packages, runtime framework, tooling etc. that are installed on their containers.
Customers of this offering prefer to package their code and dependencies into containers using various CI/CD systems like Jenkins, Maven, Travis CI or VSTS, alongside setting up continuous deployment webhooks with App Service.
This way you can easily deploy and run containerized applications that scale with your business.

How it is going to help?

*

*This will make sure that the environment that you use locally, is
exactly the same as the one in the cloud.

*Just pull container images from Docker Hub or a private Azure
Container Registry and Web App for Containers will deploy the containerized app with your preferred dependencies to production in seconds.

*Automate and simplify your container image deployments through
continuous integration/continuous deployment (CI/CD) capabilities
with Docker Hub, Azure Container Registry, and Visual Studio Team
Services

*Automatically scale vertically and horizontally based on application
needs. Granular scaling rules are available to handle peaks in
workload automatically while minimizing costs during off-peak times

When to use this option?

*

*If you are so passionate/familiar with Docker/container then you can
use the Azure App service with the container.

*If you are planning to host all your container in ACS(Azure Container
Service)/GitHub Repository then this service might be useful

You can refer to this blog for more details


text:
Q: Why dynamically created HTML Input is Empty After Postback I add HTML  and  tags to Page dynamically.
But after every postbost, all values are empty.
What can I do for Solve?

A: Make sure the controls you add to the page have an ID, and that the ID is the same after posting back.

A: You have to create controls in Init event of page, creating controls in Page_Load will not retain viewstat because according to control lifecycle, controls must be created before load event and just before load, the controls retrive their viewstat information. Create a new event Page_Init (make sure you write Init="Page_Init" in your first line in the Page tag). And create your controls in this event.

A: If you wish to keep the values after postback in this case, use Request.Forms[key]
you will get key-value pair here. You must prepare input in certain fix format like name attribute comes first then value etc. Then as you know format you can put back value filed in Page_load. User regular expression to replace string with pattern.
string UpdatedText = Label25.Text;

foreach (string key in Request.Form.AllKeys)
{
    if (key.ToLower().StartsWith("recomandedspec_"))
    {
        string keyvalue = Request.Form[key];
        // this uses regular expression to replace input string with postback values
        UpdatedText = PreFillItem.FillTextBox(UpdatedText, keyvalue, key);
    }
}

Label25.Text = UpdatedText;


text:
Q: recovery push button not working- Amlogic android box I am working on a ROM for android 7.1 with uboot bootloader. I have a p212 board (with amlogic s905x chip). The problem is recovery push biutton. (Which you can hold it to enter recovery mode)
Anyone knows what is the cause of problem? I guess maybe uboot but not sure..
Thanks


text:
Q: How to tell bash to specifically escape a wildcard in a Python script I have a script. It takes arguments, but I would like it, when it receives the string "*", to autocomplete it to a matching string in a list variable.
Unfortunately, this is impossible without the user escaping the wildcard using a backslash to escape the asterisk:
foo.py ba\*  # Will expand to "bar"

Not doing so would result in bash expanding it to a file in the working directory, then passing it to my script.
What is required to tell bash to not automatically expand the asterisk and just pass it to my script. Maybe an install script?

A: set -o noglob

will prevent bash from expanding the *.
Remove with set +o noglob

A: Simply call it like so to escape in bash:
foo.py 'ba*'


text:
Q: Does the .NET Garbage Collector free instances that were formerly assigned to a static reference? Until now, I thought that the following construction would work with the GC:
    public class SampleClass
    {
        #region Statics
        public static int CacheCapacity
        {
            get => CacheCapacity_;
            set
            {
                int val = value < 0 ? 0 : value;
                if(ActiveSamples_ != null)
                {
                    if(val == 0)
                    {
                        ClearCache();
                        CacheCapacity_ = 0;
                        return;
                    }
                    if (val < ActiveSamples_.Count)
                    {
                        ShrinkCacheTo((int)(0.8D * val));
                    }
                }

                CacheCapacity_ = val;
            }
        }
        static int CacheCapacity_;
        protected static List<SampleClass> ActiveSamples
        {
            get
            {
                if(ActiveSamples_ == null)
                    ActiveSamples_ = new List<SampleClass>();
                return ActiveSamples;
            }
        }
        protected static List<SampleClass> ActiveSamples_;

        public static bool AddToCache(SampleClass instance)
        {
            if(CacheCapacity == 0)
                return false;
            if (ActiveSamples.Count >= CacheCapacity)
                ShrinkCacheTo((int)(0.8D * CacheCapacity));
            ActiveSamples.Add(instance);
            return true;
        }

        public static void ClearCache()
        {
            ActiveSamples_ = null;
        }

        protected static void ShrinkCacheTo(int size)
        {
            if (ActiveSamples_ == null)
                return;
            if (ActiveSamples_.Count <= size)
                return;
            List<SampleClass> tmp = new List<SampleClass>(size);
            for (int i = ActiveSamples_.Count-size; i < ActiveSamples_.Count; i++)
            {
                tmp.Add(ActiveSamples_[i]);
            }
            ActiveSamples_ = tmp;
        }
        #endregion

        #region Constructors and Instance getters

        public SampleClass(string instanceID)
        {
            InstanceID = instanceID;
            // time-consuming initialisation ...
            AddToCache(this);
        }
        public static SampleClass GetOrCreateInstance(string instanceID)
        {
            var result = ActiveSamples.Find(x => x?.InstanceID == instanceID);
            if (result == null)
                result = new SampleClass(instanceID);
            return result;
        }
        #endregion

        #region Instance members
        public string InstanceID { get; protected set; }
        public bool IsCached => ActiveSamples.Find(x => x?.InstanceID == InstanceID) == this;
        #endregion

    }

I allow to cache instances of SampleClass (that takes quite long to initialise) up to a certain capacity so that I do not always create them when I reference them again.
As ActiveSamples_ is static, the cached instances will not be collected by the GC, which is intended as long as they are referenced by ActiveSamples_. I supposed that they become garbage as soon as I assign null or a new List not containing them to ActiveSamples_ in ClearCache(), ShrinkCacheTo() (and, of course, if there are no further references to them).
Now my colleage who is hunting memory leaks read here (point 3 and 5) that my caching may raise the problem that, if the instances were once referenced by a static object, they will never become managed code afterwards. The code samples in the link do not provide any code that cuts the reference between the static List or Dictionary and its contents, so that it may only say that they will remain as long as they are referenced but the text can be understood in the way that the become and remain unmanaged.
My question is, what is correct:

*

*Former members of a static field are permanently out of the scope of the GC; they have to be disposed.

*Once the reference from the static field to the object is no more valid, the GC will automatically dispose them when it decides to do so.

If 1. is true how do I dispose them?

A: Résumé from the comments of MySkullCaveIsADarkPlace:
Answer to (1) is "Incorrect".
The GC does not care about past affairs of instances with static fields.
If only the ActiveSamples_ list ever held a reference to some instance, as soon as that instance is removed from the list (without anything else coming in and holding a reference to this instance) or when the list itself is unassigned (without anything else holding a reference of it), then the list will be subject to GC.
Answer 2 is correct, provided that  there is nothing else in your program holding to those instances.


text:
Q: How can I make an iPhone UITextField required? How can I make a UITextField required? In other words, if the entry is empty, then refocus them on the required field.

A: Set a delegate for your field, and implement -textFieldShouldEndEditing: in it.

A: check length of textfield by [textfieldname.length] > 0. if it is then move else do textfield became first responder.


text:
Q: Keep header, image and first
* of
* together I am writing a user manual for my work, which is a text that should be printable. It's an instruction manual where following sequence appears often: header + image (centered, on separate line) + numbered list (with instruction steps)
I would like the header, the image below and the first item of the numbered list to always stay together, i.e. never page break, but I can't seem to find a way to do so.
I've tried to define h1, img {page-break-after:avoid;} in combination with img, ol {page-break-before:avoid;} in my css, but those don't catch on.
I tried enclosing the trio in a table with table{page-break-inside:avoid;}, but the problem is that that doesn't respect my ordered list if I close the table after the first item. I don't want to enclose the entire ordered list in a table, because the instructions (with their corresponding images) can span several pages anyway.
I tried div instead of table, but the numbering isn't respected either, and then I tried enclosing the trio with p and afterwards span. These do allow the ordered list to continue properly after the first list item, but they again don't respect the {page-break-inside:avoid}.
Any elegant solution?

A: One solution is to put the image inside the first list item.
Then a bit of positioning to get the layout right, and page-break-inside:avoid on the list item and you're done.

This is the picture

    This is point one.

    This is point two.

  etc.

li {font-size:16px; line-height:20px; page-break-inside:avoid}
li:first-child {padding-top:120px; position:relative}
li:first-child figure {position:absolute; top:0; margin:0 0 0 -40px;}

See jsFiddle.


text:
Q: SQL Data Warehouse External Table with String fields I am unable to find a way to create an external table in Azure SQL Data Warehouse (Synapse SQL Pool) with Polybase where some fields contain embedded commas.
For a csv file with 4 columns as below:
myresourcename,
myresourcelocation,
"""resourceVersion"": ""windows"",""deployedBy"": ""john"",""project_name"": ""test_project""",
"{  ""ResourceType"": ""Network"",  ""programName"": ""v1""}"

Tried with the following Create External Table statements.
CREATE EXTERNAL FILE FORMAT my_format
WITH (
    FORMAT_TYPE = DELIMITEDTEXT,
    FORMAT_OPTIONS(
        FIELD_TERMINATOR=',',
        STRING_DELIMITER='"',
        First_Row = 2
    )
);

CREATE EXTERNAL TABLE my_external_table
(
resourceName VARCHAR,
resourceLocation    VARCHAR,
resourceTags    VARCHAR,
resourceDetails VARCHAR
)
WITH (
    LOCATION = 'my/location/',
    DATA_SOURCE = my_source,
    FILE_FORMAT = my_format
)

But querying this table gives the following error:
Failed to execute query. Error: HdfsBridge::recordReaderFillBuffer - Unexpected error encountered filling record reader buffer: HadoopExecutionException: Too many columns in the line.

Any help will be appreciated.

A: Currently this is not supported in polybase, need to modify the input data accordingly to get it working.


text:
Q: Cannot start ASP.NET Core RC2 web application in IISExpress I created a new "ASP.NET Core Web Application (.NET Core)" project in VS2015. It built without any issues, so I thought to give it a test run. However, when starting up, it choked and crashed with the following error:
Exception thrown: 'System.AggregateException' in Microsoft.AspNetCore.Server.Kestrel.dll
The program '[11608] dotnet.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.
The program '[15048] iisexpress.exe' has exited with code 0 (0x0).

I don't see anything else logged. I tried debugging it, and all I found out was that it broke during the WebHostBuilder.Run() method in Program class. It is part of the framework, so I wasn't able to get much further.
Note that the program runs fine when running via dotnet run command. Only IISExpress does not work.
How should I go about debugging this issue?
The project.json file is below. (It was generated by Visual Studio, I did not change anything.)
{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0-rc2-3002702",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview1-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc2-final"
  },

  "tools": {
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    }
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "gcServer": true
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Update: I created a new project for the Core RTM release, and this time it worked.

A: The other issue is that you might be running an old version of the framework. Try going to the root (project.json) location of your runnable project and in a Command Prompt type:
dotnet run

A: I had the same problem as you. For me the solution was to close VS2015, delete the file project.lock.json  and then restart VS again. (project.lock.json will be generated automatically)
It looks like the debugger cannot attach to the application. In my case I added a throw new Exception("..."); in the first line of the function public Startup(IHostingEnvironment env) and the application just dies and doesn't break on the unhandled exception as expected.
After project.lock.json was rebuilt the debugger works fine again.

A: I updated to the RTM release of dotnet core and creating a new project using the new version worked. I guess it must be a bug.

A: For those bumping into this, I had the same exactly behavior and error message as described in the question.
Apparently there are some terms that can't solely be used as the project name, such as web or app. (I fixed it renaming my project to WebApp)
It was already logged as a bug and the fix will be included in the upcoming releases.
Unfortunately, after the first failed run, a project rename isn't enough to make it work, since the IIS Express config file keeps the old entry.
Just edit the applicationhost.config file located at [PROJECT_ROOT]\.vs\config\ and remove the site element that is named web or app, restart VS and run it.
Hope it helps!

A: I've got the same error when I run my project (not using IIS).
After some investigation I found out that server url in appsettings.json (which using in Configuration) was already busy. I changed url and it worked well.
Hope it helps somebody!

A: I had the same error. The solution is found was that my x64 app was set to build as x86


text:
Q: C++ iterator value to variable I am using an iterator in a C++ code to retrieve records read using sqlite3 statements. I am able to display the contents pointed to by the iterator to screen using cout. How would i assign the value to a simple float or array variable.
typedef vector<vector<string> > Records;
vector< vector<string> >::iterator iter_ii;
vector<string>::iterator iter_jj;

Records records = select_stmt("SELECT density FROM Ftable where PROG=2.0");

  for(iter_ii=records.begin(); iter_ii!=records.end(); iter_ii++)
   {
      for(iter_jj=(*iter_ii).begin(); iter_jj!=(*iter_ii).end(); iter_jj++)
      {
         cout << *iter_jj << endl; //This works fine and data gets displayed!

         //How do i store the data pointed to by *iter_jj in a simple float variable or array?
      }
   }

A: C++ is type-safe, so you need to explicitly convert the string to the desired target type.
For float for example you could use atof:
float f = atof(iter_jj->c_str());

A more convenient alternative is Boost's lexical_cast, which works with the same syntax for all types that support extraction from an std::istream:
float f = boost::lexical_cast<float>(*iter_jj);

Note that both of these can fail in different ways if the contents of the string cannot be converted to a float in any meaningful way.

A: Your real problem is how to convert a string to a float. Here is one solution.
float value;
stringstream ss(*iter_jj);
if (! (ss >> value))
{
    ERROR failed to convert value
}

A: If you have C++11 compatible compiler:
float x = stof(*iter_jj);

(Obviously x could be a variable outside of the loop).
If you don't have C++11:
stringstream ss(*iter_jj);
float x;
ss >> x;

A: Well since you are working with:
std::vector<std::vector<std::string> > records;

the actual question here is: how to retrieve the specific type of data from std::string object.
The good approach would be constructing and using std::istringstream object for this purpose:
float f;
std::istringstream is(*iter_jj);
if (is >> f)
{
    // handle successful retrieval...
}

just don't forget to #include <sstream> :)

A: As for converting * to string, in c++11, you can convert integer/floats to string by calling static method to_string:string str = std::string::to_string(integer/* or float*/);
in c++98, you can write your own to_string:
#include <cstdio>
#include <cstring>
#include <cstdarg>
#include <string>
void format_aux(char* ptr, int size, const char* format, ...) {
    va_list args;
    va_start(args, format);
    vsnprintf(ptr, size, format, args);
    va_end(args);
}

#undef TO_STRING__GEN
#define TO_STRING__GEN(type, arg, size)     \
std::string                                 \
to_string(type val) {                       \
    const int sz = size;                    \
    char buf[sz];                           \
    format_aux(buf, sz, arg, val);          \
    return std::string(buf);                \
}

TO_STRING__GEN(int,           "%d", 4*sizeof(int))
TO_STRING__GEN(unsigned int,  "%u", 4*sizeof(unsigned int))
TO_STRING__GEN(long,          "%ld", 4*sizeof(long))
TO_STRING__GEN(unsigned long, "%lu", 4*sizeof(unsigned long))
TO_STRING__GEN(float,         "%f", (std::numeric_limits<float>::max_exponent10 + 20))
TO_STRING__GEN(double,        "%f", (std::numeric_limits<float>::max_exponent10 + 20))

#undef TO_STRING__GEN

A: *iter_jj is going to give you a std::string.  In order to store that as a float, it will need to be a floating point number in string form (e.g. "1.23456") and you will need to call  one of the strtof family of functions (http://en.cppreference.com/w/cpp/string/byte/strtof)


text:
Q: .htaccess structure problems I'm trying to come up with an .htaccess structure for a multilingual site, using subdirectories per language (i.e. www.mysite.com/en/). I'm having some difficulties getting this to work, experiencing problems both with running it on localhost (since the site itself is not in the root directory) and redirecting to "sv" by default in case a language has not been set.
This is the .htaccess code:
RewriteEngine On
#Default to "sv/"
RewriteRule !^(.*){2}/ sv%{REQUEST_URI} [L,R=301]
#Rewrite for "properties", EN special articles related to another system
RewriteRule ^properties/(.*)/?$ index.php?language=en&page=object&slug=$1

#Rewrite for "fastigheter", SV special articles related to another system
RewriteRule ^fastigheter/(.*)/?$ /index.php?language=sv&page=object&slug=$1

#EN articles
RewriteRule ^en(.*)$ index.php?language=en&page=article&slug=$1 [L,QSA]
#SV articles
RewriteRule ^(.*)$ index.php?language=sv&page=article&slug=$1 [L,QSA]

RewriteBase /mysite
RewriteRule ^(.+)/(css|img)/(.+)\.(gif|png|jpe?g|css|js)$ $2/$3.$4 [L]

Do you see any errors in the rewrite rules / do I need to add something to get this sort of structure to work properly?


text:
Q: How to echo redirected stdin I execute an application from a script file and redirect stdin to it from here-doc like this:
my_cli << HERE_DOC
enable
configure
10
exit
exit
HERE_DOC

This works as expected, but I don't see neither the input nor the app output. The application is an interactive prompt written in C. When I interact manually with it, I see the prompt itself and responses to my input, but when I execute the aforementioned script I see nothing. I would like it to print the input and the output as if a real user was typing. Do you know how to achieve that?

A: It seems like there ought to be a better way, but you could use a wrapper function:
wrapper () { local text=$(</dev/stdin); echo "$text"; my_cli <<<"$text"; }
wrapper << HERE_DOC
enable
configure
10
exit
exit
HERE_DOC

To process the here doc line by line:
wrapper2 () { local line; while read -r line; do echo "$line"; my_cli <<<"$line"; done; }

If you manually interact with your program, does it show output? Does it output to stdout or stderr?
Another option that might work for you is expect.

A: I see Perl!
Well, you can't do it if you're using qx or system calls, since they are blocking in nature (yes, you can do system("program &") or call it from another thread and detach it.
Launcher thread:
threads->create( sub {
                    threads->self->detach();
                    qx"$cmd > file1.cmd";
});

Main code: :
threads->create( sub {
while (1) {
 get file size, if it is bigger than second ago - read new line, increase size
 parse new line, if any?
 sleep 1;
}
} );

Better,
use POE::Wheel::FollowTail
Another solution is to redirect output of each of your programs to named fifo and read them all from your prog, keeping an eye for new lines.
man mkfifo

A: (tee /dev/fd/42 | mycmd) 42>&1 <<EOF
blah
blah
EOF

It won't look exactly like a real user - all input will be printed immediately. expect is probably better for this.


text:
Q: how do I make an android service that runs when the application doesn't? my knowledge of services in any operating system, is that they usually run in the background and perform whatever work they have to do.
but the first time I got familiarized with android services, I got confused.
it appears they only run when the application is working, and that for me, makes them no more then sophisticated threads.
do I have this all wrong? how do I make a service that runs when the application doesn't? (so that I can check for updates and create notifications for the user that will then lead him to the application if he chooses to open them).
does push notifications have anything to do with it?
Edit:
thank you guys for your answers so far.
my problem seems to be the fact that the service is only started officialy when the device is booted up. I do call startService when the app starts, but that doesn't seem to help. the service still dies when the app is turned off (unless it was booted)
also I never call stopService

A: If you are trying to implement a long running task that is performed in a (background) service, you have to start one or more threads within your service. So the service just gives you the opportunity to have an application context without having to have a user interface ;) you can consider it as a kind of container.
This page give you a nice overview about different thread approaches in Android. As you can see a service has not its own thread.
Anyway, in your case it seems that an AlarmManager is probably the better option. Running services for polling information all the time can be quite CPU and battery consuming (see this post for instance). So try to avoid having threads that run all the time.
If you can push information about updates from a server it's just fine. Check out Googles Cloud Messaging in this case.

A: Michael who commented on my question first was right in his comment about startService()
so it goes like this:

*

*my receiver is only activated on boot, and uses an AlarmManager to
time the service to certain intervals.

*what I did was to bind the activities to the service. if the service
was off and I binded it and unbinded it, then by the time the app was
terminated, there was nothing keeping it alive.

*by simply making sure that the service was started properly with
startService if it is not already on, I managed to keep the service
alive at all times

*also thanks to Trinimon who gave a very nice explanation on what
services are, and the importance of not overloading the CPU with
excessive polling. (which is kind of a trade off situation)

good luck to all :)


text:
Q: Considering the Topology of a Special Open Set I have been considering the set
$$V = \{(x,y) \in \mathbb{R}^2 | 1+x^2+xy \neq 0\},$$
and I have proven earlier that this set is open. I want to prove the
disconnectedness of this set, but I am having issues with this given
my instructor's definition of a disconnected set.
Most definitions of a disconnected essentially boil down to the existence
of two open sets
$A,B \subset V$ such that $A \cap B = \emptyset, A \cup B = V, A \cap V \neq
\emptyset, B \cap V \neq \emptyset .$ Under these conditions, it is pretty
apparent that in our case, the sets
$$A = \{(x,y) \in \mathbb{R}^2 | 1+x^2+xy < 0\}$$
and
$$B = \{(x,y) \in \mathbb{R}^2 | 1+x^2+xy > 0\}$$
satisfy these conditions.
However, my instructor recently gave me the definition that a set $U$ is
disconnected if there exists two disjoint open set $A$ and $B$ such that
$U \subset A \cup B, U \cap A \neq \emptyset, U \cap B \neq \emptyset .$ Note
that this case is slightly altered given the fact that $A \cup B$ must
strictly contain $U$. Any recommendations on how to alter my current
solution to satisfy this particular definition?

A: Both definitions of disconnectedness are equivalent. If we have two disjoint nonempty open sets $A,B \subseteq V$ under the subspace topology such that $A \cup B = V$, then as Doug M pointed out in the comments, $V \subseteq A \cup B$. Further, since $A$ and $B$ are nonempty and are contained in $V$, we have $A \cap V \neq \emptyset$ and $V \cap B \neq \emptyset$.
Conversely, if there exist disjoint open sets $A$ and $B$ such that $V \subseteq A \cup B$, $V \cap A \neq \emptyset$, and $V \cap B \neq \emptyset$, then the sets $V \cap A$ and $V \cap B$ are open in the subspace topology, are disjoint, and $V= (V \cap A) \cup (V \cap B)$.
In short, there is no need to modify your answer.
I should point out that the sets $A$ and $B$ in the first definition are only required to be open in the subspace topology. This is typically the result of connectedness being defined in terms of the ambient space $X$, and then defining it for subsets of $X$ using the subspace topology.


text:
Q: How to stop an infinite stream if you don't know the exact number of iterations in Java 8 What is the best way to transform a while loop like the one below to the functional stream if you don't know the exact number of iterations?
int i = 10;
while (i > 1) {
    System.out.println(i);
    i--;
}

I came up with something like this, but I want to remove the limit and stop iteration with something like a predicate condition
Stream.iterate(10, n -> n - 1).filter(n -> n > 1).limit(9).forEach(System.out::println);

A: takeWhile, since java-9 though:
 Stream.iterate(10, n -> n - 1)
       .takeWhile(i -> i > 1)
       .forEach(System.out::println);

See a back port for java-8 here also.


text:
Q: Matching two types of data (elevation and imagery) which are in different scale? My problem is that elevation and imagery data I'm getting from USGS is in different scales and is aligned to different grids. I don't want to match it manually in Photoshop.
Does QGIS know how to match this data?
(huge, blue square is elevation, small ones, imagery)

A: As long as each dataset you are adding (elevation and imagery) has the correct grid information, QGIS will be able to project both datasets properly. If they cover the same area, than you will have the map-matching you are looking for.
Install QGIS, then add your datasets. That should work out as you are interested in.


text:
Q: Gradle properties not being read from ~/.gradle/gradle.properties I have a similar problem as detailed here:
http://gradle.1045684.n5.nabble.com/gradle-gradle-properties-not-being-read-td4372872.html
In fact, it's the exact same problem - except that the solution from that thread doesn't work for me. I'm on OS/X, with an android build using gradle. The gist of what's happening is that with the following ~/.gradle/gradle.properties file:
uploadUsername=scottj
uploadKeyFile=/home/scottjohnson/.ssh/uploadKey

And the following build.gradle file:
... skipped general gradle and android-specific stuff ...
task checkProperties << {
  if (!hasProperty('uploadUsername')) {
    throw new RuntimeException("Couldn't find uploadUsername property. Did you forget to specify it in ~/.gradle/gradle.properties?")
  } else if (!hasProperty('uploadKeyFile')) {
    throw new RuntimeException("Couldn't find uploadKeyFile property. Did you forget to specify it in ~/.gradle/gradle.properties?")
  }
  println("***** DEBUG_jwir3: " + project.getProperty('uploadUsername'))
}

When I run ./gradlew checkProperties, I get:
FAILURE: Build failed with an exception.

*

*Where:
Build file '/Users/scottjohnson/Source/core-android/crux/build.gradle' line: 50

*What went wrong:
Execution failed for task ':crux:checkProperties'.

Couldn't find uploadUsername property. Did you forget to specify it in ~/.gradle/gradle.properties?

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 7.072 secs
What's more interesting, if I specify that I want debug logging, I get the following:
mustafar:core-android scottjohnson$ ./gradlew checkProperties -d | grep properties
19:22:35.507 [DEBUG] [org.gradle.initialization.DefaultGradlePropertiesLoader] Found env project properties: []
19:22:35.508 [DEBUG] [org.gradle.initialization.DefaultGradlePropertiesLoader] Found system project properties: []
19:22:35.865 [DEBUG] [org.gradle.initialization.ProjectPropertySettingBuildLoader] Looking for project properties from: /Users/scottjohnson/Source/core-android/buildSrc/gradle.properties
19:22:37.161 [DEBUG] [org.gradle.initialization.DefaultGradlePropertiesLoader] Found env project properties: []
19:22:37.161 [DEBUG] [org.gradle.initialization.DefaultGradlePropertiesLoader] Found system project properties: []
19:22:37.200 [DEBUG] [org.gradle.initialization.ProjectPropertySettingBuildLoader] Looking for project properties from: /Users/scottjohnson/Source/core-android/gradle.properties
19:22:37.200 [DEBUG] [org.gradle.initialization.ProjectPropertySettingBuildLoader] Adding project properties (if not overwritten by user properties): [CORE_GROUP, CORE_VERSION_NAME, CORE_VERSION_CODE]
19:22:37.201 [DEBUG] [org.gradle.initialization.ProjectPropertySettingBuildLoader] Looking for project properties from: /Users/scottjohnson/Source/core-android/crux/gradle.properties

As you can see, it's recognizing the properties in the core-android/gradle.properties file (CORE_GROUP, CORE_VERSION_NAME, and CORE_VERSION_CODE), but I don't see either of the properties from ~/.gradle/gradle.properties being pulled in.
I don't want to specify these properties in my project's gradle.properties, because they are user-specific (credentials for pushing to a private maven repository).
What am I doing wrong that is causing the gradle.properties not to be pulled in?

A: Inside a task action, hasProperty will resolve to Task#hasProperty. Instead use project.hasProperty(...).


text:
Q: Collapsible list with a loadmore button to show all the items from this list I am developing a collapsible list that only shows the first five items and a load more button at first, and when I click the load more button, the full list should be shown. I am using scrollHeight to determine this collapsible list's height and it works fine to show the first five items and the load more button, but after I click the load more button, the height of this collapsible list does not change and the remaining items cannot be displayed due to the height constraint. Does anyone have an idea how to fix it? Thank you so much, I really got stuck here for this whole day.
This is how this collapsible list looks like the collapsible list
This is the code of collapsible list
    const Collapsible = ({ showCard, loaded, children }) => {
      const collapsibleEl = useRef();
      const [scrollHeight, setscrollHeight] = useState();

      useEffect(() => {
        setscrollHeight(collapsibleEl.current.scrollHeight);
        console.log(collapsibleEl.current.scrollHeight);
      }, [loaded, showCard]);
      return (
        <>
          <div
            className={styles.collapsible}
            ref={collapsibleEl}
            style={
              showCard
                ? scrollHeight
                  ? { height: `${scrollHeight + 100}px` }
                  : { height: `${collapsibleEl.current.scrollHeight + 100}px` }
                : { height: "0px" }
            }
          >
            {children}
          </div>
        </>
      );
    };
    export default Collapsible;

A: I have figured it out, all I need to do is to use settimeout.
like this, just give it a little time to get the scrollheight and then re render.
useEffect(() => {
    setTimeout(() => {
      setscrollHeight(collapsibleEl.current.scrollHeight);
    }, 300);
    console.log(collapsibleEl.current.scrollHeight);
  }, [showCard, loaded]);


text:
Q: Executing Limit within a Function I am trying to create a Mathematica function where f[0] = 0, f[1] = 1 and f[10] = $\infty$, ala Warp Speed from Star Trek. When I designate the following function:
f[x_] = Limit[90 / (10 - a) - 9, a -> x, Direction -> 1];

I get $f[x]=\frac{9 x}{x - 10}$ and $f[10] = ComplexInfinity$, where it executes the limit before it adds in the variable. How do I make it go the other way around, where the limit waits for the variable to come in first. Is that possible?


text:
Q: Смена мест элементов массива Идея программы - замена порядка номеров в массиве на обратный. Но в итоге выдает [undefined, 1, 3, 4, 5].

function reverseArray (array) {
  let tempVar = [];
  for (i=0; i<Math.floor(array.length/2); i++) {
  tempVar = array[i];
  array[i] = array[array.lenght-1-i];
  array[array.lenght-1-i] = tempVar;
  };
return array
};
console.log(reverseArray([1, 2, 3, 4, 5]));

A: Опечатка в названии свойства lenght

function reverseArray (array) {
  let tempVar;
  for (var i = 0; i < array.length / 2; i++) {
    tempVar = array[i];
    array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = tempVar;
  };
  return array;
};
console.log(reverseArray([1, 2, 3, 4, 5]));

A: Так же обратите внимание на метод reverse
Пример: [1, 2, 3, 4, 5].reverse() // [5, 4, 3, 2, 1]


text:
Q: Soql in Vf page using sForce.connection I am trying to soql in VF page. But I am not getting an result. I have verified my code.
<apex:page >

    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="/soap/ajax/33.0/connection.js" type="text/javascript"></script>
    <script src="/soap/ajax/33.0/apex.js" type="text/javascript"></script>
    <script type="text/javascript">

     function soqlQuery(){
          try{
              var result = sforce.connection.query("SELECT Id, Name from Account",{
                  onSuccess : function(result){
                      alert('I am in 2');
                  },
                  onFailure : function(error){

                  }
              });
          }catch(e){
              alert(e);
          }
      }
      window.onload=function(){
          soqlQuery();
      }
     </script>
</apex:page>

Can anyone check and let me know what i am missing out here.

A: To get the list of records from result
You need result.getArray("records") to get the records
complete code
<apex:page >

    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="/soap/ajax/33.0/connection.js" type="text/javascript"></script>
    <script src="/soap/ajax/33.0/apex.js" type="text/javascript"></script>
    <script type="text/javascript">

     function soqlQuery(){
          try{
              sforce.connection.sessionId = '{!$Api.Session_ID}';
              var result = sforce.connection.query("SELECT Id, Name from Account",{
                  onSuccess : function(result){
                      alert('I am in 2');
                      var records = result.getArray("records");
                     console.log('==========records======='+records);
                  },
                  onFailure : function(error){

                  }
              });
          }catch(e){
              alert(e);
          }
      }
      window.onload=function(){
          soqlQuery();
      }
     </script>
    </apex:page>

and check browser console..

A: Am not sure whether the sforce.connection.query have callback function. You can use like below
var result = sforce.connection.query("SELECT Id, Name from Account");
var records = result.getArray("records");
for (var i=0; i< records.length; i++) {
    var record = records[i];
    log(record.Name + " -- " + record.Id);
}

Hope it helps.


text:
Q: open form2 only one at a click of a button on form1 enter image description herehow to set a code to open form2 only one at a click of a button1 on form1. When I click on the Button1 I open my form2 and the next time I click again I open form2 again as the second same window.

A: So you only want a single form 2 to open when you click the button even if you click it multiple times?
If so you would create a bool variable and use that to check if it is open already. So this would go inside your button clicked method.
if(isOpen==false)
{
    Application.Run(form2());
    isOpen = true;
}

Then once you close that form you would just change isOpen to false so you could open it up again.


text:
Q: I have a for loop trying to plot multiple graphs, but they are plotted over each other, what am I doing wrong? I have this code, which is supposed to return multiple graphs, for some reason I cannot figure out (never had this problem). I get multiple graphs, but as it iterates through the loop the graph after the first contains all previous ones.
for x in np.arange(0,3):
    t1= table.iloc[x,2]
    t2= table.iloc[44,2]
    dts = np.arange(-0.02,0.02,0.0001)
    cc = np.zeros(len(dts))
    for i,dt in enumerate(dts):
        n1,v=np.histogram(t1,899*100)
        n2,v=np.histogram(t2-dt,bins=v)
        cc[i] = np.corrcoef(n1,n2)[0,1]
    plt.plot(dts,cc)
    #plt.title(str(table[table['ClusterNames']==test1.iloc[x,0]].iloc[0,0])+'_'+str(table[table['ClusterNames']==test1.iloc[x,1]].iloc[0,0]))
    filename='step'+str(x).zfill(6)+'.png'
    plt.savefig(filename, form='png', dpi = 96, transparent = True)

What am I doing wrong?
Thanks!

A: If you want each figure in a different window, you should add plt.figure() before plt.plot()

A: There are many ways to do this. To clear the plot after saves, you could add plt.clf() to the end of your loop. To plot everything on one page, you can use plt.subplot2grid OR plt.subplots.


text:
Q: Why we have two data model static and dynamic in lwc to refer in metadata aware component In base lightning component in LWC we can refer data model static or dynamic.
Static ensures referential integrity whereas dynamic does not.
Is there any other difference between these two? Which one is faster and what other difference these two have.


text:
Q: How to check if derived class was fully constructed What I am looking for is a way for a Base class detect that the Derived class was not fully constructed.  There is some logic in the Base destructor that I only want executed if the Derived class was fully constructed.  I don't want to modify the implementations of Derived at all. I could modify Derived with a flag that gets set at the end of the destructor, but I was hoping for some trick that does this automatically.
class Base {
public:
   ~Base() {
      if (FullyConstructed()) {cout << "fatal program bug"; abort();}
   }
};

class Derived : public Base {
public:
   Derived()
   {
      if (Something()) throw std::runtime_error("oh oh");
   }
   ~Derived() { }
};

main()
{
     Derived d;
}

When this runs, Base gets constructed, Derived does not get constructed fully because it throws, then immediate ~Base gets called.  Because ~Derived is not called, ~Base will call abort.
How do I implement FullyConstructed() in the Base class? Is there a way to detect that the vtable for Derived wasn't constructed?

A: Well you could build your own way such as:
class Base
{
protected:
    bool DerivedIsFullyConstructed;

public:
    Base() : DerivedIsFullyConstructed(false)
    {
    }
    ~Base()
    {
        if (DerivedIsFullyConstructed)
        {
            // whatever you want
        }
    }
};

class Derived : public Base
{
public:
    Derived()
    {
        // ... stuff

        DerivedIsFullyConstructed = true;
    }
};

But if I were to see such a thing in practice it would make me want to review the design to see if there's a better way.


text:
Q: Comparing two dates in JSP I know this could be a basic question but i have been stuck on this for hours. What i am trying to do is a comparing two dates in JSP and if the following equals each other do the follow.
    <%
        if(!viewBean.isHiddenEndDate())
        {
            (reportVO.getEndDate().getYear() == 9999 && reportVO.getEndDate().getMonth() == 12 && reportVO.getEndDate().getDate() == 31);
    %>
        <td headers="EndDate<%=localizationHelper.getContentString(reportVO.getLocalizedTypeLabel())%>">"Until terminated"
    <%  }else{ %>
        <%=localizationHelper.formatDate(reportVO.getEndDate())%>
    <%
    }
    %>

However when i do this, mySyntax error, insert AssignmentOperator Expression to complete Assignment and Syntax error, insert ; to complete BlockStatements.
Thanks.

A: The compiler is expecting something like boolean flag = to the left of the line (reportVO.getEndDate().getYear() == 9999 && reportVO.getEndDate().getMonth() == 12 && reportVO.getEndDate().getDate() == 31);   Hence the error about completing the Assignment Operator Expression.


text:
Q: Livewire session returns NULL in Laravel Auth Middleware I have a livewire component that needs to send requests using JWT.
As the livewire GET request is not sending the token by default, I decided to modify the Laravel's Authentication middleware in order to send the token that I put in session in the livewire component, via bearer in Laravel Auth middleware.
That the variable that I added to the session in my livewire component, returns NULL when I try to retrieve it in the Authentication middleware.
1.Livewire component
<?php

namespace App\Http\Livewire;
class HelloWorld extends Component
{
    public function mount(TransactionCheckoutRequest $request)
    {
        session(['x__livewire__token' => 'put token in session' ]);
    }
}

2.Laravel auth middleware
<?php

namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Facades\Cookie;

class Authenticate extends Middleware
{
    public function handle($request, Closure $next, ...$guards)
    {
        # Check if request is made using LIVEWIRE
        if ( request()->hasHeader('x-livewire') ) {

            /**
             * get token from session
             *
             *
             * But, this $token return NULL
             * instead token value.
             */
            $token = session()->get('x__livewire__token');

            $request->headers->set('Accept', 'application/json');
            $request->headers->set('Content-Type', 'application/json');

            // # Send token to request header
            $request->headers->set('Authorization', 'Bearer ' . $token);
        }

        # After that, authenticate livewire request
        $this->authenticate($request, $guards);

        return $next($request);
    }

    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if ( !$request->expectsJson() ) {
            return route('user.login');
        }
    }
}

3.Web route file
<?php

Route::group(['prefix' => 'v1'], function() {

    Route::group(['middleware' => ['auth:api', 'jwt.verifyer', 'hostname.access.verifyer']], function() {

        # Here is LIVEWIRE component
        Route::get('/processing', HelloWorld::class)->name('transaction.checkout');
    });

});

Can somebody explain how should I extend the middleware to use the token?

A: Livewire uses its own request when making requests. if you want to send additional data. You can send it using addHeaders.
<script type="text/javascript">
    document.addEventListener("livewire:load", function(event) {
        Livewire.addHeaders({
            'Authorization': 'Bearer {{ $token }}',
        })
    });
</script>


text:
Q: Getting more output from NetCat Currently I'm using the standard netcat -e /bin/sh to provide a remote shell for other computers to access.
The problem is however that this shell is rather terrible, since it has limited output. For example if I send some invalid command xxxxx, I will get no response from the machine, but on the machine there will be an error in the terminal saying /bin/sh: xxxxx: not found.
If I use the shell to launch a console application, often I cannot see anything the console application outputs, and I can't Ctrlz over the shell because that will close netcat on the machine. It's a mess, I'd like it to work just like SSH (which I can't use).
Instead of piping everything to /bin/sh like I'm doing with netcat, would it be possible to create a custom application instead that will show me all the outputs in a terminal? Is it possible somehow get the text off the terminal, regardless of what process wrote to it?
Would it be possible to start an sshd on the box, and then netcat -e "ssh root@localhost" and do it that way? (I've tried this, doesn't seem to work).
I'm looking for any kind of solution.

A: Creating a "custom application" would be re-implementing telnet / ssh. This is, of course, possible, but not necessary.
If there is sshd (or telnetd) on the host you can start it from your netcat-shell session with e.g. /usr/sbin/sshd -p <port> -D 2>&1 and then do ssh -p <port> root@<host> on your client. You might need to add further options to sshd, perhaps create a config file and give it in the command line: /usr/sbin/sshd -f <config-file> ...
If not, you can use the netcat session to upload telnetd or sshd, set up the needed environment / config and run it on some port.
You can also make a wrapper around your shell to redirect stderr to stdout, like /bin/sh 2>&1, which would allow you to see stderr in your netcat session, but would not give you "real terminal" functionality.
Another option is DISPLAY=<client>:0 xtrem if you have xterm or equivalent on the host and X Server on the client.


text:
Q: How to pass Array to Handlebar helper using nodemailer-express-handlebars I have trouble understanding how to use Handlebar Helpers with nodemailer-express-handlebars.
I want to send out an E-Mail asking customers to review their order. For that, our Shop sends an array with their order to our Webserver.
This is my JS code for the mail:
const hbs = require('nodemailer-express-handlebars');
const nodemailer = require('nodemailer');
const path = require('path');
const Handlebars = require("handlebars");

const viewPath =  path.resolve(__dirname, './templates/views/');
const partialsPath = path.resolve(__dirname, './templates/partials');

function reviewMail(req){

    const lineItems = req.body;

    var transport = nodemailer.createTransport({
        host: "HOST",
        port: 587,
        auth: {
        user: "USER",
        pass: "PASS"
        }
    });

    transport.use('compile', hbs({
        viewEngine: {
          extName: '.hbs',
          // partialsDir: viewPath,
          layoutsDir: viewPath,
          defaultLayout: false,
          partialsDir: partialsPath,
        },
        viewPath: viewPath,
        extName: '.hbs',
      }))

    var mailOptions = {
        from: 'MAIL',
        to: 'MAIL',
        subject: 'Bitte bewerte deine Bestellung',
        template: 'index',
        context: {
          lineItems: lineItems
        }
    };

    transport.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
    });
};

module.exports = {
    reviewMail
}

And the header of my index.hbs file contains:

The body then includes this (HTML Code shortened):
{{#each lineItems}}

<img class="adapt-img" src="{{lineItemImage}}"

{{/each}}

This is an example array, which would be passed:
{
  "lineItems": [
    {
      "lineItemName": "neowake® Chroma Watch",
      "lineItemUrl": "https://www.neuro-shop.net/products/neowake-chromawatch"
    },
    {
      "lineItemName": "BIOTONICS Vol.1 - Körperliche Ausleitung",
      "lineItemUrl": "https://www.neuro-shop.net/products/biotonics-vol-1-korperliche-ausleitung"
    },
    {
      "lineItemName": "neowake® Source Code Album (Physische CD)",
      "lineItemUrl": "https://www.neuro-shop.net/products/neowake-source-code-album"
    }
  ]
}

I do get an E-Mail but without the {{#each}} - block, probably because I don't pass the data correctly. Where is my mistake?


text:
Q: How to convert the where match query in laravel? I want to convert the following query to Laravel ORM
$sql = "SELECT * FROM snippets WHERE MATCH(snippets_name,seo_description,snippets_description,snippet_tags)
          AGAINST (' ".$query."' IN BOOLEAN MODE) LIMIT " . $start . "," . $limit;

I tried following code
But Not getting the desired results
 $searchdata = DB::table('snippets')
        ->selectRaw("*")
        ->whereRaw("MATCH(snippets_name,seo_description,snippets_description,snippet_tags) AGAINST (' ".$query."' IN BOOLEAN MODE)")
        ->paginate(20);

A: What results are you actually getting?
I've implemented FULLTEXT search using Eloquent before, and recommend moving the MATCH clause into the SELECT, and ordering by the score it returns.
Additionally, paginate() doesn't work so well with raw query parts, so you might be better off creating your own pagination using take() (limit) and skip() (offset).
And, finally, you should use a prepared query binding rather than adding your $query variable into the raw SQL.
This might work for you:
\DB::table('snippets')
    ->select([
        '*',
        \DB::raw("MATCH(snippets_name, seo_description, snippets_description, snippet_tags) AGAINST (? IN BOOLEAN MODE) AS score"),
    ])
    ->take($limit)
    ->skip($start)
    ->havingRaw('score > 0')
    ->orderBy('score', 'DESC')
    ->setBindings([$query])
    ->get();

I've included the havingRaw() to exclude any results with a 0 score, which are probably irrelevant.


text:
Q: Deletion of SQL Profiler Trace files (.trc) We've noticed a lot of .trc files in our SQL data folder (\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data) on our server. The date range for these files spans over one day and the total file size of all files together is about 21 gigs. I'd like to free up this space but I'm not sure if I can just delete the files manually through Windows Explorer or if I need to do anything in SQL, like run a command or script. Any ideas?

A: The .trc files are safe to delete.
.trc files generated by SQL Server in process of saving events to a physical file without using the Profiler client tool.  Server-side tracing is enabled and controlled by using SQL Server system-supplied stored procedures and functions. With these system-supplied processes, you can identify what to trace, when to start and stop tracing, what traces are running, and view trace information stored in the trace file.
View the number of currently running traces :
SELECT count(*) FROM :: fn_trace_getinfo(default) WHERE property = 5 and value = 1

More detail about the running traces:
SELECT * FROM :: fn_trace_getinfo(default)

You can terminate a trace with the 'sp_trace_setstatus' stored procedure using the traceid:
EXEC sp_trace_setstatus 1, @status = 0
EXEC sp_trace_setstatus 1, @status = 2

Setting the status to 0 stops the trace
Setting the status to 2 closes the trace and deletes its definition from the server
Good Luck!

A: If the trace files are no longer in use, then they should be fine to delete. I'd say someone was doing some troubleshooting of an application and forgot to delete the trace files when they were done.
A trace file would only be in use if the trace is still running. If the files are more than a day old then it's a safe bet that the trace is no longer running. If the trace IS running the file will be locked and you won't be able to delete it anyway.

A: are the traces still rolling over? what are the files name like? make sure it's not something like an audit trace.  Filenames are typically audittrace[datetime].trc
It could also be the default trace (2005+), although its unusual that it would be that large in size and these are typically found in the \MSSQL.1\MSSQL\LOG
Just to be sure, have a look at sys.traces to make sure the trace isn't still running , or stopped but still defined, or it is in fact the default trace.  You should only be seeing your default trace in there if its turned on, with an id of 1.
Either way, as long as you don't need the traces their safe to delete.  You just want to be sure they dont come back!


text:
Q: JdbcPagingItemReader vs JpaPagingItemReader which is better to use I have to write a spring batch job, and need to read 100,000 records daily.
Which implementation of Item Reader is better to use between JdbcPagingItemReader and JpaPagingItemReader.
JpaPagingItemReader will use entity classes and can have out of box Auditor.
Is something similar(Auditor) possible with domain classes used via JdbcPagingItemReader ?


text:
Q: How do I use drawimage() on an obstacle.push in an HTML canvas game? When trying to draw an image on an obstacle in an html canvas game I get this error message: Uncaught InvalidStateError: Failed to execute 'drawimage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.
The obstacle is invisible but the game still stops if the player collides with where it should be. The other stationary obstacles' images in the game are visible. What do I do?
I tried uploading the images in my html to let them load before using them but it still doesn't work. Other articles about similar situations do not cover this same context and do not help me who is quite new to programming.
Here is the code:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" type="text/css" href="stylesheet.css"> <link/>

 My Lost Game

Press the 'up', 'down', 'left' and 'right' keys on your keyboard to move. Avoid the obstacles and reach the goal.


text:
Q: What are the variables inside :root and the simple ones with $ Can somebody explain to me what's the difference between the variables in :root and the variables above it please?
Why can't we just use one syntax (either with & or --) or just put the $primary and $secondary in :root{...} ?
$primary: #ffcc00;
$secondary: #4b4b4b;

:root{
  --data-color-primary: #{$primary};
  --data-color-secondary: #{$secondary};
}

A: $primary and $secondary are SCSS variables. They get replaced with their value, #ffcc00 and #4b4b4b after compilation. When they are at the top of the file as in your case, they are accessible anywhere within the file and where it gets imported. If you declare them within :root, they will be scoped, and only visible inside of it.
On the other hand, --data-color-primary and --data-color-secondary are CSS variables (also called custom properties). They can be inherited, so to have them available for each element, we declare them inside :root, which represents html element in the page.
Now, why do you have both of them? Well, there is no reason for that. You can simply do as below, the result you would get anyway after compilation:
:root{
  --data-color-primary: #ffcc00;
  --data-color-secondary: #4b4b4b;
}

A: This is SASS
$primary: #ffcc00;
$secondary: #4b4b4b;

This is pure CSS:
:root{
    --data-color-primary: #ffcc00;
    --data-color-secondary: #4b4b4b;
}

And this is a mix between the tow:
$primary: #ffcc00;
$secondary: #4b4b4b;

:root{
    --data-color-primary: #{$primary};
    --data-color-secondary: #{$secondary};
}

If you're already using SASS, you can implement the syntax you want. But if you want to use only pure CSS, then you're not allowed to use the $variables.
On the other hand, you don't need to write --data-color-primary: #{$primary}; in SASS, --data-color-primary: $primary; will do the same work.
If you're wondering which one is faster, well both are the same, because at the end, SASS will be compiled into CSS, which means that for the browser, there's nothing called SASS or compiled CSS, it's just pure css.

Something that could bring a big difference here (I think):
@media will not accept the :root variables as breakpoint for example, which means you can not write something like:
@media screen and (var(--break-point))
{...}

While if you're using SASS, you can use:
@media screen and ($break-point)
{...}


text:
Q: create excel file of database query result in php I create excel file using php.It has contain Query Result data from database.Excel file generate and download very well but when i opened i found it gives some format error and some coding error also.

function generate_excel($conn) {
 $filename = "website_data_" . date('Ymd') . ".xls";

 function cleanData(&$str) {
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if (strstr($str, '"'))
        $str = '"' . str_replace('"', '""', $str) . '"';
}

header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-type: application/octet-stream;charset=utf-8");

 $flag = false;
 $qry = "SELECT ContactId,UniqueContactId FROM Contacts ORDER BY ContactId  ";
 $stmt = sqlsrv_query($conn, $qry);
 $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);

while (false !== ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))) {
    if (!$flag) {
        // display field/column names as first row
        echo implode("\t", array_keys($row)) . "\r\n";
        $flag = true;
    }
    array_walk($row, 'cleanData');
    echo implode("\t", array_values($row)) . "\r\n";
}
exit;
}

A: sqlsrv_fetch_array() can return either NULL or FALSE. You can make your while statement as follows:
while (NULL !== ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))) {
    if(!$row)
        break ;

    //...
}

Here's PHP function reference: http://php.net/manual/en/function.sqlsrv-fetch-array.php


text:
Q: GSheet Appscript unsuccessful loops output I successfully created two functions which are to build data report in my template based on a certain data (invoice) and to auto-download the report as a PDF file.
But when I tried to loop those functions because I have many invoices to be downloaded as pdf files. This is my function:
function downloadNota() {
  var ws = SpreadsheetApp.getActiveSpreadsheet();
  var xs = ws.getSheetByName('Print Nota');
  var lr = xs.getLastRow();
  var nota = xs.getRange('B2:B' + lr).getValues();
  var number = nota.map(function (r) { return r.toString().replace('\[ | \]', '') });
  number.forEach(function (invoice) {
    printInvoice(+invoice)
  });
  downloadPdf(noInvoice)
}

But when I run the function, data in the template become blank (image attached).

Here is my function to fill the data in my template:
function printInvoice(noInvoice) {
  var ws = SpreadsheetApp.getActiveSpreadsheet();
  var ss = ws.getSheetByName('NOTA INVOICE2');
  var dd = ws.getSheetByName('GABUNGAN');
  ss.getRange('B10').setValue(noInvoice);
  ss.getRange('A14:G120').activate();
  ss.getActiveRangeList().clear({ contentsOnly: true, skipFilteredRows: true })
    .setBackground(null)
    .setBorder(false, false, false, false, false, false)
    .setFontWeight(null)
    .setFontColor(null)
    .breakApart();
  var allData = dd.getRange('A5:S').getValues();
  var dataString = allData.filter(String);
  var listData = dataString.map(function (r) { return r; });
  var neededData = listData.filter(listData => listData[2] === noInvoice);
  var nData = neededData.length;
  var data = [];
  if (!neededData) return;
  for (var i = 0; i < nData; i++) {
    newData = [neededData[i][5], neededData[i][6], neededData[i][8], neededData[i][9], neededData[i][7], (neededData[i][8] - neededData[i][9]) * neededData[i][7]];
    data.push(newData);
  }
  ss.getRange(14, 6, nData, 2).mergeAcross();
  ss.getRange(14, 1, nData, 7).activate();
  ss.getActiveRangeList()
    .setBorder(true, true, true, true, true, true, '#000000', SpreadsheetApp.BorderStyle.SOLID)
  ss.getRange(14, 1, nData + 8, 7).activate();
  ss.getActiveRangeList()
    .setHorizontalAlignment("right");
  ss.getRange(14, 1, nData, 2).activate();
  ss.getActiveRangeList()
    .setHorizontalAlignment("center");
  ss.getRange(14, 5, nData, 1).activate();
  ss.getActiveRangeList()
    .setHorizontalAlignment("center");
  ss.getRange(14 + nData + 1, 2, 4, 1).activate();
  ss.getActiveRangeList()
    .setHorizontalAlignment("left");
  ss.getRange(14 + nData + 5, 1, 1, 7).activate();
  ss.getActiveRangeList().setBorder(true, false, false, false, false, false, '#000000', SpreadsheetApp.BorderStyle.SOLID);
  ss.getRange(14, 1, nData, 6).setValues(data);
  ss.getRange(14 + nData + 2, 1).setValue('Status Pengiriman:');
  ss.getRange(14 + nData + 2, 2).setValue('SUDAH DIKIRIM');
  ss.getRange(14 + nData + 3, 1).setValue('Status Pembayaran:');
  ss.getRange(14 + nData + 3, 2).setValue('PAID');
  ss.getRange(14 + nData + 1, 6).setValue('SUBTOTAL :');
  ss.getRange(14 + nData + 1, 7).setFormulaR1C1("=SUM(R[-2]C[-1]:R[-" + (nData + 1) + "]C[-1])");
  ss.getRange(14 + nData + 2, 6).setValue('DPP :');
  ss.getRange(14 + nData + 2, 7).setFormula('=VLOOKUP(B10,{GABUNGAN!C5:C,GABUNGAN!Q5:Q},2,false)');
  ss.getRange(14 + nData + 3, 6).setValue('PPN (11%) :');
  ss.getRange(14 + nData + 3, 7).setFormula('=VLOOKUP(B10,{GABUNGAN!C5:C,GABUNGAN!R5:R},2,false)');
  ss.getRange(14 + nData + 4, 6).setValue('BIAYA PENGIRIMAN :');
  ss.getRange(14 + nData + 4, 7).setFormula('=VLOOKUP(B10,{GABUNGAN!C5:C,GABUNGAN!N5:N},2,false)');
  ss.getRange(14 + nData + 5, 6).setValue('GRAND TOTAL :');
  ss.getRange(14 + nData + 5, 7).setFormulaR1C1("=SUM(R[-2]C[0]:R[-4]C[0])");
  ss.getRange('B10').activate();
}

Here is what I hope to get as a PDF file downloaded:

A: Rewrite the entire function without using activeRange or activate().
exp :
ss.getRange(14, 1, nData + 8, 7).activate();
  ss.getActiveRangeList()
    .setHorizontalAlignment("right");

REWRITE
var a = ss.getRange(14, 1, nData + 8, 7);
      a.setHorizontalAlignment("right");


text:
Q: Silverstripe 3 wrong sort with special chars (umlauts) Silverstripe 3.6
When trying to sort an ArrayList by a field that starts with special chars - german umlauts in my case - the result is no "natural sort"
Example:
$arrayList  = ArrayList::create(array(
  ArrayData::create(array('Title' => 'Ccc')),
  ArrayData::create(array('Title' => 'Zzz')),
  ArrayData::create(array('Title' => 'Ööö')),
  ArrayData::create(array('Title' => 'Aaa')),
  ArrayData::create(array('Title' => 'Rrr')),
  ArrayData::create(array('Title' => 'Ooo')),
  ArrayData::create(array('Title' => 'Äää'))
));

Debug::dump($arrayList->column('Title'));
$sortedList = $arrayList->sort('Title');
Debug::dump($sortedList->column('Title'));

Result of the orginal list:
[0] => Ccc
[1] => Zzz
[2] => Ööö
[3] => Aaa
[4] => Rrr
[5] => Ooo
[6] => Äää

Result of the sorted List:
[0] => Aaa
[1] => Ccc
[2] => Ooo
[3] => Rrr
[4] => Zzz
[5] => Äää
[6] => Ööö

The expectation would be:
[0] => Aaa
[1] => Äää
[2] => Ccc
[3] => Ooo
[4] => Ööö
[5] => Rrr
[6] => Zzz

Using php5.6 with intl extension.
Any ideas, how to get this working ?


text:
Q: SO Blog Censorship and Mild Criticism I think this should be put out to the meta community. As everyone knows by now the SO blog, as well as others, experienced downtime because of a fault at the hosting provider. A lot of data was lost and had to be restored from non-traditional means. This is fine. Subsequently, a post was made on the SO Blog describing the failure and describing problems with the backup strategy as a whole.
Many users commented on the blog attempting to offer advice and so forth. Of course, this advice was met with complete and utter condescension, which, of course, is the right of the person being condescending. This was even directed at Joel when he provided simple common sense industry best practices for backup.
Essentially, Jeff's argument here was that having a disaster recovery plan was as foolish as planning for a lunar attack. All right, so at this point some decided just to chime and basically say "Hey, everyone makes mistakes but maybe there's some smart people here that are offering advice and maybe just listening is the best tactic."
So, basically I've noticed a few of these posts completely deleted with no mention or anything. I noticed then when I came back to the blog and noticed some good posts from other users were missing and then my last post was as well. These posts had no offensive language, did not rudely call anyone out (i.e. "you're a loser") or anything like that. These were just mild criticisms and my comments were essentially that everyone makes mistakes and we should just learn from what others have to say.
In fact, my original deleted comment was this:

Jeff, I really think you should just
  take a minute to listen to others.
  Honestly, if I had an employee that
  was partly or entirely responsible for
  losing a non-trivial amount of data
  and that employee's response included
  sarcastic jibber jabber about lunar
  attacks or any of this nonsense then
  he would be immediately terminated; it
  wouldn't matter if that employee was
  the lead developer or not.

It's not chocolates and strawberries but I think it's hardly worthy of deletion. It may seem like sour grapes but I think this is an important discussion for Meta since many of us have invested a lot of time in becoming members of the SO community. The SO blog and podcast is a part of that community.
It's just disrepectful to users and downright childish to have such a capricious attitude toward censorship. As well, to delete comments as if they never existed seems to suggest one is just attempting to hide the fact that censorship is occuring (there could be simply a "this post was deleted because I felt like it").
Also, there's no stated policy that no criticism is allowed on SO. It seems that it should be completely open that censorship is the bread and butter of the SO blog or it should not be going on at all.
What does Meta have to say?

A: The owner of a blog has every right to delete whatever he or she wants. Period.
The readers of a blog have every right to choose not to read the blog for any or no reason. One reason might be the author's attitude towards those who post responses.
It's a shame that Jeff chose to disregard and delete all that advice. He can do as he likes, though.

A: I felt your comment was not constructive criticism, and thus it was removed. You may disagree on the definition of "constructive", but it's our blog and our rules.
I also removed other comments that were not constructive.
Criticism and disagreement is welcome -- but if you can't do this in a constructive manner, then don't bother posting on the blog, because it will be removed.
If you don't agree with those rules, take it off site where you can be as Nasty As You Wanna Be, like 2 Live Crew. I find that kind of stuff boring in my advanced old age, but it is entertaining for some.

A:

A: Joel and Jeff have both been up front about the fact that their default method of dealing with comments they don't like is to delete and ignore (or in Joel's case hide from everyone else and ignore).  Don't be surprised when they practice what they preach.

A: The blog is not a public forum for discussion.  It's a platform, not unlike a soapbox, that helps them pass out information.  They allow on-topic feedback, but you don't have any right to force your opinions onto their platform.
If you have questions about backup practices, go visit serverfault.
Otherwise, respect Jeff's decision to prune anything from the blogs that he deems counterproductive to the goals of his blog post.

A: Give not that which is holy unto the blogs...
Seriously: this is why blogs are not a discussion medium. The blog author has the ability (and ever-present temptation) to simply remove any comment that makes him uncomfortable! Eventually, most blog authors fall into this trap, and only the sycophants remain...
If you have something worth saying, get your own soapbox. No one takes blog comments seriously anyway.

A: I upvoted your question because you make some really good points and I do think it's important to call people to task on excessive reaction to legitimate criticism. However, I've also voted to close as the issue isn't (directly) Stack Overflow related: Meta doesn't cover blog.stackoverflow.com.
However, perhaps it ought to, as the blog is an official voice of SO, and Joel is involved (e.g. the regular podcasts posted there that they both create).
It really would have been preferable if the discussion had taken place on codinghorror.com instead, which is quite clearly Jeff's own personal site and has nothing to do with Stack Overflow. Then he could have reacted in whatever manner he pleased and the community would have less of a case to question his response.


text:
Q: How to make a sequence of elements that can check if the one before it is active? This is extremely complicated to explain with words but I'm trying to make a system where I have one element (number 1 in the image) that stems of to another element. In some cases like element two it might stem of in two directions. I want to be able to activate these elements but only if an element linked to it is activated.

Example:
The element to the right of element two can now be activated but if element two wasn't active I would have to activate element one first.
I thought of using data-attributes and give them a number and check if a number before that was active, but the problem is when sometimes it divides into two, three or more. Is there any way I could achieve this? Any suggestion would be great I just can't come up with a way of detecting this condition, thanks in advance!
Additional info:
The basic idea is that there has to be a touching element active (dark blue) before you can activate that element. In the image below you can see two different ways of reaching element A, also looking at the dark blue lines you can see what other elements are now available for activating.

A: I'd recommend building a graph on page load, and then using this graph through the lifetime of the page to track what has been activated etc.
A basic node of your graph would look like this:
var node = {
   adjacent : [], // list of adjacent nodes (depending on your use case, you might not need this
   previous : prevNode, // previous node (for node2, it is node1)
   isActive : false,
   activate : function(){
       // code that checks previous and activates the current node
       // if previous is not active, it can call previous.activate()
       // which will then activate prevNode and its dependencies
   }
}