text:
Q: Следует ли коммитить в git промежуточные копии когда библиотека вообще не готова Я так понимаю система git служит для контроля версий библиотеки и т.п.
Но если стоит иная задача: промежуточные копии когда библиотека вообще не готова. Например, добавил класс, в нём несколько функций. Библиотека не готова, она не рабочая, но мне нужно сделать точку восстановления. (Скажем, я не уверен точно каким путём идти дальше, чтобы можно было вернуться к этому состоянию, или же просто резервная копия случай сбоя). Коммит делать, как мне кажется нецелесообразно, существуют ли другие пути для этой задачи?

A:
Коммит делать, как мне кажется нецелесообразно

Гит создан именно для того, чтобы делать коммиты и делать их часто. Можете воспринимать коммиты как сохранения в опасной стрелялке — вы можете сохраняться в каждой удобной ситуации, перед каждым углом и дверью. И не делайте из разработки рогалик, в котором ошибка приведет к тому, что нужно начинать всё заново. Только постарайтесь давать сохранениям осмысленные имена, иначе они будут бесполезны. Ограничивает вас только место на диске (которое расходуется довольно эффективно, там есть сжатие и переиспользование).

Скажем, я не уверен точно каким путём идти дальше, чтобы можно было вернуться к этому состоянию, или же просто резервная копия случай сбоя)

Резервная копия - каждый коммит является резервной копией.
git add <имена файлов и папок>
git commit -m'какое-то сообщение, отражающее суть коммита'

Посмотреть историю коммитов и выбрать какой-нибудь:
git log

Вернуться к нужному коммиту/состоянию:
git checkout <sha1 коммита>
git checkout <имя ветки>

Каким путем идти дальше — создаем ветку, она представляет собой альтернативный путь.
git branch new-branch-name

для контроля версий библиотеки

Когда ваша библиотека достигнет статуса релиза, можете сделать очередной коммит и отметить его тегом (tag)
git tag Release-1.0

A: Мой вариант работы - репозиторий лежит в интернете, работаю с нескольких мест. Коммиты до пуша хранятся локально, поэтому они больше для истории. Пуш в репозиторий в тестовую ветку в любом состоянии - чтобы при продолжении с другого места было доступно текущее состояние. В любом случае благодаря истории коммитов всегда можно вернуться на любой этап.
Но при этом вся разработка ведется в отдельной ветке, перед заливкой на боевой сервер рабочей версии - слияние с мастером, перед итоговым пушем в репозиторий дополнительный тест.
Правильная идеология - завести ветку testing, в которую коммит без ограничений, пуш по настроению, но слияние с мастером только работоспособной версии.
На возможной развилке можно создать новую ветку, потом победивший вариант вливается в testing, тестируется и уходит в мастер.
И как написал предыдущий докладчик - использовать тэги для отдельных вех.

A: Как раз еще для этого git и существует. Коммит - это сохранение локальных изменений, это не публикация. Вы в любой момент можете просмотреть историю коммитов и откатиться на нужный. По большому счету, коммит - это и есть "точка восстановления".
А можете сделать ветку, и в этой ветке работать над какой-то фичей. Переключаясь между ветками, получаете два варианта - код стабильный и код с фичей. После отладки можете слить и удалить ветку. Если не смогли заставить фичу работать, просто удаляете ветку и возвращаетесь к основной.


text:
Q: How would I separate a sentence into individual words with a loop and send them individually into an ArrayList in Java? I have a very specific problem for my CS course. I have a sentence in a string, and I need that separated into individual words within an ArrayList, and cannot use the split method.
The issue I have is that I have had zero teaching on arrays, only the bare minimum teaching for loops and String statements. I've done a lot of research and figured out the best way to go about making the loop, and sending the words to the ArrayList, however I still can't find a good way to actually have it loop through the sentence and separate each individual word at all. I get how easily it can be done to separate the very first word, however after that I get lost. I have no idea how to make the loop for its other iterations specifically grab the next word in the sentence after the one it previously got.
(Note: The only utilities imported are Scanner, File, HashMap, ArrayList, Random, and *)
What I'm looking for is any tips of specific methods I should try and employ or research. Or perhaps a set of code that is fairly functional in doing something similar to what I'm looking for that I can look at and build my own code off of.

A: When you said the word "word"(That's weird) I assume that they are separated by spaces. If you are reading in the inputs, then just use Scanner... Then:
Scanner input = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
for(int i = 0;i<numberOfWord;i++){
   words.add(input.next());// .next() method read data that are separated by space
}

or:
String theLineOfWord;//Given to you

StringTokenizer st = new StringTokenizer(theLinOfWord);//Used to separate words.
ArrayList<String> words = new ArrayList<String>();

while(st.hasMoreTokens()){
    words.add(st.nextToken();
}

or:
public static ArrayList<String> getWords(String line){
        ArrayList<String> words = new ArrayList<String>();
        line += " ";//add a space to ignore the ending case

        while(line.length() != 0) {
            words.add(line.substring(0, line.indexOf(' ')));//add the word to the list
            line = line.substring(line.indexOf(' ') + 1, line.length());//take out the useless string away
        }
        return words;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show Modal depending on the selected value in dropdown list I have a dropdown list
  <select class="select" name="mode" ng-model="modes.mode" ng-dropdown required  >
   <option ng-option value="modal1">Mode1</option>
   <option ng-option value ="modal2">Mode2</option>
   <option ng-option value="modal3">Mode3</option>
  </select>

And three different buttons
 <button class="action_delete" id="delete" ngmodel="button" ng-click="delete()">Delete</button>
 <button class="action_modify" id="modify" ngmodel="button"  ng-click="modify()">Modify</button>
 <button class="action_create" id="create" ng-model="button" ng-click="open()" >Add</button>

Now, what I want is to display modals on button click depending on the selected value in the dropdown list. Each mode has their own modals for button click. For example when the user selects mode1 and wants to add, the modal that will show is for mode1, add modal popup, for mode1, modify modal. If mode 2 has been selected, the modals will be for mode2, add modal; mode2, modify pop up and so on. How can I possibly do that? I'm using angularjs. Thanks for any help

A: You could simply define a modal template for each <option> value - modal1, modal2 ..

...

See also the plnkr, notice {{ action }}. Create a function that opens a modal using the template that corresponds to the selected value
$scope.showModal = function(action) {
  if (!$scope.modes.mode) return
  $scope.action = action
  $scope.modal = $uibModal.open({
    templateUrl: $scope.modes.mode+'.html',
    scope: $scope
  });
}

(using angular ui modals) Call showModal from the button ng-click handlers (action is just to demonstrate the template / button relationship)
$scope.delete = function() {
  $scope.showModal('delete')
}
...

But action can be useful in the mutual ok() and cancel() methods
$scope.ok = function() {
  //if ($scope.action == 'delete') { ... }
  $scope.modal.close();
}
$scope.cancel = function() {
  $scope.modal.dismiss();
}

Consider the above as a minimal skeleton for showing different modals that each can be activated by different buttons.
See demo -> http://plnkr.co/edit/LYOEntdgLbONNAzH0Ove?p=preview


text:
Q: self killing shell script I'm trying a simple test to kill a script from within its self.  It doesn't seem to be working.
function testKill
{
  PID=$$
  kill $PID
  echo  hello!
}

When I run this function,
[....]$ testKill
hello!

It clearly doesn't kill the process.  How do I make the process terminate before sending the echo command?
When I move this all into an external script, it terminates correctly if I call the script directly from the command line. However, if I make a function inside my .bash_profile and call the script from within that function, the script isn't killed and it prints instead. How do I integrate it into my .bash_profile?
This is a minimal working example to use in a more complicated script.

A: You haven't written a script in your example; it's a function. You're therefore applying the kill to your interactive shell session. Interactive shells ignore most signals, including the SIGTERM that you're sending.
Put the function and its call in a script and run that. It's far more likely to do what you expect.

A: try following, if you want to use it as function directly in bash, respectively sourced from console.
function testKill
{
  kill $PPID
  echo  "no hello :-/"
}


text:
Q: Is this call-by-reference? I have an ArrayList:
ArrayList ReceivedPackets = new ArrayList();

And I have another ArrayList:
ArrayList returnList = ReceivedPackets;

Why does returnList loose it's value when I run this code?
ArrayList ReceivedPackets = new ArrayList();  // ReceivedPackets is empty
ReceivedPackets.Add(1);                       // Now it has an Integer
ArrayList returnList = ReceivedPackets;       // Call-by-Reference (I thought), returnList now has an Integer
ReceivedPackets.clear();                      // returnList is empty now. Why?

A: When you do this:
ArrayList returnList = ReceivedPackets;

You are creating a new variable called returnList, but this variable points to the same in-memory object as ReceivedPackets.  There is still only one actual ArrayList, it just has two variables pointing to it.  So changes made to one are reflected in both.

How can I do without returnList loosing it's value?

Create a new object.  At its simplest, that would look like this:
ArrayList returnList = new ArrayList();

If you also want that object to contain all the values from ReceivedPackets, fortunately ArrayList has a constructor overload which does just that:
ArrayList returnList = new ArrayList(ReceivedPackets);

Now you'd have two objects which should contain copies of the same data.  Changes to one would not be reflected in the other.

In the absence of that constructor, ArrayList also has some CopyTo() methods which can be used to copy elements from one to the other.  Failing that, you could also manually loop over the source ArrayList and copy elements to the destination ArrayList.
It's possible that this can get pretty confusing if the ArrayList itself contains reference objects.  Because those too may have multiple "pointers" to the same in-memory object.
For example, if you create a single Widget object and add it to two ArrayList objects, then any modifications made to the ArrayList objects (adding/removing elements) would be independent, but any modification made to the Widget object would be reflected in both ArrayLists.
The point is that the ArrayList itself is an object, independent of the objects it contains.
So, depending on the full context of what you're doing, your mileage may vary.

A: ArrayList is a reference type, meaning that if you simply assign some variable to an instance of it, both objects will point to the same location in memory.
If you want to create deep copy, create a new object.
static void Main() {
    ArrayList a = new ArrayList() {1,2,3};
    var b = a;
    var c = new ArrayList(a);

    a.Clear();
    Console.WriteLine(a.Count); // 0
    Console.WriteLine(b.Count); // 0
    Console.WriteLine(c.Count); // 3
}


text:
Q: How do I navigate once I submit a form and receive a status of 200 I am confused about how to navigate away from a form route in view to another route, once my data has been submitted successfully.
I found this example.
Which seems like it should work, but it's a bit unclear on the Vue router side, can I instantiate a new Vue router in any component if I have a routes component already. Anyway, it seems to get the status but it doesn't push the route.
My Method:
methods: {
  handleSubmit(event) {
    const router = new VueRouter();
    axios.post(API_ENDPOINT,
    this.itemInit,
    { headers: {
      'Content-type' : 'application/json',
       }
    }).then(response => {
        this.results = response.data.results;
        if(response.status == 200) {
          router.push('/');
        }
    }).catch(error => {console.log(error)});
  }
}

I am expecting to have it navigate to the root route when I get a status 200 from the server, which I am and everything works fine, just not getting this navigation.
Update: This worked for me.
methods: {
  handleSubmit(event) {
    const router = new VueRouter();
    axios.post(API_ENDPOINT,
    this.itemInit,
    { headers: {
      'Content-type' : 'application/json',
       }
    }).then(response => {
        this.results = response.data.results;
        if(response.status == 200) {
          this.$router.push('/');
        }
    }).catch(error => {console.log(error)});
  }
}

A: Assuming you are building a single page app in your entry point (usually main.js)
You would do something similar to the following:
import Vue from 'vue'
import { router } from '@/plugins/vue-router' // This is where you declare your routes

and when you initiate your app you will have something like:
new Vue({
  el: '#app',
  router,
  template: '<App/>'
})

Now in your component you would need to update your code to:
methods: {
  handleSubmit(event) {
    axios.post(API_ENDPOINT,
    this.itemInit,
    {
      headers: {
        'Content-type' : 'application/json',
      }
    }).then(response => {
      this.results = response.data.results;
      if(response.status == 200) {
        this.$router.push('/');
      }
    }).catch(error => {console.log(error)});
  }
}


text:
Q: atheros ar5bmd22 wifi drivers I have >120mb BB connection, via wifi on windows i get around 90+mb connection.
I have an Asus RT-N66U Dark Night router, like i said on all other devices i have no issue. But using ubuntu 12.10 on my ultrabook i'm lucky if i get +10mb and the connection is very temperamental.
Even simple actions like updating take an age to do via wifi.
Any advice would be greatly appreciated.

A: Can you run this command and put the result?
sudo lshw -class network
Also, what computer are you using?


text:
Q: Return a DTO Object in spring data repository method annotated with @Query I have a Repository  and in this interface I have a method that would like to return a ComentarioEditalDto instead of an ComentarioEdital, but when I call this method an exception is thrown, telling me that I don't have a Converter, how can I convert to return a instance of another class?.
import br.edu.ifrn.rederenova.dto.ComentarioEditalDto;
import br.edu.ifrn.rederenova.model.ComentarioEdital;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface ComentarioRepository extends CrudRepository<ComentarioEdital, Long>{

    @Query(value = "SELECT c.id, c.texto, c.data_ultima_edicao, c.autor_id, " +
           "c.data_criacao, c.edital_id, c.excluida FROM comentario_edital c INNER JOIN edital e ON e.id = c.edital_id " +
           "WHERE (c.excluida = FALSE OR c.excluida IS NULL) AND e.numero = :numero ORDER BY c.data_criacao DESC",
            nativeQuery = true)
    public List<ComentarioEditalDto> findAllByEdital(@Param("numero") String nuEdital);

}

I removed Gets and Sets
import br.edu.ifrn.rederenova.model.ComentarioEdital;
import br.edu.ifrn.rederenova.model.Edital;
import br.edu.ifrn.rederenova.model.Usuario;
import java.util.Calendar;
import java.util.List;

public class ComentarioEditalDto {

    private Long id;
    private String texto;
    private Calendar dataCriacao;
    private Calendar dataUltimaEdicao;
    private List<ComentarioEdital> respostasComentario;
    private Usuario autor;
    private Edital edital;
    private Boolean excluida;

}

I removed Gets and Set
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;

@Entity
@SequenceGenerator(allocationSize = 1, initialValue = 1, name = "comentario_seq", sequenceName = "comentario_seq")
public class ComentarioEdital implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "comentario_seq")
    private Long id;
    @NotBlank(message = "Não deve estar vazio")
    private String texto;
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private Calendar dataCriacao;
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private Calendar dataUltimaEdicao;
    @OneToMany(cascade = {CascadeType.REMOVE, CascadeType.REFRESH}, fetch = FetchType.EAGER)
    @JoinTable(name = "respostas_comentario",
                joinColumns = @JoinColumn(name = "pergunta_id"),
                inverseJoinColumns = @JoinColumn(name = "resposta_id"))
    private List<ComentarioEdital> respostasComentario;
    @ManyToOne(fetch = FetchType.EAGER)
    private Usuario autor;
    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    private Edital edital;
    @JsonIgnore
    private Boolean excluida;
}

A little of the exception

org.springframework.core.convert.ConverterNotFoundException: No
  converter found capable of converting from type
  [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap]
  to type [br.edu.ifrn.rederenova.dto.ComentarioEditalDto]  at
  org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321)
  ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]    at
  org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194)
  ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]

A: You need to return a dto in your @Query
@Query(value = "SELECT new br.edu.ifrn.rederenova.dto.ComentarioEditalDto(c.id, c.texto, c.dataCriacao, c.dataUltimaEdicao, c.excluida) " +
        "FROM ComentarioEdital c ....

*

*don't write a native query, you can use a JPQL

*use SELECT new package.DTOClass as SELECT new br.edu.ifrn.rederenova.dto.ComentarioEditalDto

*in your ComentarioEditalDto define a constructor with the same parameters you are passing to your SELECT new br.edu.ifrn.rederenova.dto.ComentarioEditalDto

A: First of all do not remove getter/setters of your POJOs.
Second if you want to return a custom object from your repository I recomed you to use QueryDSL. You can use it like this:
Repository:
@Repository
public interface EntityRepository extends JpaRepository<Entity, Long>, EntityRepositoryCustom, QuerydslPredicateExecutor<Entity> {
}

Custom repository:
public interface EntityRepositoryCustom {
    List<EntityDTO> getEntityDTOsByCriteria(String arg0, String args1);
}

Repository impl:
public class EntityRepositoryImpl implements EntityRepositoryCustom {

    @Autowired
    private CardHolderRepository cardHolderRepository;

    @Autowired
    private EntityManager entityManager;

    @Override
    public List<EntityDTO> getEntityDTOsByCriteria(String arg0, String args1) {
    final List<EntityDTO> projections = new JPAQuery(entityManager, jpqlTemplates)
                    .from(entity)
                    .orderBy(entity.somefield.asc())
                    .list(ConstructorExpression.create(EntityDTO.class, entity.somefield,
                                    entity.someOtherfield));
    return projections;
}

A: Just change the class ComentarioEditalDto to an Interface, like this:
public interface ComentarioEditalDto {

    BigInteger getId();
    String getTexto();
    Calendar getDataCriacao();
    Calendar getDataUltimaEdicao();
    List<ComentarioEdital> getRespostasComentario(); --> attention to this ComentarioEdital
    Usuario getAutor();
    Edital getEdital();
    Boolean isExcluida();

}


text:
Q: How to use Collections.shuffle() to shuffle an ArrayList in SSJS? I need to shuffle/randomize the contents of an ArrayList.  I was excited to discover Collections.shuffle() but unlike other Java maps/lists/collections it appears the Collections class is not direclty available to my XPages SSJS code.  Is there a way to import/reference the Collections class for access to its shuffle() method?
Here is my current code:
var numbersArrayList = new java.util.ArrayList;
for (i=1; i<=10; i++) {
    numbersArrayList.add(i)
}
dBar.dump(numbersArrayList);

Collections.shuffle(numbersArrayList);

dBar.dump(numbersArrayList);

And here is the error indicating the Collections class cannot be found:
This file is encoded using UTF-8. Please set your editor/viewer options appropriately
10/29/20 6:22 AM: Exception Thrown
Context Path: /TravelTrackPaul2.nsf
Page Name: /resetData.xsp
Control id: button6
Property: onclick
Script interpreter error, line=8, col=13: [ReferenceError] 'Collections' not found
     6:
     7: Collections.shuffle(numbersArrayList);
->   8:
     9: dBar.dump(numbersArrayList);

A: Call the method using the complete package name:
java.util.Collections.shuffle(numbersArrayList);


text:
Q: How to get download file from Laravel 5.1 with AngularJS and ui-router I have this code in laravel for export excel:
public function export_excel(Request $request){
    $user = user::all();
    Excel::create('user', function($excel) use($user) {
        $excel->sheet('Sheet 1', function($sheet) use($user) {
            $sheet->fromArray($user);
        });
    })->download('xls');
}

and my route is:
Route::get('user/export/excel','UserController@export_excel');

and my html is:
 Export to Excel

I want to send request from REST API with Restangular and after that get download file.

A: I solved problem with this:
this.downloadExcel = function(){
        Restangular.one('user/export/excel').withHttpConfig({responseType: 'blob'}).get().then(function(response) {
             var url = (window.URL || window.webkitURL).createObjectURL(response);
             window.open(url,"_self");
        })
    }

A: You can simple use the href attribute

    Export to Excel


text:
Q: Can ZFC be taken as the foundation of mathematics without first-order logic? On the wikipedia page for ZFC:
link
It says that ZFC is formally a theory in logic. And I guess all of mathematics relies on logic, but we use logic informally when creating mathematical arguments.(This seems to be done in all textbooks.)
Does this mean that mathematics can live or exist without formal logic? As have been said on this site mathematics existed before formal logic. So is it correct to say that we can build up analysis, algebra etc., with ZFC and logical arguments, but not using formal first order logic?

A: Norman Megill addresses this here:
http://us.metamath.org/mpeuni/mmset.html#axioms

Note. Books sometimes make statements like "(essentially) all of mathematics can be derived from the ZFC axioms." This should not be taken literally—there's not much you can do with those 7 axioms by themselves! The authors are assuming that you will combine the ZFC axioms with logic (that is, the axioms and rules of propositional and predicate calculus). Between ZFC axioms and logic there is a total of 20 axioms and 2 rules in our system.

If you start working with these it quickly becomes clear that you need the logic axioms to do much of anything.


text:
Q: Python code to create list from a file I have a dictionary file.txt, with 3 - 5 words in each line.
Like:
apple ball back hall
hello bike like

I need a python code to put all these words into a list before any other coding occurs.
My idea is to read the file line-by-line, and use split(), and list.append() functions, but I don't seem to sort it out. Can anyone help?
Edited: Said it the wrong way, sorry!

A: You can do something like:
file_list = []
with open('file.txt', 'r') as file:
    for line in file.readlines().rstrip('\n'):
        for word in line.split(' '):
            file_list.append(word)

If file.txt has the following contents:
apple ball back hall
hello bike like

The output would be:
>>> file_list
['apple', 'ball', 'back', 'hall', 'hello', 'bike', 'like']


text:
Q: Dynamic Mouse hover images using php and javascript The hover event on an image should show it on a fixed div. How can i achieve this ?
For example : In flipkart if there is particular product and they give color variation for that product, when we hover on color variation we can see that color product.
If their is blue color option available for bag, we hover on blue box and then blue bag image appears.

A: Try this:

*

*Save the url of img in Javascript

*Add a data-color attribute to the elements

*Use hover event

$("div.color").hover(function() {
  var color = $(this).attr("data-col");
if (color == "blue"){
  $("#box").html("");
}
if (color == "red"){
  $("#box").html("");
}
if (color == "green"){
  $("#box").html("");
}
if (color == "yellow"){
  $("#box").html("");
}

});
.color {
heigth: 50px;
 width: 50px;
  border: solid 1px black;
  display: inline-block;
}
#box {
height:300px;
  width:300px;
    border: solid 1px black;
 margin-top:20px;
}

blue

red

green

yellow

A: BASIC CSS
.clearfix:after {
  content: ".";
  display: block;
  width: 100%;
  height: 0px;
  visibility: hidden;
  clear: both;
}

#prod-image-container {
  border: 1px solid #CCC;
  width: 600px;
  height: 400px;
}

#prod-images {
  list-style: none;
  margin: 0;
  padding: 0;
}

#prod-images li {
  display: block;
  float: left;
  width: 50px;
  height: 50px;
  border: 1px solid #CCC;
  margin: 0 4px 4px 0;
}

HTML

Using jQuery

Quick little fiddle: https://jsfiddle.net/adrianopolis/ast16g7t/


text:
Q: Session missmatch in ADFS I use an ADFS STS to log into my application.
Roles and users are working properely most of the time, but on somes pages, I get some users mismatch : suddenly, the username on the up right corner of the screen is not the right one (it's another user that is logged in at the same time).
Do you have any clue of what I should check ?
Thanks.

A: ** comment moved into an answer **
First thought is caching and cache-variance. I'm thinking that that cache control is either not set, or set to public, and no other vary-bys means you could get a response from a different session.
If you're not setting private headers in your response, you should be explicit:
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Private);

There's a bunch of different ways to wrap e.g. attributes to make more MVC-like.
MSDN docs here:
http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cachecontrol.aspx


text:
Q: Remove comments from bundled js and css files I am using Cassette for Asp.Net to bundle and minify my js and css files. The issue is it leaves all the comments in file headers. I want to remove them since they contain some delicate information about the code for the development team.
I understand that it's for reference lines and License information protection, but that really should be disabled on demand (leaving the refence lines).
Is this possible? I am going through the documentation but couldn't find anything.


text:
Q: C: strange behavior of wrong initialization of array #include <stdio.h>
#include <stdlib.h>

int main() {
    int step;
    double position[4];
    position[0] = 1;
    for (step = 1;step<=4;step++){
        position[step] = 99;
    }
    return 0;

}

can compile without error and the resulting program can run.
However,
#include <stdio.h>
#include <stdlib.h>

int main() {
    int step;
    double position[3];
    position[0] = 1;
    for (step = 1;step<=3;step++){
        position[step] = 99;
    }
    return 0;

}

can compile also but the program cannot run: The error is Abort trap: 6.
In both cases above, the (wrongly) initialized array is of size one less than what I fill in the for loop. But why do 4 and 3 make a difference here?
Now, more interestingly,
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

int main() {
    int step;
    double position[4];
    position[0] = 1;
    position[1] = 99;
    position[2] = 99;
    position[3] = 99;
    position[4] = 99;
    return 0;
}

cannot even compile (Error is array index 4 is past the end of the array (which contains 4 elements). So why does for loop make a difference here?

A: In the third case, the compiler is alerting you of an out of bound access. The standard doesn't require it to complain but it does so.
For the first two cases there is no point in thinking what is happening. You said the first program runs fine. It doesn't - It has an UB.
For your question about how 3 & 4 changes anything, it could be dependent on how the stack frame is layed out. Due to alignment difference maybe the return address gets mucked in one case but doesn't in another. You will have to look at the generated assembly file to see what is actually going wrong.
This https://godbolt.org/g/gqz39q shows that in case where you set the array size to be 3 it is placing position at %rbp - 32 and step at %rbp - 4. So in case when you write position[3], step is being overwritten ( I don't want to think about what is being written).
When you make size of position to be 4, it places step at %rbp - 4 and position at %rbp - 48. Now you write to position[4] ie %rbp - 48 + 4 * 8 = %rbp - 16. This will write till %rbp - 8. So %rbp - 4 (step) is not changed.
Long story short, the padding saved you in case 1 but not in case 2.
PS: Again this is specific to the chosen compiler gcc 6.2 with O0 optimization level. The reason could be entirely different in your case.

A: There is nothing mentioned in the C language that stops you from writing a code that access out of bound memory, standard just clearly mentions that any attempt of doing so will causes undefined behavior.
Any diagnostic, if provided is at sole discretion of the compiler, maybe tied to the supplied compiler options, standard mentions no requirement of this.
For example, for some compiler, the last snippet compiles just fine (and receives runtime error, too).
Note 1: In the shown snippets, the statements are not initialization, they are assignments.
Note 2: I've modified the code a bit, but the invalid accesses made are same
#include <stdio.h>

int main(void) {
    //int step;             // remove unused variable warning
    double position[4];
    position[0] = 1;
    position[1] = 99;
    position[2] = 99;
    position[3] = 99;
    position[4] = 99;

    (void) position;          // suppress unused variable warning

    return 0;
}


text:
Q: Elliptic Operator Principal Part Inequality (Hints) I am looking to show the following estimate, for an elliptic PDO $P$ of order $m$ there is $K>0$, $R>0$ such that
$$\bigg|\sum_{|\alpha| \leq m}a_{\alpha}\xi^\alpha \bigg| \geq K|\xi|^m$$
for all $\xi$ with $|\xi| > R$. I have shown the result for the principal part $P_m(\xi)$ and was looking to use that, but I cannot figure out how to do it for the full expression. My main idea was to take
$$f(\xi) := \bigg|\sum_{|\alpha| \leq m}a_{\alpha}\xi^\alpha \bigg| - K|\xi|^m$$
and show that $f$ diverges to positive infinity as $|\xi|$ goes to $\infty$. This would mean that $f$ is bounded below, and also that it would eventually be positive which would give the result. Any hints on how to do any of this?

A: Here is an expanded version of the suggestion proposed in the comments by Hans Engler.
Consider any polynomial $Q(\xi) = \sum_{|\alpha| \le m} a_\alpha \xi^\alpha$ and note that $|Q(\xi)| \le \sum_{|\alpha| \le m} |a_\alpha| |\xi|^{|\alpha|}$.  Thus if we set
$$
b_k = \sum_{|\alpha|=k} |a_\alpha|,
$$
then we can bound
$$
|Q(\xi)| \le \sum_{k=0}^m b_k |\xi|^k.
$$
Now set $\beta = \sum_{k=0}^m b_k$.  If $|\xi| \ge 1$ then
$$
|Q(\xi)| \le \sum_{k=0}^m b_k |\xi|^k \le \sum_{k=0}^m b_k |\xi|^m = \beta |\xi|^m.
$$
On the other hand, if $|\xi |\le 1$ then
$$
|Q(\xi)| \le \sum_{k=0}^m b_k |\xi|^k \le \sum_{k=0}^m b_k \cdot 1 = \beta.
$$
Consequently,
$$
|Q(\xi)| \le \beta(1+|\xi|^m) \text{ for all } \xi \in \mathbb{R}^n.
$$
With this bound in hand we can apply it to your problem.  Write the symbol of your operator as $L = P + Q$ for $P = \sum_{|\alpha|=m} a_\alpha \xi^\alpha$ and $Q = \sum_{|\alpha| \le m-1} a_\alpha \xi^\alpha$.  You have already established that there exists $K >0$ such that
$$
|P(\xi)| \ge K |\xi|^m \text{ for all } \xi.
$$
Thus the triangle inequality tells us that
$$
|L(\xi)| = |P(\xi) + Q(\xi)| \ge |P(\xi)| - |Q(\xi)| \ge K |\xi|^m - \beta(1+|\xi|^{m-1}).
$$
Now we just observe that for $|\xi| > R$ with $R$ sufficiently large we must have that
$$
\frac{K}{2} |\xi|^m - \beta(1+|\xi|^{m-1}) \ge 0,
$$
and so $|\xi| >R$ implies that
$$
|L(\xi)| \ge \frac{K}{2} |\xi|^m.
$$


text:
Q: PHP upload settings, max file upload and chunks My host is on a shared server so therefore i cannot change the php.ini.  My goal is to upload files of upto 100mb but the servers upload_max_filesize is set to 6mb which i cannot change..
My quetsion is, is it possible to bypass this by uploading in chunks using something like https://github.com/blueimp/jQuery-File-Upload?
Many thanks in advance.

A: Ok I've now figured it..
By default chunking is not enabled.. you have to enable it in the jquery options, here is the source to do that https://github.com/blueimp/jQuery-File-Upload/wiki/Chunked-file-uploads
For testing purposes i've changed my php.ini settings to accept only 1mb and i'm successfully loading files that surpass that max upload.


text:
Q: Save one form as well as generate a value in Outputid(primary key) which is in another form at a time? I've two forms  named

*

*Input form and its table name is Input (Fields :Input_id,Input_name,Output_id)

*Output form and its table name is Output(Fields :Output_id,Output_name)

I am going to First save the Input form so it must save the Input table data as well as  generate a data  as 1 (for next record 2, 3 ,4 and so on)
on output_ID(primary key) in the Output table at one time on click of save button.
so on click of one save buton(which is in Input form), Output id(primary key ) should generate in Output table
as well as it should be store in Input table as a foriegn key?
Is it possible to do such scenario?anyone reply

A: If I am not wrong , on click of save button you are going to send input name and output name to your api.
MySQL doesn't support multi-table insertion in a single INSERT statement
So in your API code you should first

*

*Save output name in Output_table.

*Get the id of the row of Output_table

*Write another query that will take this output_id and input name and save it to input table.

You should fill output table to link to Input table with output id


text:
Q: How to use CKEDITOR.tools.callFunction for specific instance I can use this code:
var OriginalFunction = CKEDITOR.tools.callFunction;
CKEDITOR.tools.callFunction=function(n,x)
{
  OriginalFunction(n, x);
  alert("Called From New function");
}

To add a javascript function beside the regular function of he CKeditor toolbar buttons. but i need to be able to add to a specific editor instance. so i tried:
var OriginalFunction = CKEDITOR.instances.editor1.tools.callFunction;
CKEDITOR.instances.editor1.tools.callFunction=function(n,x)
{
  OriginalFunction(n, x);
  alert("Called From New function");
}

But then the function i add don't work. is there another way to do that?
Thanks.

A: You should get an error (not "doesn't work" but a javascript error) because tools isn't a member of the editor instance.
You might want to use the afterCommandExec event instead.


text:
Q: find the position of a sequence within a series of sequences I am having an array formed by n elements, each one with 2 possible values: x or o. The possible combinations are ordered so, if for example n=3, they would line up (horizontally) like this:
o|x|o|o|x|x|o|x
 o|o|x|o|x|o|x|x
 o|o|o|x|o|x|x|x
(first column: all o, last column: all x).
For n=4 the combinations will be ordered like:
o|x|o|o|o|x|x|x|o|o|o|x|x|x|o|x
 o|o|x|o|o|x|o|o|x|x|o|x|x|o|x|x
 o|o|o|x|o|o|x|o|x|o|x|x|o|x|x|x
 o|o|o|o|x|o|o|x|o|x|x|o|x|x|x|x
For n=5:
o|x|o|o|o|o|x|x|x|x|o|o|o|o|o|x|o|x|x|x|x|x|o|o|o|o|x|x|x|x|o|x
 o|o|x|o|o|o|x|o|o|o|x|x|x|o|o|x|o|x|x|o|o|o|x|x|x|o|x|x|x|o|x|x
 o|o|o|x|o|o|o|x|o|o|x|o|o|x|x|x|o|o|o|x|x|o|x|x|o|x|x|x|o|x|x|x
 o|o|o|o|x|o|o|o|x|o|o|x|o|x|o|o|x|x|o|x|o|x|x|o|x|x|x|o|x|x|x|x
 o|o|o|o|o|x|o|o|o|x|o|o|x|o|x|o|x|o|x|o|x|x|o|x|x|x|o|x|x|x|x|x
And so on.
I now want, given an array, to know where in the sequence it falls. I.e., if I have x|o|x|o, I would like to have a formula that tells me "it's on the 7th position". Of course, once I have as input the array, I know n, and so also the maximum length of the possible combinations (2^n).
I tried assigning a value to the "x"s so that the sequence of combinations is respected and each one has a unique value (the sum of the "x"s). For doing this, I assigned each row of the matrix an increasing value (1, 2, 2.5, 2.75, 2.875, 2.9375, etc). The point is that the values of the columns, calculated in that way, don't distribute proportionally among themselves, and even less among series with different n. The only thing that seems to work (with error increasing after n=5) is the ratio among a certain array and the one with all x (for the same n).
Any suggestions or ideas?


text:
Q: How to publish An Azure function that connects to a storage account Just wondering what the best practice when it comes to deploying / publishing an azure function... that needs to connect to a database / storage account. I'm new to .net and new to azure ... so i apologize in advance for any noob question.
We have the following logic in a powershell deploy script for our azure function (HTTP Triggered):
#login with service principal
az login --service-principal --username $UID --password $PASSWD --tenant $TENANT --allow-no-subscriptions

#set the subscription we want to use
az account set --subscription $SUBSCRIPTION_ID

#create resource group
az group create -n $GRP_NAME -l $LOCATION

#create resources defined in JSON
az deployment group create --resource-group $GRP_NAME --template-file "./resources/azfnResources.json"

func azure functionapp publish $FN_APP_NAME --publish-local-settings -i --overwrite-settings -y

This is what our local.settings.json file looks like:
{
    "IsEncrypted": false,
    "Values":{
        "FUNCTIONS_WORKER_RUNTIME": "dotnet",
        "WidgetStorageQueue":"DefaultEndpointsProtocol=https;AccountName=asdfasdf;AccountKey=<key>;EndpointSuffix=core.windows.net"
    }
}

Problem
This type of an approach requires manual intervention.  We can just let this script run because... we have to update the connection string AFTER the resources in the azfnResources.json file have been created ... and BEFORE the functionapp publish command is triggered.
Question
Based on the documentation, it seems that the local.settings.json file needed when I want to debug / run my code locally ... and be able to connect to the backend storage. (which lives upstream).  Makes sense.
What is the best way to automate this script such that no manual work is needed to update the connection string after the storage account is generated from scratch?
Maybe we shouldn't use the local.settings.json file to publish?  Is Maybe we should just make that something the developer has to manually update on his / her own.

A: When publishing, your Azure Function should read settings from Azure Functions App Settings using environment variables.
You can find more information in the following links:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-how-to-use-azure-function-app-settings?tabs=portal#settings
https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library?tabs=v2%2Ccmd#environment-variables


text:
Q: How to Refactor this jQuery Fade in effect? I'm new to writing jQuery and wanted to get some help on how refactor something.. I'm trying to get elements to fade in sequentially on the page load. The effect works well, but it looks clumsy in the code. Can someone with more experience help me refactor this to be more efficient?
$('.home h1').delay(100).animate({
    opacity : '1'
}, 'slow');

$('.home h2').delay(250).animate({
    opacity : '1'
}, 'slow') ;

$('.home h3').delay(400).animate({
    opacity : '1'
}, 'slow');

$('.home hr').delay(550).animate({
    opacity : '1'
}, 'slow');

$('.homeimages > img').delay(900).animate({
    opacity : '1'
}, 'slow');

$('.homenav').delay(1000).animate({
    opacity : '1'
}, 'slow');

Thanks!

A: Try the following way:
var elements: {
    'selector': 100, // delay
    'selector2': 200 // delay
};

for( var selector in elements ) {
    $(selector).delay( elements[selector] ).animate({
        opacity : '1'
    }, 'slow');
}


text:
Q: LWC Fires on Change Event when Record Edit Form Picklist Fields are reset On my Lightning Page I am using a Record Edit Form with Input fields for Picklists and Text.
When any of the Input fields are changed the onchange Event Handler is firing the HandleChange Event.  This event updates Form Fields which show the Form Footer that contains Save and Cancel Buttons.
If the Cancel button is clicked this fires the HandleCancel event which Resets all of the Form Input Fields and Form Fiels (to hide the Footer).
This works fine for text fields however when I reset a Picklist field this is triggering the onchange Event Handler and therefore re-showing the Footer.
As a workaround I added  timeout in the resetFields event to delay running the Form Field updates
Is there a better way to manage this?
JS
import {LightningElement} from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

export default class Test extends LightningElement {
    recordId='a0203000002o7QJ';

    pendingChanges = false;
    showFooter = false;
    handleChange() {
        this.showFooter = true;
        this.pendingChanges = true;
            console.log('Handle Changes - Pending = ' +  this.pendingChanges);
    }

    handleSubmit(event) {
        this.template.querySelectorAll("lightning-record-edit-form").forEach((element) => {element.submit()});
            console.log('Submit ' + event.detail.id);
    }

    handleSuccess(event) {
        if(event.detail.id.match(RegExp(this.recordId + ".*"))){
            const evt = new ShowToastEvent({
                title: 'Saved!',
                message: 'This Work Experience record has been updated',
                variant: 'success',
                mode: 'dismissable'
            });
            this.dispatchEvent(evt);
            this.resetFields();
        }
            console.log('onsuccess event recordEditForm ', event.detail.id);
    }

    handleCancel(){
        this.resetFields();
    }

    resetFields(){
        const inputFields = this.template.querySelectorAll('lightning-input-field');
        inputFields.forEach( field => {
            field.reset();
        });
        setTimeout(() => {
            this.pendingChanges = false;
            this.showFooter = false;
        }, 750);
            console.log('Reset Fields - Pending Changes = ' + this.pendingChanges);
            console.log('Reset Fields - Show Footer = ' + this.showFooter);
    }

    handleError(event){
        const evt = new ShowToastEvent({
            title: 'Error!',
            message: event.detail.detail,
            variant: 'error',
            mode:'sticky'
        });
        this.dispatchEvent(evt);
    }
}

HTML
<template>
  <lightning-record-edit-form record-id={recordId} object-api-name="Match__c"
    onsuccess={handleSuccess} onerror={handleError}>
    <lightning-card title="Location">

                <lightning-input-field field-name="Relocation_Flexibility__c" onchange={handleChange}></lightning-input-field>
                <lightning-input-field field-name="Commute__c" onchange={handleChange}></lightning-input-field>

                <lightning-input-field field-name="RelocationContext__c" onchange={handleChange}></lightning-input-field>
                <lightning-input-field field-name="CommuteContext__c" onchange={handleChange}></lightning-input-field>

    </lightning-card>
    <template if:true={showFooter}>

        <lightning-button variant="nuetral" label="Cancel" onclick={handleCancel} class="slds-p-left_x-small"></lightning-button>
        <lightning-button variant="brand" label="Save" onclick={handleSubmit} class="slds-p-left_x-small"></lightning-button>

    </template>
  </lightning-record-edit-form>
</template>


text:
Q: ShowDialog box is always fullscreen in Flutter? I want to create a show dialog box that will act as a disclosure. The one that I've used now gives me a fullscreen dialog, which I don't want. I want it to take the least amount of space that is needed.
This disclosure should pop up immediately as soon as the app opens, therefore, I've added this in the init state. Can someone please tell me how to minimise the size?
The code is as below.`
  class LandingScreen extends StatefulWidget {
  static const routeName = "/landing_screen";
  @override
  _LandingScreenState createState() => _LandingScreenState();}

  class _LandingScreenState extends State<LandingScreen> {
       bool _introDone = false;

     @override
      void initState() {
       // TODO: implement initState
      super.initState();
      SharedPreferences.getInstance().then((value) {
        final introDone = value.getBool("introDone") ?? false;
        setState(() {
          _introDone = introDone;
        });
        !_introDone
            ? showDialog(
          barrierDismissible: true,
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text("DISCLOSURE"),
              content: Column(
                children: <Widget>[
                  const Text("This app collects location data to enable location tracking in order to provide location based reminders. This include collecting location data even when the app is running in the background. The data collected will be handled according to the terms of our Privacy notice"),
              ],
              ),
              actions: <Widget>[
                TextButton(
                    style: TextButton.styleFrom(primary: Colors.blue),
                    onPressed: () {},
                    child: const Text("GOT IT")),
              ],
            );
          },

        ):null;
      });

    @override
    Widget build(BuildContext context) {
      return Containter();
    }
  }

A: Your problem is in the Column widget. You have to changethe mainAxisSize to min.
builder: (BuildContext context) {
            return AlertDialog(
              title: const Text("DISCLOSURE"),
              content: Column(
                mainAxisSize: MainAxisSize.min, // <---
                children: <Widget>[
                  const Text("This app collects location data to enable location tracking in order to provide location based reminders. This include collecting location data even when the app is running in the background. The data collected will be handled according to the terms of our Privacy notice"),
              ],
              ),
              actions: <Widget>[
                TextButton(
                    style: TextButton.styleFrom(primary: Colors.blue),
                    onPressed: () {},
                    child: const Text("GOT IT")),
              ],
            );
          },


text:
Q: What does "head on back" mean? In a movie "Moana", there's this conversation between Moana and her gramma Tala:

Moana: It's time to put my stone on the mountain.
Tala: Okay! Well, then head on back! Put that stone up there.

Here, what does "head on back" mean?
I guess "head" here means "go". Then, can you say "go on back" instead of "head on back" here?
EDIT
For more context, here's a clip starting with the conversation above.

A: Your assumptions are correct - head can be treated as a verb, meaning to move in a specified direction. For example.

*

*After we got to the beach, we headed south.

*After work, we all headed to the pub.

*It's getting late, I think I'll head home.

... and to head on in this context simply means to continue on.
From that, we get head on back. Although it seems counterintuitive (and it is), head on back has become an idiomatic expression meaning to turn around and go back the way you came, or to some previous waypoint on your route.

*

*After the hike, I headed back home.

*I headed back down the river as the sun began to set.

*You should head back home before the sun sets.

Go on back could also be used in your example:

Well, then go on back! Put that stone up there.

It seems equally counterintuitive, but is also commonly used in this context.


text:
Q: Android: How to set List item checked? I have an android.R.layout.simple_list_item_multiple_choice with checkboxes an want so initiate some of them.
How can I do that?
I have the following code:
    private void fillList() {
    Cursor NotesCursor = mDbHelper.fetchAllNotes();
    startManagingCursor(NotesCursor);

    String[] from = new String[] { NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_BODY, NotesDbAdapter.KEY_CHECKED };

    int[] to = new int[] {
    android.R.id.text1,
    android.R.id.text2,
    //How set checked or not checked?
     };

    SimpleCursorAdapter notes = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, NotesCursor,
            from, to);
    setListAdapter(notes);

}

A: *

*Put the resource id of your checkbox in your row layout into the to array, corresponding to the NotesDbAdapter.KEY_CHECKED cursor in from array.

*Implement a SimpleCursorAdapter.ViewBinder.

*Have the ViewBinder.setViewValue() method check for when its called for the NotesDbAdapter.KEY_CHECKED column.

*When it is not the KEY_CHECKED column, have it return false the the adapter will do what it normally does.

*When it is the KEY_CHECKED column, have it set the CheckBox view (cast required) to checked or not as you wish and then return trueso that adapter won't attempt to bind it itself.  The cursor and corresponding column id is available to access query data to determine whether to check the checkbox or not.

*Set your ViewBinder in your SimpleCursorAdapter via setViewBinder()
Here's one of my ViewBinder implementations.  Its not for checboxes, rather its for doing some fancy formatting of a text view, but it should give you some idea for the approach:
private final SimpleCursorAdapter.ViewBinder mViewBinder =
    new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(
                final View view,
                final Cursor cursor,
                final int columnIndex) {
            final int latitudeColumnIndex =
                cursor.getColumnIndexOrThrow(
                        LocationDbAdapter.KEY_LATITUDE);
            final int addressStreet1ColumnIndex =
                cursor.getColumnIndexOrThrow(
                        LocationDbAdapter.KEY_ADDRESS_STREET1);

            if (columnIndex == latitudeColumnIndex) {

                final String text = formatCoordinates(cursor);
                ((TextView) view).setText(text);
                return true;

            } else if (columnIndex == addressStreet1ColumnIndex) {

                final String text = formatAddress(cursor);
                ((TextView) view).setText(text);
                return true;

            }

            return false;
        }
    };


text:
Q: Function does not return expected value, when max value returns NULL I have created function to return the max number from  data set, which works fine, if the data set exists ie., if MAX returns a VALUE.
If there is no matching data set I need to return a value of 0, but no matter what I try the retrieval either equals no value or I get the no data found.
Have tried when when no data found, when others and null values as below but cant get this function to return 0 if max value is not found ie., if MAX value returns NULL.
CREATE OR REPLACE FUNCTION OPC_OP.sitezone_msm
    (in_site_id AW_ACTIVE_ALARMS.site_id%TYPE
    ,in_zone_id AW_ACTIVE_ALARMS.zone_id%TYPE
    ,in_mod AW_ACTIVE_ALARMS.module%TYPE)

RETURN NUMBER
IS

v_msm NUMBER;
NULL_VALUES EXCEPTION;

BEGIN
    SELECT MAX(AW_ACTIVE_ALARMS.weight)
    INTO v_msm
    FROM AW_ACTIVE_ALARMS
    WHERE AW_ACTIVE_ALARMS.site_id = in_site_id
    AND AW_ACTIVE_ALARMS.zone_id = in_zone_id
    AND AW_ACTIVE_ALARMS.module LIKE in_mod||'%';

RETURN (v_msm);

EXCEPTION
    WHEN NULL_VALUES
    THEN
    RETURN 0;

END sitezone_msm;

Have spent an age playing with this but cant get desired results and suggestions much appreciated

A: Try this:
CREATE OR REPLACE FUNCTION OPC_OP.sitezone_msm
    (in_site_id AW_ACTIVE_ALARMS.site_id%TYPE
    ,in_zone_id AW_ACTIVE_ALARMS.zone_id%TYPE
    ,in_mod AW_ACTIVE_ALARMS.module%TYPE)

RETURN NUMBER
IS

v_msm NUMBER;

BEGIN
    SELECT COALESCE(MAX(AW_ACTIVE_ALARMS.weight),0)
    INTO v_msm
    FROM AW_ACTIVE_ALARMS
    WHERE AW_ACTIVE_ALARMS.site_id = in_site_id
    AND AW_ACTIVE_ALARMS.zone_id = in_zone_id
    AND AW_ACTIVE_ALARMS.module LIKE in_mod||'%';

RETURN (v_msm);

END sitezone_msm;

A: Try this NVL function is generally used for handling NULL values

CREATE OR REPLACE FUNCTION OPC_OP.sitezone_msm
    (in_site_id AW_ACTIVE_ALARMS.site_id%TYPE
    ,in_zone_id AW_ACTIVE_ALARMS.zone_id%TYPE
    ,in_mod AW_ACTIVE_ALARMS.module%TYPE)

RETURN NUMBER
IS

v_msm NUMBER;
--NULL_VALUES EXCEPTION; -- not required

BEGIN
    SELECT nvl(MAX(AW_ACTIVE_ALARMS.weight),0)
    INTO v_msm
    FROM AW_ACTIVE_ALARMS
    WHERE AW_ACTIVE_ALARMS.site_id = in_site_id
    AND AW_ACTIVE_ALARMS.zone_id = in_zone_id
    AND AW_ACTIVE_ALARMS.module LIKE in_mod||'%';

RETURN (v_msm);

EXCEPTION
    WHEN OTHERS
    THEN
    RETURN 0;

END sitezone_msm;


text:
Q: Lock screen orientation to Portrait - React Native Android Tried lock screen orientation to portrait. It is easier to use and better experience for the customer.
I find AndroidManifest.xml and added android:screenOrientation="portrait" to activity which is child of application.
This should work. But not. Any glue? Running app in Android via development server.


text:
Q: Losing ssh connection I have a CentOS server where I try running fail2ban & iptables (don't like firewalld so I installed the package "iptables-services").
Using iptables with the following rules in a script "/etc/init.d/iptables.rules" launched at startup:
#!/bin/sh

# flush all
iptables -t filter -F
iptables -t filter -X

# Deny i/o
iptables -t filter -P INPUT DROP
iptables -t filter -P FORWARD DROP
iptables -t filter -P OUTPUT DROP

# Established co
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# loopback
iptables -t filter -A INPUT -i lo -j ACCEPT
iptables -t filter -A OUTPUT -o lo -j ACCEPT

# ICMP
iptables -t filter -A INPUT -p icmp -j ACCEPT
iptables -t filter -A OUTPUT -p icmp -j ACCEPT

# SSH
iptables -t filter -A INPUT -p tcp --dport 2222 -j ACCEPT
iptables -t filter -A OUTPUT -p tcp --dport 2222 -j ACCEPT

Changed ssh port to 2222 in sshd_config but when I reboot I definitely lose ssh connection. Pretty sure I forgot something stupid but don't see what.
Have you an idea?


text:
Q: Simple question about combinations There is this problem I found in a book on combinations. It goes roughly like this:
There are 4 type A machines and 5 type B machines. Three of the machines are removed from the piles. What is the total number of possibilities that the result contains at least one A machine and at least one B machine?
The answer on the book was given as 1C4 * 2C5 + 2C4 * 1C5 = 70 total possibilities. However, the way I did it was by first enumerating the total methods of choosing one type A and one type B, i.e. 20 different methods, and then multiplying by 7, the number of machines left over after choosing 2. This results in an answer of 140, two times too much.
Why was my answer wrong?

A: Because if you choose $A_1$ and $B_1$ as the first 2, and later chose $A_3$ to be the last one, it is exactly the same as choosing $A_3$ and $B_1$ as the first 2, and later choosing $A_1$ to be the last one.
This also shows why you counted by twice as much, since every such sequence will be repeated twice.

A simple way to convince yourself, is to consider the scenario where there is 1 type A machine and 2 type B machines, and we want to choose 3 machines, at least 1 of each type. Clearly, there is only 1 way to do so. However, if we were to use your method, for the first 2 machines, there is 1 way to choose a type A machine, 2 ways to choose a type B machine, and finally there is 1 way to choose what's left. This will give $1 \times 2 \times 1$, which is not 1.


text:
Q: NextJS: Context API for storing and passing values I am building this project on NextJS where I want to build a shopping cart. For that, I decided to use useContext hook.
So basically what I did is pretty basic. Create a ShoppingCartContext, add a addToCart function which will push the data to store. But when I press the add to cart button it shows me that,

store.push is not a function.

edit: When I press the button first time, nothing happens. When I press it the 2nd time it gives the mentioned error.
I think I did some basic stuff wrong in the code which is why I am getting this error.
My context code
import {
  createContext,
  useCallback,
  useContext,
  useState,
  useEffect,
} from "react";

const ShoppingCartContext = createContext();

export function ShoppingCartContextProvider({ children }) {
  const [store, setStore] = useState([]);

  return (
    <ShoppingCartContext.Provider
      value={{
        store,
        setStore,
      }}
    >
      {children}
    </ShoppingCartContext.Provider>
  );
}

export function useShoppingCartContext() {
  const { store, setStore } = useContext(ShoppingCartContext);

  //function to push data to array
  const addToCart = (product) => {
    setStore(store.push(product));
  };

  return {
    store,
    setStore,
    addToCart,
  };
}

Where I called the button component to add data
import { useRouter } from "next/router";
import { useState } from "react";
import { useShoppingCartContext } from "../../context/CartContext";

const SingleProduct = ({ product, categories }) => {
  const { store, setStore, addToCart } = useShoppingCartContext();
  const router = useRouter();
  const breadcrumb = router.components["/shop/[[...category]]"].resolvedAs;

  const [count, setCount] = useState(0);
  const increment = () => {
    setCount(count + 1);
  };
  const decrement = () => {
    setCount(count - 1);
  };

  return (
    <>

        <Button
              onClick={() => {
                addToCart(product); // product is basically an object which holds all the info of the single product
              }}
            >
              Add to Cart
            </Button>
    </>
   )
}

my _app.js file
import "../styles/globals.css";
import { ChakraProvider } from "@chakra-ui/react";
import { ShoppingCartContextProvider } from "../context/CartContext";

function MyApp({ Component, pageProps }) {
  return (
    <ChakraProvider>
      <ShoppingCartContextProvider>
        <Component {...pageProps} />
      </ShoppingCartContextProvider>
    </ChakraProvider>
  );
}

export default MyApp;

please take a look at this.

A: For updating state which is array you need to do
setStore(store => [...store, product])

//OR

// make clone of store and then setStore
temp=[...store]
temp.push(product)
setStore(temp)

EXPLANATION OF CURRENT BEHAVIOUR

*

*In your case it's working 1st time as you have initialized store as [] empty array.

*And because it's an array it has .push() method.

*But [].push(val) will not return an array it will return the length of array.

*And therefore after 1st time store get's the value of numeric datatype which does not has .push() method.

Below you can see the result of .push() your self.

arr=[1,2,3] // length 3
console.log(`initial array`)
console.log(arr)
console.log(`spread operator + new val`)
console.log([...arr,5]) // spread operator + new val
console.log(`.push()`)
console.log(arr.push(5),"length=",arr.length) // .push() this will return length of the arr


text:
Q: Connect to MS SQL on a network with SQL Alchemy in Python using Windows Authentication I am trying to use pandas.read_sql_table to get data from MS SQL Server (the server is on a network).  I use Windows authentication to access the server.  Pandas read_sql_table takes a SQL Alchemy connection as an argument for "connection."  I am having a difficult time finding an example that combines:

*

*SQL Alchemy

*MS SQL Server

*DSN (the "preferred"
    specification according to SQL Alchemy)

*Windows authentication

I've consulted SQL Alchemy, which shows an example using SQL authentication, but not Windows authentication. http://docs.sqlalchemy.org/en/latest/dialects/mssql.html#connecting-to-pyodbc
Here are various options I have tried.  All return an error.
import pandas as pd
from sqlalchemy import create_engine
import pyodbc
# set some variables
dbname = 'mydbname'
schemaname = 'myschemaname'
servername = 'myservername'
tablename = 'mytablename'

sqlcon = create_engine('mssql+pyodbc://@' + servername)
#sqlcon = create_engine('mssql+pyodbc://' + servername + '/' + dbname)
#sqlcon = create_engine('mssql+pyodbc://' + servername)
#sqlcon = create_engine('mssql://' + servername + '/' + dbname + '?trusted_connection=yes')
#sqlcon = create_engine('mssql+pyodbc://' + servername + '/' + dbname + '?trusted_connection=yes')
mydataframe = pd.read_sql_table(tablename,con=sqlcon,schema=schemaname)

The error I get is this:

(pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver
  Manager] Data source name not found and no default driver specified
  (0) (SQLDriverConnect)') (Background on this error at:
  http://sqlalche.me/e/rvf5)

What is especially perplexing is the comment about no default driver being specified.  None of the examples refer to specifying a default driver when I use this DSN format.
I have consulted this example, which also fails for me: How do I connect to SQL Server via sqlalchemy using Windows Authentication?
I can connect fine with SSMS.  I'm using python 3.6.

A: I found a solution to my question.  Posting here for others' reference.
This code worked.  I wasn't able to avoid specifying a driver explicitly, though.
sqlcon = create_engine('mssql+pyodbc://@' + servername + '/' + dbname + '?driver=ODBC+Driver+13+for+SQL+Server')

A: If you are confused with driver version you can use below code
username=<username>
password=<password>
server=<servername> | <host:port>
database=<database>

#below code is with authentication
engine = create_engine('mssql+pyodbc://'+username+':'+password+'@' + server + '/' + database + '?driver=SQL+Server')
query = '''select * from <table>'''
result = engine.execute(query)

#below code is without authentication
engine = create_engine('mssql+pyodbc://@' + server + '/' + database + '?driver=SQL+Server')
query = '''select * from <table>'''
result = engine.execute(query)


text:
Q: find all common sequences of two list in python I want to find all the common sequences in two list.
for example:
list1 = [1,2,3,4,5,6,7,8,9]
list2 = [1,2,7,8,9,5,7,5,6]

I want output as:
matched_list = [[1,2],[7,8,9],[5,6]]

my code is below:
import difflib
def matches(first_string,second_string):
    s = difflib.SequenceMatcher(None, first_string,second_string)
    match = [first_string[i:i+n] for i, j, n in s.get_matching_blocks() if n > 0]
    return match

But I am getting the output as:
match = [[1,2] ,[7,8,9]]

A: If the output order is not important, a multi pass solution could do the trick. Every time you find a match, remove the sub-string/sub-lists from both the lists/strings.
Implementation
def matches(list1, list2):
    while True:
        mbs = difflib.SequenceMatcher(None, list1, list2).get_matching_blocks()
        if len(mbs) == 1: break
        for i, j, n in mbs[::-1]:
            if n > 0: yield list1[i: i + n]
            del list1[i: i + n]
            del list2[j: j + n]

Sample Output
>>> list(matches(list1, list2))
[[7, 8, 9], [1, 2], [5, 6]]


text:
Q: What's the use of "System version" in eclipse "Driver Definitions"? Eclipse Data Tools Platform has a "Driver Definitions" entry, where you can indicate the JDBC drivers you want to use. When adding one, the wizard asks you to select a "driver template" from a provided list. In my eclipse Neon Java EE version, the list contains, among others, [Name=Other Driver; System Vendor=Derby; System Version=10.2], and [Name=Other Driver; System Vendor=Derby; System Version=10.1]. I can't see a difference between these two templates, except that they end up with different indicated System Version as a result of the wizard (expectedly). However, in both cases (selecting the 10.2 line or the 10.1 line), when the wizard asks for a jar containing the driver, I use a jar containing the 10.10 version, so this indicated System Version is incorrect in both cases.
My questions are: how does eclipse use these version numbers? If it does not use them, why does eclipse bother displaying a list with different entries for different versions? Can I get problems if the version of the driver I use does not match the indicated one? Should I somehow tell eclipse the right version I use?

A: The system version is the supported (minimum) version of the target database. The definition of a higher version can contain new features, keywords, data types etc of that database version. In other words: improved/closer support for the database version you are targeting.
For example on of the differences between the Derby 10.1 definition and Derby 10.2 definition is the default length reported for blobs:
In 10.1:
<predefinedDataTypeDefinitions xmi:id="BINARY_LARGE_OBJECT_1" lengthSupported="true"
    defaultLength="1024" maximumLength="2147483647" primitiveType="BINARY_LARGE_OBJECT" jdbcEnumType="2004" javaClassName="java.sql.Blob">

In 10.2:
<predefinedDataTypeDefinitions xmi:id="BINARY_LARGE_OBJECT_1" lengthSupported="true"
    defaultLength="2147483647" maximumLength="2147483647" primitiveType="BINARY_LARGE_OBJECT" jdbcEnumType="2004" javaClassName="java.sql.Blob">

Sometimes there might be no difference at all, but a separate (identical) definition might be provided just to avoid confusion for users to indicate that version is supported, and to make it easier to add corrections/improvements at a later time for that specific database version if necessary.
In short: use the version that is closest (but lower than or equal to) the version you are targetting; in this case: use the 10.2 definition.


text:
Q: How to decode a base64 to string Swift I'm trying to get the readme data for a selected repository from the GitHub api. So, the "content" is the content of the readme file, but is a base64 type. I tried to convert it but when I'm running the app, I get a fatal error "Fatal error: Unexpectedly found nil while unwrapping an Optional value "
Code:
class DetailsViewController: UIViewController {
    var details: Item?
    var read: Readm?
    @IBOutlet weak var forksLabel: UILabel!
    @IBOutlet weak var starLabel: UILabel!
    @IBOutlet weak var readMeLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        forksLabel.text = "\(details!.forks_count)"
        starLabel.text = "\(details!.stargazers_count)"
        downloadJSON {
            return
        }
        readMeLabel.text = decodeBase64(word: read!.content) // <- here is the error

    }
    func downloadJSON (completed: @escaping () -> ()) {

        let url = URL (string: "https://api.github.com/repos/\(details!.full_name)/readme")
        URLSession.shared.dataTask(with: url!) { (data, response, error) in

            if error == nil {
                do {
                    print("ceva")
                    self.read = try JSONDecoder().decode(Readm.self, from: data!)
                    DispatchQueue.main.async {
                        completed()
                    }
                }catch {
                    print (error)
                }

            }
        }.resume()

    }

    func decodeBase64(word: String) -> String {
        let base64Decoded = Data(base64Encoded: word)!
        let decodedString = String(data: base64Decoded, encoding: .utf8)!
        return decodedString
    }

}

This is where the error is :
 readMeLabel.text = decodeBase64(word: read!.content)

EDITED:
super.viewDidLoad()

        forksLabel.text = "\(details!.forks_count)"
        starLabel.text = "\(details!.stargazers_count)"
        downloadJSON {
            if let content = self.read?.content {
                self.readMeLabel.text = self.base64Decoded(word: content)
                print(self.base64Decoded(word: content))

            }

        }

    }

    func base64Decoded(word: String) -> String? {
        guard let base64Data = Data(base64Encoded: word) else { return nil}
        let decodedData = String(data: base64Data, encoding: .utf8)
        return decodedData
    }

I have managed how to unwrap things, but now, my label is empty, I made a print statement and is nil. Anyone know why ?

A: As you have already an asynchronous completion handler use it!.
A single return statement is pretty pointless, move the line to assign the text into the closure.
And unwrap the value always safely, because an error could occur
downloadJSON {
    if let content = self.read?.content {
        self.readMeLabel.text = self.decodeBase64(word: content)
    }
}


text:
Q: Query an XmlDocument without getting a 'Namespace prefix is not defined' problem I've got an Xml document that both defines and references some namespaces. I load it into an XmlDocument object and to the best of my knowledge I create a XmlNamespaceManager object with which to query Xpath against. Problem is I'm getting XPath exceptions that the namespace "my" is not defined. How do I get the namespace manager to see that the namespaces I am referencing are already defined. Or rather how do I get the namespace definitions from the document to the namespace manager.
Furthermore tt strikes me as strange that you have to provide a namespace manager to the document which you create from the documents nametable in the first place. Even if you need to hardcode manual namespaces why can't you add them directly to the document. Why do you always have to pass this namespace manager with every single query? What can't XmlDocument just know?
Code:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(programFiles + @"Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\HfscBookingWorkflow\template.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);

XmlNode referenceNode = xmlDoc.SelectSingleNode("/my:myFields/my:ReferenceNumber", ns);
referenceNode.InnerXml = this.bookingData.ReferenceNumber;

XmlNode titleNode = xmlDoc.SelectSingleNode("/my:myFields/my:Title", ns);
titleNode.InnerXml = this.bookingData.FamilyName;

Xml:
  <?xml version="1.0" encoding="UTF-8" ?>
  <?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:Inspection:-myXSD-2010-01-15T18-21-55" solutionVersion="1.0.0.104" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
  <?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
  <my:myFields xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-01-15T18:21:55" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003">
  <my:DateRequested xsi:nil="true" />
  <my:DateVisited xsi:nil="true" />
  <my:ReferenceNumber />
  <my:FireCall>false</my:FireCall>

Update:
ns.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
ns.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");
ns.AddNamespace("xd", "http://schemas.microsoft.com/office/infopath/2003");
ns.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-01-15T18:21:55");

This does the job, but it mean's I have to hard code to this particular xml schema. This schema represents an infopath form template. In particular the my namespace url will be different for every form template so I really don't want to hardcode this. It would be nice to find a clean way to get this namespace from the xml without resorting to RegEx.
I was hoping that the XmlNamespaceManager would just sort of pick up the namespace definitions form the NameTable. I mean their in the Xml but I still have to define them.

A: ns.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
ns.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");
ns.AddNamespace("xd", "http://schemas.microsoft.com/office/infopath/2003");
ns.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-01-15T18:21:55");

This does the job, but it mean's I have to hard code to this particular xml schema. This schema represents an infopath form template. In particular the my namespace url will be different for every form template so I really don't want to hardcode this. It would be nice to find a clean way to get this namespace from the xml without resorting to Regex.
I was hoping that the XmlNamespaceManager would just sort of pick up the namespace definitions form the NameTable. I mean their in the Xml but I still have to define them.

A: Here is the answer to the "What can't XmlDocument just know?" question.
NameTable is just an optimization for storing names. It has actually nothing to do with namespaces.
And even if XmlNamespaceManager could infer all namespaces and prefixes from XML doc that won't help in general case because of XML namespaces nature, e.g. what would XmlNamespaceManager map "my" prefix in this case:
<root>
    <foo xmlns:my="blah"/>
    <foo xmlns:my="balh-blah-blah"/>
</root>

A: Have you defined "my" in the namespace-manager?
ns.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-01-15T18:21:55");

Or better - choose something that is unlikely to conflict. It does seem odd that it didn't pick it up from the name-table, though.

A: For me with InfoPath 2007 this solved the problem
static public XmlNamespaceManager GetNameSpaceManager(this XmlDocument document)
{
    XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(document.NameTable);

    xmlNamespaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    xmlNamespaceManager.AddNamespace("dfs", "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution");
    xmlNamespaceManager.AddNamespace("d", "http://schemas.microsoft.com/office/infopath/2003/ado/dataFields");
    xmlNamespaceManager.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-03-29T06:28:28");
    xmlNamespaceManager.AddNamespace("xd", "http://schemas.microsoft.com/office/infopath/2003");

    return xmlNamespaceManager;
}


text:
Q: How to separate links of images on the basis of content inside them in beautifulsoup4 I am new to BeautifulSoup4 and I am trying to fetch all image links from a site for eg.Unsplash but I only wan urls that contains word "photo" in there url eg.
https://images.unsplash.com/photo-1541892079-2475b9253785?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60
I don't want urls that contain word "profile" for eg.
https://images.unsplash.com/profile-1508728808608-d3781b017e73?dpr=1&auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
How can I do so I am using Pyhton 3.6 and urllib3 .

A: You can use this script as an example, how to filter the links:
import requests
from bs4 import BeautifulSoup

url = 'https://unsplash.com'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

for img in soup.find_all('img'):
    if 'photo' in img['src']:  # print only links with `photo` inside them
        print(img['src'])

Prints:
https://images.unsplash.com/photo-1597649260558-e2bd7d35f043?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format%2Ccompress&fit=crop&w=1000&h=1000
https://images.unsplash.com/photo-1598929214025-d6bb6167d43b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1599567513879-604247ea2bd3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1599366611308-719895c34512?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1598929214025-d6bb6167d43b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1599366611308-719895c34512?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1599567513879-604247ea2bd3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1598929214025-d6bb6167d43b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1599567513879-604247ea2bd3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1599366611308-719895c34512?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80

With urllib:
import urllib.request
from bs4 import BeautifulSoup

url = 'https://unsplash.com'
soup = BeautifulSoup(urllib.request.urlopen(url).read(), 'html.parser')

for img in soup.find_all('img'):
    if 'photo' in img['src']:
        print(img['src'])


text:
Q: ASP.MVC Windows Authentication HTTP Error 401. The requested resource requires user authentication I have an ASP.NET MVC application using windows authentication that I published by visual studio on a windows 2008 server.
But when I try to reach the application from a browser I have to authenticate I get the default authentication form to do this.
If I type my user name and password I can not reach my application but if I use the administration account the application will be displayed in the browser.
And other strange things... in the IIS server I select the application site and click basic settings.
I click on the test connection button I get the following error message:
"Invalid application path".
But if I click the connect as button and use the administration account the test is passed successfully.
Anybody can help me?
l.


text:
Q: Changing row font color of rows with vuejs and veuntify I need to change the row font color of a vuetify v-data-table.
I receive from my backend a set of rows and each row has a column called "color_status".
I have created a template to do it. But, the problem is that when executed it shows all fields.
I´d like to show only the fields of the header.
Is there a simple way to do it?
 <v-data-table
      :headers="headers"
      :items="fila"
      :options.sync="options"
      :server-items-length="total"
      :loading="loading"
      sort-by="nome"
      :items-per-page="5"
      :search="search"
    >
      <template v-slot:item="{ item }">

            {{ item[key] }}

      </template>
      <template v-slot:item.ativo="{ item }">
        <v-icon color="success">
          {{
            item.ativo.trim() == "T"
              ? "mdi-checkbox-marked"
              : "mdi-checkbox-blank-outline"
          }}
        </v-icon>
      </template>
      <template v-slot:no-data>
        <v-btn color="primary" @click="restart">Reiniciar</v-btn>
      </template>

      <template v-slot:item.nome="{ item }">
        <router-link :to="{ name: 'EditFila', params: { id: item.id } }">{{
          item.nome
        }}</router-link>
      </template>
    </v-data-table>

methods:{
    getColorStatus(item) {
      return item.color_status;
    }
}

A: Why don't you loop through headers instead of Objects ?

   {{ item[key] }}


text:
Q: Why did the Boltons burn Winterfell? At the end of Season 2/beginning of Season 3, Ramsay Bolton and his men burn Winterfell after the Iron Born (other than Theon) run away. But why?
If Roose Bolton was already planning his betrayal of the Starks, he knew he would be making a play for Winterfell so why burn his future castle?
And if Roose Bolton was not already planning his betrayal of the Starks, the burning is even more puzzling as it is treasonous to the King in the North.

A: You are correct Bolton was already planning that. Given Robb's constant blunders, He was certain that North was doomed to be defeated eventually and he didn't plan on being on the losing side. Jaime turning up at Harrenhal gave him the opportunity to pull his master-stroke, getting on the good side of Tywin Lannister.
There would be several reasons for burning however.

*

*Boltons weren't sure that their plan would work (Re: the Red Wedding). It was still a military plan and thing about military plans is that things rarely go according to the plan. Destroying Stark seat and stronghold would have been great in event of something backfiring and an open war with the Stark.

*Burning Winterfell helped them hide any possible evidence e.g. Dead bodies of all the Ironborn, their stuff, their banners, the bodies of all the witnesses and any survivors who maybe hiding somewhere which would have proved that unlike their story that Ironborn burnt the Castle, it was actually them who did that. (Evidently this failed as they did not take the Crypts into account or Godswood, both of which were used by the survivors).1

*Ramsay is a sadistic monster who just takes pleasure in misery of others. It would have amused him to see the Castle where he was imprisoned and kept as a servant to burn. He is the kind of person who would do it just for the heck of it.

*Stark-Bolton enmity goes back to thousands of years. Both claimed Kingship. Bolton Kings are said to have flayed many Stark Kings and worn their skins as cloaks. Eventually the Starks prevailed. This could be a payback for that defeat which reduced the Boltons from Kings to Lords. In any case, burning Winterfell is in line with the Bolton traditions. Kings Royce II and Royce IV Bolton did the same.

1. Many key logical factors like this one are missing from the Show due to their time and focus constraints. Which in turn gives birth to such questions by Show-fans. In the Books, Ironborn didn't abandon Theon. They were all killed by Ramsay. It was Ser Rodrik Cassel who had Winterfell and Ironborn besieged.
The Boltons attacked Cassel and killed him and his men. So given the size of massacre, it would have been evident something grand had happened. Therefore they needed to destroy the evidence and make it look like it was the Ironborn who did it. In the Show, they didn't show the Wex Pyke either. He was Theon's squire and hid in the God's Woods. He's the main source of how Northmen learnt that Bran was still alive and Boltons were in league with Freys and Lannisters. Plus it was Ramsay who later took it as his personal seat, not Roose Bolton.
 Seat of House Bolton remained Dreadfort. Ramsay claimed Winterfell for his own by virtue of his marriage to Arya Stark.


text:
Q: AppCompat Navigation Drawer not letting me to focus any EditText I am creating an application for pre-L (exactly API 9+) devices using AppCompat support library.
The problem I have is related to AppCompat's Navigation drawer: if I have a drawer in my layout and I am initializing it, none of the EditText elemenets in my fragments cannot be focused (they are getting fosus for a split-second, and then they lose it; the soft-keyboard is not showing up).
I am using only an activity into which I load fragments:
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/toolbar"/>

    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:foreground="?android:windowContentOverlay">

        <View
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:background="@drawable/toolbar_shadow"/>

        <FrameLayout
            android:id="@+id/app_fragment"
            android:layout_below="@id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/scan_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_margin="16dp"
            android:clickable="true"
            android:src="@drawable/ic_scan"
            app:borderWidth="0dp"
            app:elevation="4dp"/>

    </RelativeLayout>

</LinearLayout>

<include layout="@layout/drawer_content"/>

I tested the code without initializing the drawer and everything is working fine. Any idea what could be causing this problem?

A: So I found what was the issue. I don't know why, probably because the touch event was going trough the drawer, I had in my code this line which was disabling any events on everything under DrawerLayout:
    drawer.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);


text:
Q: how to consume a RESTful web service as a jar in JAVAEE I have a RESTful web service developped using (Spring-Java)
and it is a JAR file
I have created a Java EE web app that must consume this web service (using Eclipse)
running on WildFly9
How can I do to run the web service (JAR file) so that the web app can consume it ?


text:
Q: Having some trouble with my webpack config, and I think I am confused by the directory structure I am using I am trying to learn webpack, and I think I am confused by __dirname and getting the right entry file to work.  Basically, the file I want to use is in app/index.js, and my server.js and webpack.config.js are in config/.
I had this working fine when I had kept server.js and webpack.config.js in the root, but I want to move it into a config folder, and I also added an app folder instead of keeping the contents of the app as it is right now in the root.
I have the following file structure:
.
|++[app]
|----[actions]
|----[modules]
|----[reducers]
|----[store]
|----index.html
|----index.js
|--[config]
|----server.js
|----webpack.config.js
|--[node_modules]
|--package.json

I have the following in my server.js:
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var config = require('./webpack.config');
var path = require('path');
var app = new (require('express'))();
var port = 9001;

var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));

app.get('/*', function(req, res) {
  res.sendFile(path.resolve(__dirname) + 'app/index.html');
});

app.listen(port, function(error) {
  if (error) {
    console.error(error);
  } else {
    console.info('started on localhost://%s.', port);
  }
});

And the webpack.config.js:
var webpack = require('webpack');
var path = require('path');
var autoprefixer = require('autoprefixer');
var isProd = process.env.NODE_ENV === 'production';

module.exports = {
  devtool: isProd ? null : 'source-map',
  entry: 'app/index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  resolve: {
    root: path.resolve(__dirname, 'app'),
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loaders: [
          'react-hot',
          'babel'
        ],
        include: path.join(__dirname, ''),
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg)$/,
        loader: 'file-loader?name=img/[name].[ext]'
      },
      {
        test: /\.scss$/,
        loader: 'style!css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]!postcss!sass'
      }
    ]
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ],
  postcss: [
    autoprefixer({ browsers: ['last 3 versions'] })
  ]
};

A: If it helps, the following is my current webpack config
import path from 'path';
import webpack from 'webpack';

export default {
  target: 'node',
  node: {
    // prevents webpack from overwriting the values from node
    // https://github.com/webpack/webpack/issues/1599
    __dirname: false,
    __filename: false
  },
  devtool: 'source-map',
  resolve: {
    root: path.resolve(__dirname + '/app'),
    extensions: ['', '.js']
  },
  entry: {
    server: './app/app'
  },
  output: {
    path: path.join(__dirname + '/../dist'),
    filename: '[name].bundle.js',
    libraryTarget: 'commonjs'
  },
  // prevents node_modules from being bundled by webpack
  externals: [/^(?!\.|\/).+/i,],
  module: {
    loaders: [{
      loader: 'babel-loader',
      test: /\.js$/,
      exclude: /(node_modules|dist)/,
      cacheDirectory: 'webpack-cache',
      query: {
        presets: ['es2015'],
        plugins: [
          'transform-runtime',
          'transform-async-to-generator'
        ]
      }
    }]
  }
}


text:
Q: How iterating on std::map returns sorted elements based on the key value The container std::map is a data structure that STL provides. In almost all compilers it is implemented as a R&B tree with guaranteed log(n) insertion, find and removal time.
In a red and black tree the elements are sorted based on the "less" operator of the stored element. So basically if a root is N + 1 , N will be on the left sub-tree while N + 2 will be on the right sub-tree and this ordering will be decided by the less operator.
My question is when executing the below code:
  std::map<char,int> testMap;

  testMap['a']=10;
  testMap['b']=30;
  testMap['g']=50;
  testMap['d']=70;
  testMap['h']=23;
  testMap['f']=44;
  testMap['c']=100;
  testMap['e']=10;

  typedef std::map<char, int>::iterator it_type;
  for(it_type iterator = testMap.begin(); iterator != testMap.end(); iterator++) {
      std::cout << iterator->first << std::endl;
  }

This is the output of the code:
a
b
c
d
e
f
g
h
The elements are returned in a sorted order based on the key value. How can this be possible considering the fact that the underlying data structure is a red and black tree? How c++ iterates from the leftmost sub-tree to rightmost sub-tree is it a doubly linked r&b tree?

A: Broadly speaking, there are two ways to iterate through the contents of a tree: breadth first and depth first. Breadth first looks at all the elements at one level before going down to the next level. Depth first goes down one branch of the tree to it's leaf, then comes up and back down to the next leaf, etc. For a tree that represents sorted data, depth first can give you the data in sorted order, and that's what map iterators do, because it's most useful.


text:
Q: How to install GCC Cross Compiler (ix86) on Cygwin Are there any packages available in Cygwin as cross compile toolchain for Linux-i386-elf. I am unable to find any while installing cygwin packages. But here, while anwering this question, it says that it is available.
However, Cygwin has no package corresponding to linux-*-gcc-* in Devel category
If anyone has any idea. please let me know.

A: The cygwinports.org mirror no longer contains the extra packages, i.e., those that are not part of the official cygwin.org packages.
These extras are now only available in the cygports-extras project on Github. See e.g. https://github.com/cygwinports-extras/linux-x86_64-gcc. You should be able to download, or clone this repo into /usr/src or something similar in the cygwin install tree. This will let you build a cross-compiler that runs in cygwin and targets the X86-64 architecture on the linux os. It currently has patches for and will build GCC 4.8.2 because it has not been updated since August 2015. There are a lot of other packages you will need for a complete cross-compiler tool chain and runtime. Then, if you need a more recent version of the compiler, you will need to develop any patches needed to make more recent versions of these package work.
That sounds like a lot of work. A much easier solution is to download a virtual machine, such as Virtual Box from https://www.virtualbox.org/. Install a minimal linux from an ISO image or download a prebuilt virtual disk with the os and software you need. VBox runs nicely on a Win7 or Win10 machine. You won't need a huge virtual disk, just enough for the os, the gcc compiler tool chain and a bit of work space. You can fiddle with the settings to get it working seamlessly with windows, or just let it run a console or the linux desktop in a window.
You could also look at the Windows Subsytem for Linux (WSL) that runs on Win10. I have not used it, but I think you can install a Ubuntu system with access to all the packages available for Ubuntu.
HTH
Doug


text:
Q: Duplicate Classes to handle app flow (with explicit intents) I have three different options in my app that allow the user through several of the same classes but at different times, ie
1) Sharing with friend:
MainClass -> InviteFriendOrGroup -> Sharing -> IM
2) Creating event with friends
MainClass -> InviteFriendOrGroup -> CreateEvent -> OpenEventsPage
3) Creating event with no friends:
MainClass -> CreateEvent -> OpenEventsPage
My issue is with the intents to allow for this navigation without so many duplicate classes. For example, in the InviteFriendOrGroup class, onListItemClick method
    Intent i = new Intent(getActivity(), SpecialSharing.class);
    startActivity(i);

which means that only open 1) above is allowed. An easy solution is to make duplicate classes, but with the different intents in them, ie.InviteFriendOrGroupEvent, or InviteFriendOrGroupSharing....
But there has to be a better way?

A: You shouldn't duplicate the classes. Pass parameters using "extras" in the Intent to control which options are available.


text:
Q: Makefile tries to compile one of it's own rules as if it were a file I have a simple makefile to compile some C code that uses OpenGL libraries, however, it appears to be interpreting one of it's own rules as a file to compile. The simplified version is as follows:
CC = gcc
COMPILEFLAGS = -Wall -lglut -lGL -lGLU -lm -c
LINKFLAGS = -lglut -lGL -lGLU -lm

castle: castle_link

run_castle:
    ./castle $(ARGS)

castle_link: castle_compile
    ${CC} -o castle castle.o ${LINKFLAGS}

castle_compile:
    ${CC} ${COMPILEFLAGS} castle.c

clean:
    rm *.o castle

Executing make -n castle yields the following:
gcc -Wall -lglut -lGL -lGLU -lm -c castle.c
gcc -o castle castle.o -lglut -lGL -lGLU -lm
gcc   castle.o castle_link   -o castle

And I cant understand why this happens. On this very same file there is another set of rules that follow precisely the same pattern, only changing file names, that work flawlessly.
(This only happens when executing the rule make castle, manually executing castle_compile and then castle_link does not cause that).
Any help is very much appreciated.

A: To explain what happened, you have a rule without a recipe:
castle: castle_link

which means that make will try to find an implicit rule for it. From the manual:

If none of the explicit rules for a target has a recipe, then make searches for an applicable implicit rule to find one

And earlier in that page it says that prerequisites for targets are combined:

One file can be the target of several rules. All the prerequisites mentioned in all the rules are merged into one list of prerequisites for the target.

The implicit rule that matches will be either:
%: %.o
    $(LINK.o) $^ $(LOADLIBES) $(LDLIBS) -o $@

if the .o file exists or:
%: %.c
    $(LINK.c) $^ $(LOADLIBES) $(LDLIBS) -o $@

if it doesn't. (make -p will print definitions of the implicit rules).
So the prerequisites for target castle will be:

*

*either castle.o castle_link

*or castle.c castle_link

And the $^ variable in the recipe from the implicit rule will put them in the cc command to execute. Let's see with this simplified makefile:
castle: castle_link

castle_link: castle_compile
    $(CC) -o castle castle.o -lm

castle_compile:
    $(CC) -Wall -c castle.c

If we execute it on a clean directory (i.e. with no castle.o):
]$ make --debug=m castle
...
    Must remake target 'castle_compile'.
cc -Wall -c castle.c                                # This is our recipe, notice -Wall
    Successfully remade target file 'castle_compile'.
  Must remake target 'castle_link'.
cc -o castle castle.o -lm                           # This is our reicpe, notice -lm
  Successfully remade target file 'castle_link'.
Must remake target 'castle'.
cc     castle.c castle_link   -o castle             # This is implicit rule with castle.c
cc: error: castle_link: No such file or directory

Now that castle.o was created, we execute it again:
]$ make --debug=m castle
...
    Must remake target 'castle_compile'.
cc -Wall -c castle.c                                # This is our recipe, notice -Wall
    Successfully remade target file 'castle_compile'.
  Must remake target 'castle_link'.
cc -o castle castle.o -lm                           # This is our recipe, notice -lm
  Successfully remade target file 'castle_link'.
 Prerequisite 'castle_link' of target 'castle' does not exist.
Must remake target 'castle'.
cc   castle.o castle_link   -o castle               # This is implicit rule with castle.o
cc: error: castle_link: No such file or directory

As you can see, in the first invocation it was "cc castle.c castle_link -o castle" and in the second it was "cc castle.o castle_link -o castle".
Don't ask me why only the second invocation printed "Prerequisite 'castle_link' of target 'castle' does not exist." :-)