text:
Q: Clojure IntelliJ Repl can't reload files properly First, thank you for take your time reading my question!
The problem is that when I try to start my system, the repl can't find some files, but if I go and load manually, each of this file's dependencies one by one before it, the file loads perfectly.
Example of manual loading:

The commands I'm trying to execute:
(clojure.tools.namespace.repl/refresh)

Getting this error:
       :via [{:type clojure.lang.Compiler$CompilerException,
              :message "Syntax error compiling at (purchase_listinator/adapters/db/purchase_category.clj:1:1).",
              :data #:clojure.error{:phase :compile-syntax-check,
                                    :line 1,
                                    :column 1,
                                    :source "purchase_listinator/adapters/db/purchase_category.clj"}

I also tried this one:
(do (require '[com.stuartsierra.component.repl :as crepl])
    (require 'purchase-listinator.core)
    (crepl/reset))

Getting this error:
Syntax error compiling at (purchase_listinator\core.clj:1:1).
namespace 'purchase-listinator.components.pedestal' not found after loading '/purchase_listinator/components/pedestal'

Repository at the moment of this error for future reference
I have no idea what is happening, actually, I've been working on this project for many time and it was working well until this week.
I tried to research, but I had no success, it should be a simple thing that I'm missing, but I can't see it. I would be glad if you help me with this. Thank you so much in advance :)

A: (Maybe)Removing the .idea folder and reopen the project helps.

A: First, the problem is not related to the repository itself.
I have no idea what is happening, but I just clone the repository in another folder and I tried to start the system again, and guess what? It worked...
Probably there is a strange thing happening in my local folder, but I don't know what :/
Thank you so much!


text:
Q: Moving the head to the current branch in git I am quite confused why I can't push my changes in the remote branch of my repository
I have this current setup and branches by using git branch -a:
*(HEAD detached from 008fds4)
develop
master
remotes/origin/HEAD -> origin/master
remotes/origin/develop
remotes/origin/master

Every time I tried to push my commits by git push origin develop the terminal displays that develop does not appear to be a git repository. Please enlighten me in the current situation of my branch and how can I move the pointer or head to my develop/current branch

A: It happens because your are on a detached state.
I suppose you made some modifications to your repository so I suggest you to follow this:
git stash save
git checkout develop
git stash pop
git add --all
git commit -m "My commit message."
git push

Please tell me if it works for you too.
PS: git stash save/pop prevent you from loosing changes done in the detached state.

redpajama_set_name: RedPajamaStackExchange


text:
Q: will_paginate starts next page count from 1 with indexing I have an indexed page of posts and it goes like:
<% @posts.each_with_index do |post, index| %>
   //do some rendering
<% end %>
<%= will_paginate @posts %>

While in my controller i have the following:
def index
    @posts = Post.paginate(:page => params[:page], :per_page => 15)
end

The first page numbering counts up to 15 but when i proceed to page two the index count goes back to 1. I want it to proceed from 15 onwards. Thankx

A: Had to browse through the will_paginate code to come up with a solution. In recipe model i added this method.
def offset(page)
    per_page = 15
    @off_set = WillPaginate::PageNumber(page).to_offset(per_page).to_i
end

While in my controller i added:
def index
     @page = params[:page]
end

Finally in my view i added this:
<%= index + recipe.offset(@page) + 1 %>


text:
Q: Arduino API Authentication I'm working on a project and I have a problem since three days.
I'm doing this project with an ESP32 and want to connect it automatically to WIFI and get the API information.
The first part is okay, I did it without any problem. But it does not get the API Information.
My API-Link is something like this:
http://test.de/milad/api/Tv

And it needs a User and Password:
User: Demo
Pass: OIMLyyIR03QZTqN2KFZkDKneuuk5ixMgeGOHS7r3

I tried to read all the BASIC-Auth examples in internet. But I couldn't find the solution... I get this error:
[HTTP] GET... failed, error: connection refused

For example I used this code:
// wait for WiFi connection
if((wifiMulti.run() == WL_CONNECTED)) {

    HTTPClient http;

    USE_SERIAL.print("[HTTP] begin...\n");
    // configure traged server and url

    http.begin("http://test.de/milad/api/Tv");
    http.setAuthorization("demo", "OIMLyyIR03QZTqN2KFZkDKneuuk5ixMgeGOHS7r3");

    USE_SERIAL.print("[HTTP] GET...\n");
    // start connection and send HTTP header
    int httpCode = http.GET();

    // httpCode will be negative on error
    if(httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

        // file found at server
        if(httpCode == HTTP_CODE_OK) {
            String payload = http.getString();
            USE_SERIAL.println(payload);
        }
    } else {
        USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
    }

    http.end();

A: The server uses Digest Authentication while HTTPClient library on ESP32 currently only supports Basic Authentication.


text:
Q: copy activity alternative in Azure Data Factory I have output from web activity in Azure data factory and I want to store the data in blob storage.
Is there any way other than Copy Activity and Function app that I can use to store data in blob storage?

A: Yes, You can use following way to store data in blob storage.
Use PUT method to store web activity output to blob storage.
Step1: Use Web activity body as @activity('Web1').output

Or  if you want to pass the "data" (depending on variable name) and not the headers use @activity('Web1').output.data

Step2: For Authentication select Managed Identity and Resource should be  https://storage.azure.com/

For information follow this link - Azure Data Factory Web activity save output


text:
Q: Listview using Endless adapter I have DB table with 10,000 rows which I want to display in the listview. I want to display first 20 and when the user scrolls down to the last item the next 20 should be loaded (and so on.). it really takes a lot of time to load all the datas in the listview so thats why i want it to load 20 datas first..
inside onCreate() Method the code is:
    dbHelper = new WordDbAdapter(this);
    dbHelper.open();

    //Generate ListView from SQLite Database
    displayListView();

then on the displayListView() method the code is like this:
  @SuppressWarnings("deprecation")
private void displayListView() {

  final Cursor cursor = dbHelper.fetchAllWords();

  // The desired columns to be bound
  String[] columns = new String[] {
          WordDbAdapter.KEY_WORD,
          WordDbAdapter.KEY_ROWID,

  };

  // the XML defined views which the data will be bound to
  int[] to = new int[] {

    R.id.Word,
    R.id.imgStar,

  };

  // create the adapter using the cursor pointing to the desired data
  //as well as the layout information
  dataAdapter = new SimpleCursorAdapter(
    this, R.layout.word_info,
    cursor,
    columns,
    to
    );

  ListView listView = (ListView) findViewById(R.id.Diclist);
  // Assign adapter to ListView
  listView.setAdapter(dataAdapter);
listView.setOnScrollListener(new OnScrollListener(){
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        int lastInScreen = firstVisibleItem + visibleItemCount;
        if(cursor != null){

            if(lastInScreen == totalItemCount && isLoadingMore == false){
                isLoadingMore = true;

                loadedPage ++;
                new LoadWords().execute();
            }
        }
    }
    public void onScrollStateChanged(AbsListView view, int scrollState) {}
});

  listView.setOnItemClickListener(new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> listView, View view,
     int position, long id) {
   // Get the cursor, positioned to the corresponding row in the result set
   Cursor cursor = (Cursor) listView.getItemAtPosition(position);

   // Get the word name from this row in the database.
       String wordSelected =
               cursor.getString(cursor.getColumnIndexOrThrow("word"));
       String wordSyllabication =
               cursor.getString(cursor.getColumnIndexOrThrow("syllabication"));
       String wordPartofSpeech =
               cursor.getString(cursor.getColumnIndexOrThrow("partofspeech"));
       String wordMeaning =
               cursor.getString(cursor.getColumnIndexOrThrow("meaning"));
       String wordSpeak =
               cursor.getString(cursor.getColumnIndexOrThrow("speakword"));

       EditText TextDic = (EditText) findViewById(R.id.TextDic);
       TextDic.setText(wordSelected);
       speakMeaning = wordMeaning;
       speakSyllabication = wordSyllabication;
       speakPartOfSpeech = wordPartofSpeech;
       speakWord = wordSpeak;
       speakGetWord = wordSelected;

       //Toast.makeText(getApplicationContext(),
             //  wordSyllabication + "\n" + wordPartofSpeech + "\n" + wordMeaning , Toast.LENGTH_SHORT).show();

       }
      });

  EditText TextDic = (EditText) findViewById(R.id.TextDic);
  TextDic.addTextChangedListener(new TextWatcher() {

   public void afterTextChanged(Editable s) {
     speakWord = "";
     speakMeaning = "";

   }

   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }

   public void onTextChanged(CharSequence s, int start,
     int before, int count) {
   dataAdapter.getFilter().filter(s.toString());
   }
  });

   dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
         public Cursor runQuery(CharSequence constraint) {
         return dbHelper.fetchWordsByWord(constraint.toString());
         }
     });

     }

then my AsyncTask is like this:
private class LoadWords extends AsyncTask<String, Void, Void> {
    private final ProgressDialog dialog = new ProgressDialog(DictionaryActivity.this);

    Cursor cursor = dbHelper.fetchAllWords();

    @Override
    protected void onPreExecute() {
       this.dialog.setMessage("Loading books...");
       this.dialog.show();
    }

    public void execute() {
        // TODO Auto-generated method stub

    }

    @Override
    protected Void doInBackground(String... arg0) {
        try{
            cursor = dbHelper.fetchAllWords();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    @SuppressWarnings("deprecation")
    @Override
    protected void onPostExecute(final Void unused){
        if(cursor != null){
            if(dataAdapter == null){
                startManagingCursor(cursor);
                String[] columns = new String[] {
                          WordDbAdapter.KEY_WORD,
                          WordDbAdapter.KEY_ROWID,

                  };
                int[] to = new int[] {

                        R.id.Word,
                        R.id.imgStar,

                      };
                getListView().setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
                dataAdapter = new SimpleCursorAdapter(DictionaryActivity.this, R.layout.word_info, cursor, columns, to);
                ListView listView = (ListView) findViewById(R.id.Diclist);
                  // Assign adapter to ListView
                listView.setAdapter(dataAdapter);

            }else{
                dataAdapter.notifyDataSetChanged();
            }
        }
        if(dialog != null && dialog.isShowing()){
            dialog.dismiss();
        }
        isLoadingMore = false;
    }

    private AbsListView getListView() {
        // TODO Auto-generated method stub
        return null;
    }
}

A: The adapter doesn't load everything at once, and that should not be the reason you're seeing poor performance. ListView and SimpleCursorAdapter are fully capable of scrolling a list of only 10,000 items. The adapter only loads items as the user scrolls through the list. From the code that you've posted, I would say that your performance issues come from
dbHelper.deleteAllWords();
dbHelper.insertSomeWords();

If you post the code for these methods and dbHelper.fetchAllWords(), perhaps we can offer more help. Additionally, you can solve user interface problems by executing these long running tasks on a background thread (check out AsyncTask) and using a ProgressDialog to inform the user what is going on.

A: Take a look at Endless Adapter from the great Mark Murphy. It makes it really easy. You'll have your dataset that contains just the items you're displaying. In the adapter you can then tell it to grab the next set from your database and add it to the dataset.


text:
Q: Remove white line after \item in enumerate and before display math The goal is to remove the white line after the 1. in the second enumerate in the picture, so it will look like the first enumerate.
I don't like the first enumerate because it uses inline math, needs the white line in the code to make a new paragraph, and uses \displaystyle which I think is not the way to go: it feels like a 'hack'. Maybe I am mistaken, in that case say so, but I think there must be a good solution.

MWE:
\documentclass[english]{exam}
\usepackage[fleqn]{amsmath}

\begin{document}

    \begin{enumerate}  %result looks fine, but code ugly
        \item
        $\displaystyle \pi$

        $\displaystyle 2\pi$
    \end{enumerate}

    \begin{enumerate} %code looks fine, but result ugly
        \item
        \[\pi\]
        \[2\pi\]
    \end{enumerate}

\end{document}

A: Simply try this:
\documentclass{article}
\usepackage[fleqn]{amsmath}
\newcommand\mathitem{\item\leavevmode\vspace*{-\dimexpr\baselineskip+\abovedisplayskip\relax}}

\begin{document}

    \begin{enumerate} %
        \mathitem \begin{gather*}
          \pi\\2\pi
        \end{gather*}

    \end{enumerate}

\end{document}

A: One problem is that \[...\] environments always add extra vertical space and try to center their contents (the fleqn might help to avoid that).  Using a \tesxtstyle approach with $ delimiters is the typical approach for what you seem to want.  But if \item is just a bunch of left-aligned stacked math, this might be more streamlined.
Maybe one of (or some combination of) the following three stack approaches would work for you (no fleqn required).
\documentclass[english]{exam}
\usepackage{tabstackengine}
\stackMath
\makeatletter\renewcommand\TAB@delim[1]{\displaystyle#1}\makeatother
\setstackEOL{\cr}% ROW DELIMITER FOR STACKS
\renewcommand\stackalignment{l}% LEFT ALIGNMENT OF STACKS
\setstackgap{S}{8pt}% INTER-ROW PADDING OF SHORT STACKS
\begin{document}
    \begin{enumerate}  %result looks fine, but code ugly
        \item
%       FOR SIMPLE REGULAR-HEIGHT STACKS
        \Longunderstack{\pi\cr 2\pi}
        \item
%       FOR IRREGULAR HEIGHT STACKS IN \textstyle
        \Shortunderstack{\pi\cr \frac{2\pi}{x}\cr \frac{\pi^3}{\pi_x}}
        \item
%       FOR IRREGULAR HEIGHT STACKS IN \displaystyle
        \tabbedShortunderstack{\pi\cr \frac{2\pi}{x}\cr \frac{\pi^3}{\pi_x}}
    \end{enumerate}
\end{document}

If typing \tabbedShortunderstack was too much work each time, one could, for example, \let\Estack\tabbedShortunderstack in the preamble.

A: One more (simple) solution:
\documentclass{article}
\usepackage{amsmath}

\begin{document}
\begin{enumerate}
  \item $\begin{aligned}[t]
          x & = 0   \\
          y & = \frac{1}{2}
        \end{aligned}$
\end{enumerate}
\end{document}

A: With the extension witharrows correctly parameted, you have directly the result. Of course, the main purpose of the extension witharrows is to add arrows. That's, why, in the following example, I have added an arrow.
\documentclass[english]{exam}
\usepackage[fleqn]{amsmath}
\usepackage{witharrows}
\WithArrowsOptions{fleqn,displaystyle,mathindent = 0pt,notag}
\begin{document}
\begin{enumerate}
\item
\begin{DispWithArrows}[format=c]
\frac{2\pi}{3} \Arrow[tikz=-]{which one?}\\
\frac{5\pi}{4}
\end{DispWithArrows}
\end{enumerate}
\end{document}


text:
Q: what datatype to choose in pgadmin4 to store long text in Postgres instead of 'char varying []'? I'm storing a title of a post and need to store long text - which is a list of 100 comments for this post. I want to append them altogether and store as a string
in pgadmin4 there is
character varying []

data type available when creating table.
what other options do i have? create my own custom structure?

A: TEXT data type is the best choice and it's a variable with unlimited length
For more information refer https://www.postgresql.org/docs/current/datatype-character.html


text:
Q: If 4 people have five meal choices how many different ways can they order? If 4 people have five meal choices, and multiple people can have the same meal. How many different ways can they order?

A: There are $(5^4)$ possible ways in which four people may order their meals, assuming everyone orders one meal. (Remember, everyone may order the same meal.)
Person 1: 5 choices
Person 2: 5 choices
Person 3: 5 choices
Person 4: 5 choices
Multiply: $5 \cdot 5\cdot 5\cdot 5 = 5^4 = 625$ possible meal orders for 4 people.
If some can opt to fast (not order anything), so everyone orders at most one meal, then there are $(6^4)$ possible ways four people may order their meals, since now each of the 4 people actually have $6$ choices, one of which is simply not ordering anything offered.


text:
Q: using Python 3 A byte-like object is required not a str" i have tried converting it into bytes but it still giving me the same error import netfilterqueue
import scapy.all as scapy

    def process_packet(packet):
        scapy_packet = scapy.IP(packet.get_payload())
        if scapy_packet.haslayer(scapy.DNSRR):
            qname = scapy_packet[scapy.DNSQR].qname
            website = 'www.bing.com'

            if website in qname:
                print("[+] Spoofing ")
                answer = scapy.DNSRR(rrname=qname, rdata="10.0.2.12")
                scapy_packet[scapy.DNS].an = answer
                scapy_packet[scapy.DNS].ancount = 1

                del scapy_packet[scapy.IP].len
                del scapy_packet[scapy.IP].chksum
                del scapy_packet[scapy.UDP].len
                del scapy_packet[scapy.UDP].chksum

                packet.set_payload(str(scapy_packet))
        packet.accept()

    queue = netfilterqueue.NetfilterQueue()
    queue.bind(0, process_packet)
    queue.run()

Exception ignored in: 'netfilterqueue.global_callback'
Traceback (most recent call last):
  File "dns_spoofer.py", line 9, in process_packet
    if website in qname:
TypeError: a bytes-like object is required, not 'str'
Exception ignored in: 'netfilterqueue.global_callback'
Traceback (most recent call last):
  File "dns_spoofer.py", line 9, in process_packet
    if website in qname:
TypeError: a bytes-like object is required, not 'str'
Exception ignored in: 'netfilterqueue.global_callback'
Traceback (most recent call last):
  File "dns_spoofer.py", line 9, in process_packet
    if website in qname:
TypeError: a bytes-like object is required, not 'str'
Exception ignored in: 'netfilterqueue.global_callback'
Traceback (most recent call last):
  File "dns_spoofer.py", line 9, in process_packet
    if website in qname:
TypeError: a bytes-like object is required, not 'str'
Exception ignored in: 'netfilterqueue.global_callback'
Traceback (most recent call last):
  File "dns_spoofer.py", line 9, in process_packet
    if website in qname:
TypeError: a bytes-like object is required, not 'str'
Exception ignored in: 'netfilterqueue.global_callback'
Traceback (most recent call last):
  File "dns_spoofer.py", line 9, in process_packet
    if website in qname:
TypeError: a bytes-like object is required, not 'str'
Exception ignored in: 'netfilterqueue.global_callback'
Traceback (most recent call last):
  File "dns_spoofer.py", line 9, in process_packet
    if website in qname:
TypeError: a bytes-like object is required, not 'str'
Exception ignored in: 'netfilterqueue.global_callback'
Traceback (most recent call last):
  File "dns_spoofer.py", line 9, in process_packet
    if website in qname:
TypeError: a bytes-like object is required, not 'str'
^CTraceback (most recent call last):
  File "dns_spoofer.py", line 25, in <module>
    queue.run()
KeyboardInterrupt

A: Try website = b'www.bing.com'. The b makes it a byte literal.

A: use website = b"www.bing.com"

and also in here
packet.set_payload(str(scapy_packet))

change this to
 packet.set_payload(bytes(scapy_packet))


text:
Q: USACO name that number problem execution error The problem statement:
Among the large Wisconsin cattle ranchers, it is customary to brand cows with serial numbers to please the Accounting Department. The cow hands don't appreciate the advantage of this filing system, though, and wish to call the members of their herd by a pleasing name rather than saying, "C'mon, #4734, get along."
Help the poor cowhands out by writing a program that will translate the brand serial number of a cow into possible names uniquely associated with that serial number. Since the cow hands all have cellular saddle phones these days, use the standard Touch-Tone(R) telephone keypad mapping to get from numbers to letters (except for "Q" and "Z"):
              2: A,B,C     5: J,K,L    8: T,U,V
              3: D,E,F     6: M,N,O    9: W,X,Y
              4: G,H,I     7: P,R,S

Acceptable names for cattle are provided to you in a file named "dict.txt", which contains a list of fewer than 5,000 acceptable cattle names (all letters capitalized). Take a cow's brand number and report which of all the possible words to which that number maps are in the given dictionary which is supplied as dict.txt in the grading environment (and is sorted into ascending order).
For instance, the brand number 4734 produces all the following names:
    GPDG GPDH GPDI GPEG GPEH GPEI GPFG GPFH GPFI GRDG GRDH GRDI
    GREG GREH GREI GRFG GRFH GRFI GSDG GSDH GSDI GSEG GSEH GSEI
    GSFG GSFH GSFI HPDG HPDH HPDI HPEG HPEH HPEI HPFG HPFH HPFI
    HRDG HRDH HRDI HREG HREH HREI HRFG HRFH HRFI HSDG HSDH HSDI
    HSEG HSEH HSEI HSFG HSFH HSFI IPDG IPDH IPDI IPEG IPEH IPEI
    IPFG IPFH IPFI IRDG IRDH IRDI IREG IREH IREI IRFG IRFH IRFI
    ISDG ISDH ISDI ISEG ISEH ISEI ISFG ISFH ISFI
    As it happens, the only one of these 81 names that is in the list of valid names is "GREG".

Write a program that is given the brand number of a cow and prints all the valid names that can be generated from that brand number or ``NONE'' if there are no valid names. Serial numbers can be as many as a dozen digits long.
  PROGRAM NAME: namenum
  INPUT FORMAT
      A single line with a number from 1 through 12 digits in length.
      SAMPLE INPUT (file namenum.in)
        4734
      OUTPUT FORMAT
        A list of valid names that can be generated from the input, one per line, in ascending alphabetical order.
      SAMPLE OUTPUT (file namenum.out)
        GREG

My code:
#include<bits/stdc++.h>
using namespace std;
int main(){
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    ofstream fout("namenum.out");
    ifstream fin("namenum.in");
    long long int n,n1;
    fin>>n;
    int d=0; n1=n;
    while(n1){
        n1/=10;
        d++;
    }
    n1=n;
    unordered_map<int,vector<char>> m={{2,{'A','B','C'}},
                                   {3,{'D','E','F'}},
                                   {4,{'G','H','I'}},
                                   {5,{'J','K','L'}},
                                   {6,{'M','N','O'}},
                                   {7,{'P','R','S'}},
                                   {8,{'T','U','V'}},
                                   {9,{'W','X','Y'}}};
    fin.open("dict.txt");
    string s;
    fin>>s;
    vector<string> ans;
    while(!fin.eof()){

        if(s.length()==d){
            int flag=1,check=0;
            for(int i=d-1;i>=0;i--){
                flag=1;
                for(int j=0;j<3;j++){
                    if(m[n1%10][j]==s[i]){
                        flag=0;
                    }
                }
                n1/=10;
                if(flag==1){
                    check=1;
                    break;
                }
            }
            if(check==0){
                ans.push_back(s);
            }
            n1=n;
        }
    }
    sort(ans.begin(),ans.end());
    for(int i=0;i<ans.size();i++){
        fout<<ans[i]<<'\n';
    }
    return 0;
}

The following error is occuring:
 > Run 1: Execution error: Your program (`namenum') used more than
        the allotted runtime of 1 seconds (it ended or was stopped at
        1.855 seconds) when presented with test case 1. It used 1360 KB of
        memory.

        ------ Data for Run 1 [length=5 bytes] ------
        4734
        ----------------------------
    Test 1: RUNTIME 1.855>1 (1360 KB)

I don't get this error. How am i supposed to calculate the time and rectify my code accordingly?

A: Done.
Was not reading the input correctly.
Just corrected the input of dict.txt and it's fine.
#include<bits/stdc++.h>
using namespace std;
int main(){
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    ofstream fout("namenum.out");
    ifstream fin("namenum.in");
    fstream file;
    long long int n,n1;
    fin>>n;
    int d=0; n1=n;
    while(n1){
        n1/=10;
        d++;
    }
    n1=n;
    unordered_map<int,vector<char>> m={{2,{'A','B','C'}},
                                   {3,{'D','E','F'}},
                                   {4,{'G','H','I'}},
                                   {5,{'J','K','L'}},
                                   {6,{'M','N','O'}},
                                   {7,{'P','R','S'}},
                                   {8,{'T','U','V'}},
                                   {9,{'W','X','Y'}}};
    file.open("dict.txt");
    string s;
    vector<string> ans;
    while(getline(file,s)){
        if(s.length()==d){
            int flag=1,check=0;
            for(int i=d-1;i>=0;i--){
                flag=1;
                for(int j=0;j<3;j++){
                    if(m[n1%10][j]==s[i]){
                        flag=0;
                    }
                }
                n1/=10;
                if(flag==1){
                    check=1;
                    break;
                }
            }
            if(check==0){
                ans.push_back(s);
            }
            n1=n;
        }
    }
    file.close();
    sort(ans.begin(),ans.end());
    for(int i=0;i<ans.size();i++){
        fout<<ans[i]<<'\n';
    }
    if(ans.size()==0){
        fout<<"NONE\n";
    }
    return 0;
}


text:
Q: Problem in response.write escaping quotes Hey friends please help me ...
how can i write response.write statement..... i want to put radio button but threre is some problem in response.write to get string from the record set RS and ORS...
set ORS = Server.CreateObject("ADODB.recordset")
getopt="SELECT * FROM Options WHERE QuestionID=" & RS("QuestionID")
ORS.Open getopt,Conn

if not ORS.EOF then
    ORS.movefirst
    do
        response.write " <input type='radio' name=' 'Question' & RS('QuestionID')& ''' value='Answer' & ORS('OptionID') & ''' >
" & ORS("Option") & "

"
        ORS.movenext
    loop until ORS.EOF
end if

RS.movenext
loop until RS.EOF

A: Use double quotes " to delimit server side strings, and single quotes ' for the client side:
response.write " <input type='radio' name='Question" & RS("QuestionID") & "' value='Answer" & ORS("OptionID") & "'>
" & ORS("Option") & "

"

A: Sometimes it's better to break long string into smaller, more manageable chunks. Try --
response.write "<input type='radio' name='Question"
response.write RS("QuestionID") & "' value='Answer"
response.write ORS("OptionID") & "'> "
response.write "
" & ORS("Option") & "

"


text:
Q: How to call method at fixed time android? How do i call specific method at particular time in my android app
suppose I have to call startService() method at fix time which is provided by user. Only on that time startService() method automatic going to execute.
Do not know how to start. graceful to anyone suggest me direction of solution. i mean which functionality I have to implement.

A: You can use AlarmManager to do it.
Method Example: Waking CPU every 10 minutes until the phone turns off.
Add to Manifest.xml:
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

<receiver  android:process=":remote" android:name="Alarm"></receiver>

Code:
    package YourPackage;
    import android.app.AlarmManager;
    import android.app.PendingIntent;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.os.PowerManager;
    import android.widget.Toast;

    public class Alarm extends BroadcastReceiver
    {
         @Override
         public void onReceive(Context context, Intent intent)
         {
             PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
             PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
             wl.acquire();

             // Put here YOUR code.
             Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example

             wl.release();
         }

     public void SetAlarm(Context context)
     {
         AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
         Intent i = new Intent(context, Alarm.class);
         PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
         am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
     }

     public void CancelAlarm(Context context)
     {
         Intent intent = new Intent(context, Alarm.class);
         PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
         AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
         alarmManager.cancel(sender);
     }
 }

Set Alarm from Service:
package YourPackage;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

public class YourService extends Service
{
    Alarm alarm = new Alarm();
    public void onCreate()
    {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
{
         alarm.SetAlarm(YourService.this);
     return START_STICKY;
}

    public void onStart(Context context,Intent intent, int startId)
    {
        alarm.SetAlarm(context);
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
}

If you want set alarm repeating at phone boot time:
Add permission to Manifest.xml:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

<receiver android:name=".AutoStart">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"></action>
    </intent-filter>
</receiver>

And create new class:
package YourPackage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AutoStart extends BroadcastReceiver
{
    Alarm alarm = new Alarm();
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
        {
            alarm.SetAlarm(context);
        }
    }
}

A: What you are looking for is the AlarmManager.
For example, if you are looking to start a service every couple of minutes
long repeatTimeInMillis = getUserRepeatTimeInMillis();

PendingIntent pendingIntent = PendingIntent.getService(
        context,
        0,
        new Intent(context, ServiceToStart.class),
        0);

AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() + repeatTimeInMillis,
        repeatTimeInMillis,
        pendingIntent)

If you need to execute some other code every couple of minutes then instead of a service you could use a broadcast receiver and use the getBroadcast static method from PendingIntent.
For more detailed information check out Google's documentation about the AlarmManager.
https://developer.android.com/training/scheduling/alarms.html
Make sure you read what the differences are between the different alarm types (ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC, RTC_WAKUP) as they change the behavior of the alarm.


text:
Q: netbeans subversion cleanup button There is a cleanup button in svn-workbench
Using it + update we can usually fix some svn bugs (for example "... is not a working directory")
I cant find this function in netbeans:
context menu -> subversion
and in the
team -> subversion
where is it?
upd:
I have not in the context menu "Cleanup Working Copy" item (netbeans 6.8 under ubuntu)

A: I have updated netbeans to 6.9 version
"Cleanup Working Copy" appear at proper place!
Mchl comment is the right answer!
I dont understand him havent posted it as an real answer


text:
Q: Python List of charts in excel I have a program which takes DataFrame and writes it into excel as chart(using xlsxwriter and pandas libraries). For example, I wrote column-stacked-chart into excel.
What I want now is to add line chart to that excel chart which was created before. This isn't problem if I write them in the same function, but first chart is already created and I don't have that object in another code. I want to combine them, so I need to get list of charts in excel to take first one, create second and combine them.


text:
Q: Spring Boot 1.4 and Apache Axis2 - Tomcat doesn't start by running Jar I am now using Spring Boot 1.4 and Apache Axis2 in my project. After adding dependencies in pom.xml, the generated jar file can't run. It means the tomcat server doesn't start and
java.util.concurrent.ExeutionException: org.apache.catalina.LifecycleException: Failed to start component

A: I could solved the problem by adding exclusions in pom.xml. I think the problem is the embed Tomcat has some problems with javax.servlet-api.
<dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-kernel</artifactId>
            <version>${axis2.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
            </exclusions>
</dependency>


text:
Q: UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) I'm trying to write quite a complicated Python program, but it's mostly done. I am having trouble with just one tiny little detail.
The problematic code section is this:
newData = kmeans.sampleNewData(200, means, covariances, priors)

newData = newData.astype(str)
...loops and logic and stuff...
newData[i, j] = columnsList[j][(indexList[j]).index(closestFit)]

Basically, newData is a numpy matrix size 200 by 4, filled with numbers of type float. I then convert them to strings use the astype method.
I then try to put this columnsList[j][(indexList[j]).index(closestFit)] which is some string, into an entry of newData.
The problem is that columnsList[j][(indexList[j]).index(closestFit)] is not necessarily English. It could for example be hebrew. In which case - I get the error

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

It is worth noting that I have written # -*- coding: utf-8 -*- so we are encoding in utf-8, and when I print columnsList[j][(indexList[j]).index(closestFit)] it indeed prints the correct value. So we can print it. But for some reason I can't put it into the newData matrix.

A: Encode is operation when you're trying to convert from some string type to bytes. It seems, that your columnsList[j][(indexList[j]).index(closestFit)] contains Unicode string, so try
newData[i, j] = columnsList[j][(indexList[j]).index(closestFit)].encode('utf-8')
instead.


text:
Q: Disprove for every $k$ vertices of $G$ lies on a common cycle of $G$ for $k \geq 2$, $G$ is $k$ connected graph in general Disprove for every $k$ vertices of  $G$ lies on a common cycle of $G$ for $k  \geq 2$, $G$  is $k$ connected graph
I want to disporve this so I'm trying to show that $G$ is not a$$ connected graph.
I'm looking at the cycle. Let $G = C_n$ for $n \geq k \geq 3$ because the smallest cycle has 3 vertices. In $C_n$ every vertex lies on a big common cycle. Now I need to consider 2 cases
Case 1: $n =k$, then if I delete $k$ vertices in $C_n$ , I have a null graph, which have nothing to prove.
Case 2: $n>k$ then $n \geq k+1>3$. Let $S=\{v_1, v_2,v_3, \dots , v_k\}$ such that $v_i$ adjacent to $v_{i+1}$, then $C_n -S=P_{n-k}$ which still connected. So this doesn't work for every $k$ vertices in $C_n$, thus the statement is also false in this case.
I'm not sure if my reasoning is acceptable in case 2? I feel like I've missed something

A: In order to disprove this general statement, you just need one completely specific counterexample.
Consider $C_5$.  This satisfies the hypothesis for $k=3$ but is not $3$-connected.  This disproves the claim.


text:
Q: .Net 4.0 JSON Serialization: Double quotes are changed to \" I'm using System.Web.Script.Serialization.JavaScriptSerializer() to serialize dictionary object into JSON string. I need to send this JSON string to API sitting in the cloud. However, when we serialize it, serializer replaces all the double quotes with \"
For example -
Ideal json_string = {"k":"json", "data":"yeehaw"}
Serializer messed up json_string = {\"k\":\"json\",\"data\":\"yeehaw\" }
Any idea why it is doing so? And I also used external packages like json.net but it still doesn't fix the issues.
Code -
Dictionary<string, string> json_value = new Dictionary<string, string>();
json_value.Add("k", "json");
json_value.Add("data", "yeehaw");
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json_string = jsonSerializer.Serialize(json_value);

A: I'm going to hazard the guess that you're looking in the IDE at a breakpoint. In which case, there is no problem here. What you are seeing is perfectly valid JSON; simply the IDE is using the escaped string notation to display it to you. The contents of the string, however, are your "ideal" string. It uses the escaped version for various reasons:

*

*so that you can correctly see and identify non-text characters like tab, carriage-return, new-line, etc

*so that strings with lots of newlines can be displayed in a horizontal-based view

*so that it can be clear that it is a string, i.e. "foo with \" a quote in" (the outer-quotes tell you it is a string; if the inner quote wasn't escaped it would be confusing)

*so that you can copy/paste the value into the editor or immediate-window (etc) without having to add escaping yourself

A: Make sure you're not double serializating the object. It happened to me some days ago.

A: What you're seeing is a escape character
Your JSON is a String and when you want to have " in a string you must use one of the following:
string alias = @"My alias is ""Tx3""";

or
string alias = "My alias is \"Tx3\"";

Update
Just to clarify. What I wanted say here is that your JSON is perfectly valid. You're seeing the special characters in the IDE and that is perfectly normal like Jon & Marc are pointing in their answers and comments. Problem lies somewhere else than those \ characters.


text:
Q: Additional fields in django not being saved I have already looked through all the django registration examples and i've successfully created a form with extended fields but i've experienced a few problems listed below, mainly with the data not being saved in the DB table UserProfile.
I created a forms.py and stored in my proj directory.
It's as follows:
from django import forms
from r2.models import Keyword
from r2.models import UserProfile
from registration.forms import RegistrationForm
from registration.models import RegistrationProfile
from django.utils.translation import ugettext_lazy as _
from registration.forms import RegistrationForm, attrs_dict

class ProjectSpecificRegistrationForm(RegistrationForm):
    keywords = forms.ModelChoiceField(queryset=Keyword.objects.all())
    first_name =forms.CharField(widget=forms.TextInput(attrs=attrs_dict),label=_(u'First Name'))
    last_name =forms.CharField(widget=forms.TextInput(attrs=attrs_dict),label=_(u'Last Name'))

def save(self, profile_callback=None):
    new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
    password=self.cleaned_data['password1'],
    email=self.cleaned_data['email'])
    new_profile = UserProfile(user=new_user,username=self.cleaned_data['username'], keywords_subscribed=self.cleaned_data['keywords'],first_name=self.cleaned_data['first_name'],last_name=self.cleaned_data['last_name'])

    new_profile.save()

and the URLS.py:
#registrations URLS
url(r'^activate/(?P<activation_key>\w+)/$',activate,name='registration_activate'),
url(r'^login/$',auth_views.login,{'template_name': 'registration/login.html'}, name='auth_login'),
url(r'^logout/$',auth_views.logout,{'template_name': 'registration/logout.html'},name='auth_logout'),
url(r'^password/change/$',auth_views.password_change,name='auth_password_change'),
url(r'^password/change/done/$',auth_views.password_change_done,name='auth_password_change_done'),
url(r'^password/reset/$',auth_views.password_reset,name='auth_password_reset'),
url(r'^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',auth_views.password_reset_confirm,name='auth_password_reset_confirm'),
url(r'^password/reset/complete/$',auth_views.password_reset_complete,name='auth_password_reset_complete'),
url(r'^password/reset/done/$',auth_views.password_reset_done,name='auth_password_reset_done'),
url(r'^register/$',register, {'backend': 'accounts.regbackend.RegBackend','form_class' : ProjectSpecificRegistrationForm},  name='registration_register'),

url(r'^register/complete/$',direct_to_template,{'template': 'registration/registration_complete.html'},name='registration_complete'),

I've added all these to the proj urls.py as i've followed a tutorial from somewhere.
Problem 1: User profile is not getting saved into the DB even though i am using django registration 0.6.
Problem 2: Is this the correct way to set my urls.py? because i understand i'm not supposed to overwrite the registration urls.py.
Problem 3: Must i create a regbackend.py? and if so how do i go about doing that?


text:
Q: Breadcrumb navigation in SharePoint Online I would like to ask you if is it possible to display breadcrumb navigation in SharePoint Online as in this post?
I would like to use this navigation also as a next-one navigation element for users through the portal. I think its really practical element for end-users.


text:
Q: xsl-fo header not appearing second page of first chapter I'm creating custom PDF output from a DITA bookmap using the AntennaHouse formatting engine. I'm trying to create a custom header that appears only on the first page of the book. These books can have multiple chapters, so the strategy I'm using is to create one page sequence for the first chapter, and then a different page sequence for the remaining chapters.
I distinguish between the first chapter processing and the rest of the chapters to be processed like this (in the file commons.xsl). The first block determines the chapter number and puts it in the variable "chapterNumber". The second block describes how to process chapters, depending on the content of the chapterNumber variable:
    <xsl:variable name="id" select="@id"/>
    <xsl:variable name="topicChapters">
        <xsl:copy-of select="$map//*[contains(@class, ' bookmap/chapter ')]"/>
    </xsl:variable>
    <xsl:variable name="chapterNumber">
        <xsl:number format="1" value="count($topicChapters/*[@id = $id]/preceding-sibling::*) + 1"/>
    </xsl:variable>

    <xsl:when test="$topicType = 'topicChapter'">
    <xsl:choose>
        <xsl:when test="$chapterNumber = '1'">
            <xsl:call-template name="processFirstChapter"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:call-template name="processTopicChapter"/>
        </xsl:otherwise>
    </xsl:choose>

The page sequence for the first chapter looks like this:
    <fo:page-sequence-master master-name="body-first-sequence">
        <fo:repeatable-page-master-alternatives>
            <fo:conditional-page-master-reference page-position="first" master-reference="body-first"/>
            <fo:conditional-page-master-reference page-position="rest" master-reference="body-rest"/>
            <fo:conditional-page-master-reference master-reference="body-rest"/>
        </fo:repeatable-page-master-alternatives>
    </fo:page-sequence-master>

The page sequence for the remaining chapters looks like this:
    <fo:page-sequence-master master-name="body-sequence">
        <fo:repeatable-page-master-alternatives>
            <fo:conditional-page-master-reference page-position="any" master-reference="body-rest"/>
        </fo:repeatable-page-master-alternatives>
    </fo:page-sequence-master>

During processing, I call two templates, one for the first chapter, and one for the rest of the chapters:
    <xsl:template name="insertBodyStaticContents">
        <xsl:call-template name="insertBodyFootnoteSeparator"/>
        <xsl:call-template name="insertBodyRestHeader"/>
        <xsl:call-template name="insertBodyFooter"/>
    </xsl:template>

    <xsl:template name="insertBodyFirstStaticContents">
        <xsl:call-template name="insertBodyFootnoteSeparator"/>
        <xsl:call-template name="insertBodyFirstHeader"/>
        <xsl:call-template name="insertBodyFooter"/>
    </xsl:template>

Those templates in turn call header templates, one for the first page of the first chapter, the other one for all remaining pages:
    <xsl:template name="insertBodyFirstHeader">
        <fo:static-content flow-name="first-body-header">
            <fo:block-container z-index="-1" position="absolute" top="0pt" left="0pt" height="1.5in" width="100%">
                <fo:block>
                    <fo:external-graphic src="Configuration/OpenTopic/cfg/common/artwork/qrgraphic.png"/>
                </fo:block>
            </fo:block-container>
            <!-- set the title -->
            <fo:block xsl:use-attribute-sets="__qrc__title__header">
                <xsl:value-of select="//*[contains(@class,' bookmap/mainbooktitle ')]"/>
            </fo:block>
            <!-- set the subtitle -->
            <fo:block xsl:use-attribute-sets="__first__heading__qrctext">
                    Quick Reference Card
            </fo:block>
        </fo:static-content>
    </xsl:template>

    <xsl:template name="insertBodyRestHeader">
        <fo:static-content flow-name="rest-body-header">
            <!-- set the title -->
            <fo:block xsl:use-attribute-sets="__qrc__title__header2">
                <xsl:value-of select="//*[contains(@class,' bookmap/mainbooktitle ')]"/>
            </fo:block>
            <!-- set the subtitle -->
            <fo:block xsl:use-attribute-sets="__firstheading__subtitle">
                Quick Reference Card
            </fo:block>
        </fo:static-content>
    </xsl:template>

Everything works except for one strange glitch--if the first chapter of the book is longer than one page, then the first page of the first chapter has the correct header (the one with the flow name called first-body-header) but on subsequent pages of that chapter, the header is blank. Chapters two and greater also have the correct header (the one with the flow name called rest-body-header). I know that the code for that header is correct, since it appears in chapter two and beyond. But that exact same header is supposed to appear on pages 2+ of the first chapter, and it doesn't appear. I can't for the life of me figure out what's going wrong with my code. Any help is appreciated.

A: You may be making things more complicated than you need to. If the geometry of the page regions is the same for all the chapters, then you shouldn't need a different page sequence master for the first chapter, just different content in the header region's static content.
The other thing to do is to save the .fo file and inspect it to make sure it is being generated the way you thing it is. Set the Ant parameter "retain.topic.fo" to "yes" and clean.temp to "no".
Cheers,
Eliot

A: I'm not sure where you're making some of your calls, but basically you need two simple page masters (4, counting blankpage). 1 is your first chapter opener, one is your every-other-page-in-the-book.
Define an fo:region-before for each of those. Then, in your flow, call the applicable static-contents. Right now, it doesn't look like your BodyRestHeader is getting called at all when you generate your first chapter.
A very basic example:
<fo:root>
    <fo:layout-master-set>
        <fo:simple-page-master master-name="chapfirstopen">
            <fo:region-body/>
            <fo:region-before region-name="firstopenhead"/>
        </fo:simple-page-master>
        <fo:simple-page-master master-name="everythingelse">
            <fo:region-body/>
            <fo:region-before region-name="elsehead"/>
        </fo:simple-page-master>
        <fo:page-sequence-master master-name="firstchap">
          <fo:repeatable-page-master-alternatives>
            <fo:conditional-page-master-reference master-reference="chapfirstopen" page-position="first">
            <fo:conditional-page-master-reference master-reference="everythingelse">
          </fo:repeatable-page-master-alternatives>
        </fo:page-sequence-master>
        <fo:page-sequence-master master-name="everyotherchap">
          <fo:repeatable-page-master-alternatives>
            <fo:conditional-page-master-reference master-reference="everythingelse">
          </fo:repeatable-page-master-alternatives>
        </fo:page-sequence-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="firstchap">
        <fo:static-content flow-name="firstopenhead">
            <!--your first page static content.-->
        </fo:static-content>
        <fo:static-content flow-name="elsehead">
            <!--your every-other-page static content.-->
        </fo:static-content>
        <fo:flow><!--first chapter--></fo:flow>
    </fo:page-sequence>
    <fo:page-sequence master-reference="everyotherchap">
        <fo:static-content flow-name="elsehead">
            <!--your every-other-page static content.-->
        </fo:static-content>
        <fo:flow><!--other chapter--></fo:flow>
    </fo:page-sequence>
</fo:root>

Something along those lines.


text:
Q: Spring configuration file defined in multiple place Suppose I have created an spring application with following configurations
First::
<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>/app/*</url-pattern>
</servlet-mapping>

Spring will look for springweb-servlet.xml file. Then it will read all the bean difination from the file and creates bean objects
Here only single application context is created.
Second::
<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>/app/*</url-pattern>
</servlet-mapping>
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/service-context.xml
    </param-value>
</context-param>

Here first spring reads all the beans definations from service-context.xml file, which is the root spring context.
Then it reads all the bean definations from the springweb-servlet.xml file, which is the child spring context/WebApplicationContext.
Then all the merge the two parent-child context into one and create spring beans objects
Third::
What if I define the springweb-servlet.xml file in both place.
<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>/app/*</url-pattern>
</servlet-mapping>
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/springweb-servlet.xml,
        /WEB-INF/service-context.xml
    </param-value>
</context-param>


text:
Q: Pheanstalk reserve function I have just started using pheanstalk and am having an issue with the reserve function. I have the following code for a worker script:
<?php
  //... code that requires the autoload.php page among and other

  $queue = new Pheanstalk_Pheanstalk("127.0.0.1:11300");
  $queue->watch("action_tube");
  $job = $queue->reserve();

  //... code that would then output the information obtained from the job
?>

The issue I am having is that the code always gets stuck when preforming the reserve function. I know for a fact that it is getting stuck there because I went through the effort of running this code in a browser and using echo while commenting out code to see exactly where the code is getting stuck. It's as if an infinit while loop is happening inside the reserve function.
For instance, if I were to comment out $job = $queue->reserve(), the code would low freely and the page would immediately load, however if I don't comment it out, the circle loading in the browser keeps on going forever.
QUESTION: Why might I be having this problem? Is this normal for the reserve function? Does it just stand waiting for something to appear in the queue? I do actually have the "action_tube" queue created from a previous script so I would think that the reserve function would take some of these out. Might the condition of the queue cause a reserve function to stall? Any feedback is greatly appreciated!

A: Beanstalk reserve will run forever until the job is ready

reserve blocks until a job is ready, possibly forever. If that is not desired, we can invoke reserve with a timeout (in seconds) how long we want to wait to receive a job. If such a reserve times out, it will return None:

>>> beanstalk.reserve(timeout=0) is None
True

Found this here


text:
Q: Can I set recipient of mailto to a php string? is it possible to set my mailto recipient to the $email string?
I have a reservation form on my website and i want to have 2 buttons(Accept/Decline) in the mail that i get from it. The buttons should automatically open a new email windows with the set body and the recipient email from the form. My problem is that i cant get the email from the form into the mailto button.
some help would be nice :)
 <?php
include dirname(dirname(__FILE__)).'/mail.php';

error_reporting (E_ALL ^ E_NOTICE);

$post = (!empty($_POST)) ? true : false;

if($post){
    $name = stripslashes($_POST['name']);
    $email = trim($_POST['email']);
    $phone = stripslashes($_POST['phone']);
    $amount = stripslashes($_POST['amount']);
    $date = stripslashes($_POST['date']);
    $time = stripslashes($_POST['time']);

    $message .= "Telefonnummer: ".$phone."\n
"."Personen: ".$amount."\n
"."Datum: ".$date."\n
"."Uhrzeit: ".$time."\n
";
    $message .= '

<a href="mailto:<?php $email?>?Subject=Reservierung 73BB&Body=Hiermit bestaetigen wir Ihre Reservierung in der ...." target="_blank" style="font-size: 16px; font-family: Helvetica, Arial, sans-serif; color: #ffffff; text-decoration: none; border-radius: 3px; -webkit-border-radius: 3px; -moz-border-radius: 3px; background-color: #EB7035; border-top: 12px solid #EB7035; border-bottom: 12px solid #EB7035; border-right: 18px solid #EB7035; border-left: 18px solid #EB7035; display: inline-block;">Annehmen →

';
    $message .= '

<a href="mailto:<?php $email?>?Subject=Reservierung 73&Body=Leider müssen wir Ihre Reservierung ablehnen da wir schon ausgebucht sind" target="_blank" style="font-size: 16px; font-family: Helvetica, Arial, sans-serif; color: #ffffff; text-decoration: none; border-radius: 3px; -webkit-border-radius: 3px; -moz-border-radius: 3px; background-color: #EB7035; border-top: 12px solid #EB7035; border-bottom: 12px solid #EB7035; border-right: 28px solid #EB7035; border-left: 18px solid #EB7035; display: inline-block;">Ablehnen →

';

$headers = "From: $name\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    $mail = mail('tes@test.test', 'Reservierung', $message, $headers);

    if($mail){
        echo 'Ihre Reservierung wurde erfolgreich abgeschickt. Sie erhalten in kürze eine Bestätigung';
    }

}
?>

A: You do not have to open php tags again. Just add slashes and concatenate your variable.
$message .= '...<a href="mailto:' . $email . '?...';


text:
Q: Missing an asssembly reference - 'SingleSignOn' namespace I am getting this error when building my project on VS10 on Windows 7:
The type or namespace name 'SingleSignOn' does not exist in the namespace 'System.Web.Security' (are you missing an assembly reference?)
Just starting learning about ADFS and I am trying to make my web application supports ADFS logons.
Seem like I am missing the SingleSignOn.dll.
Is it because I am doing this on Windows 7 instead of of a Web server?
Pretty much lost right now.

A: So I presume you are using WIF?
WIF uses the Microsoft.IdentityModel dll.
Refer Get Started with Windows Identity Foundation (WIF)
Or else please provide more detail.


text:
Q: Statistics joint density function
Tried to solve question, but I am stuck because there is no range for y.
Should I consider range of $y$ like $x \le y \lt \infty$?

A: Marginal distributions:
$f_X(x)=\int_0^\infty f_{XY}(x,y) dy=\int_x^\infty \lambda^2\exp(-\lambda y)dy = \lambda \exp(-\lambda x)$
$f_Y(y)=\int_0^\infty f_{XY}(x,y) dx=\int_0^y \lambda^2\exp(-\lambda y)dx = \lambda^2 y \exp(-\lambda y)$
So
$f_X(x) f_Y(y) \ne f_{XY}(x,y)$
Now let $Z=X/(Y-X)$
$$
P(Z\le a)=
P(X\le a(Y-X))=
P(X\le aY/(1+a))=\int_0^\infty dy \big(\int_0^{ay/(1+a)} f_{XY}(x,y) dx\big)=\int_0^\infty ay/(1+a) \lambda^2\exp(-\lambda y) dy=a/(1+a)\int_0^\infty y\lambda^2\exp(-\lambda y)dy=a/(1+a)
$$
$$
P(Y\le b)=\int_0^b \lambda^2 y \exp(-\lambda y)dy
$$
and
$$
P(Z\le a, Y\le b)=a/(1+a)\int_0^b\lambda^2\exp(-\lambda y)dy
$$
So
$$
P(Z\le a, Y\le b)=P(Y\le b)P(Z\le a)
$$
and then $Y$ and $Z$ are independent.


text:
Q: Import packages for service bus sas connection I am trying to send messages to a queue. I have created below function to create the SAS Connection
def configureSASAuthentication (namespace: String, sasKeyName: String, sasKey: String, serviceBusRootUri: String): ServiceBusContract = {
  val config = ServiceBusConfiguration.configureWithSASAuthentication(namespace, sasKeyName, sasKey, serviceBusRootUri)
  val service: ServiceBusContract = ServiceBusService.create(config)
  return service
}

I am not sure which packages I need to import. i am getting below error:
error: not found: type ServiceBusContract
error: not found: value ServiceBusConfiguration
error: not found: type ServiceBusContract
error: not found: value ServiceBusService

A: You need to import Azure serivce bus classes. You should get them with the following assuming you have added the library to your project:
import com.azure.messaging.servicebus.*;

You should of course, have Azure messaging service bus and azure core imported. You could add the following dependencies to your build.sbt if you don't have it already:
"com.azure" % "azure-core" % "1.13.0",
"com.azure" % "azure-messaging-servicebus" % "7.0.2"


text:
Q: How to resolve a PHP-FPM Primary script unknown with a PHP-FPM and an Nginx Docker container? My situation is this, I have two Docker containers:

*

*Runs PHP-FPM on port 9000

*Runs nginx and has PHP files (should the PHP-FPM container have access to the files?)

I keep getting the following error:
FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 172.17.0.1, ser
ver: _, request: "GET / HTTP/1.1", upstream: "fastcgi://172.17.0.2:9000", host: "172.17.0.3"

I read here that this is "always related to a wrongly set SCRIPT_FILENAME in the nginx fastcgi_param directive."
The problem is, I don't know how to resolve it :-P
Config in Container 2:
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    charset UTF-8;
    root /var/www/WordPress;

    index index.php index.html index.htm;
    server_name _;
    location / {
        try_files $uri/ /index.php?$args;
    }
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_index index.php;
        fastcgi_pass 172.17.0.2:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME /var/www/WordPress$fastcgi_script_name;
        # set headers
        add_header Cache-Control $cc;
        access_log off;
        expires $ex;
    }
    location ~* \.(js|css|svg|png|jpg|jpeg|gif|ico|eot|otf|ttf|woff)$ {
        add_header Access-Control-Allow-Origin *;
        add_header Cache-Control "public";
        access_log off;
        log_not_found off;
        expires 1y;
    }
    location ~ /\.ht {
           deny all;
    }
}

A: Change root line to: root /var/www/WordPress/; for the $fastcgi_script_name doesn't include /

A: I'm no nginx expert, but literally every instance of fastcgi_param SCRIPT_FILENAME in the docs ends with $fastcgi_script_name, and yours doesn't.

A: I broke my brain trying to figure out why it is not working.
As usual, it's a matter of inattention.
So, in my nginx.conf I have lines:
set $root "/var/www/html/web";

root   $root;
set $bootstrap "index.php";
index  $bootstrap;

location / {
    index  index.html $bootstrap;
    try_files $uri $uri/ /$bootstrap?$args;
    expires    -1;
}

location ~ \.php$ {
    fastcgi_split_path_info  ^(.+.php)(.*)$;

    set $fsn /$bootstrap;
    if (-f $document_root$fastcgi_script_name) {
        set $fsn $fastcgi_script_name;
    }

    fastcgi_pass php:9000;
    fastcgi_index $bootstrap;
    include fastcgi_params;

    fastcgi_param  SCRIPT_FILENAME  $document_root$fsn;

    fastcgi_param  PATH_INFO        $fastcgi_path_info;
    fastcgi_param  PATH_TRANSLATED  $document_root$fsn;

    try_files $fsn =404;
    expires    -1;
}

include defaults.conf;

Very important to pay attention to line if (-f $document_root$fastcgi_script_name) {, because it is a check for existence.
In my docker-compose.yml I had different mounts in the nginx-container and the php-container:
php:
  image: aspendigital/octobercms:php7.2-fpm
  container_name: "${PROJECT_NAME}_php"
  volumes:
    - ./web:/var/www/html # <- this line is incorrect! Mounts MUST be identical!
nginx:
  image: wodby/nginx:$NGINX_TAG
  container_name: "${PROJECT_NAME}_nginx"
  depends_on:
    - php
  environment:
    NGINX_STATIC_OPEN_FILE_CACHE: "off"
    NGINX_ERROR_LOG_LEVEL: debug
    NGINX_BACKEND_HOST: php
    NGINX_SERVER_ROOT: /var/www/html/web/
    NGINX_CONF_INCLUDE: /var/www/html/nginx/*.conf
  volumes:
    - ./:/var/www/html:cached

So, replaсing in php-part the volume to the same as in the nginx-part solved my problem.
Be careful!


text:
Q: Latitude and Longitude is getting null in Flutter (Get Current Location) I am using this plugin flutter_geofence to get current location latitude and longitude. Below is the sample dart code, problem i facing is inside the Geofence body i can get latitude and longitude but when i try to access outside it is getting null.
return Scaffold(
          body: Container(
            child: GestureDetector(
                onTap: () {
                  var latitude;
                  var longitude;
                  Geofence.initialize();
                  Geofence.requestPermissions();
                  Geofence.getCurrentLocation().then((cd) {
                    latitude = cd!.latitude;
                    longitude = cd.longitude;
                  });
                  print(latitude); // getting null
                  print(longitude); // getting null
                },
                child: Center(child: Text('Test'))),
          ),
        );

DataService.class

class DataService {
Future<List<RecommendedForYouData>?> makeRequestRecommendedForYou(
      BuildContext context) async {
var latitude;
var longitude;
Geofence.initialize();
                  Geofence.requestPermissions();
                  Geofence.getCurrentLocation().then((cd) {
                    latitude = cd!.latitude;
                    longitude = cd.longitude;
                  });
                  print(latitude); // getting null
                  print(longitude); // getting null
}
}

A: This problem happend because your variables are outside the function (Geofence.getCurrentLocation().then ...), if you put this variables inside {} probably you can get different value than null, but I recommend create a new function outside the build method.

*

*If you use a Stateful Widget:

*

*Declare your variables in the top of your class.

*Use initState and call your methods inside (Geofence.initialize(), Geofence.requestPermissions(), Geofence.getCurrentLocation())

*You can create a specific function outside the initState to call inside of your build method.

*Inside your specific functions you need call the setState function to rebuild your UI.

I recommend you use a state management like bloc or provider instead of setState.


text:
Q: Looking for solution for exporting data to Excel with Vaadin We are looking for solution to export the data to excel in Vaadin application.
I have downloaded Vaadin excel exporter from GitHub https://github.com/bonprix/vaadin-excel-exporter which sounds to be a very useful utility but I am getting the error below when I am compiling vaadin-excel-exporter-demo project.
<vaadin.version>8.0.6</vaadin.version>
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project vaadin-excel-exporter-demo: Compilation failure: Compilation failure:
[ERROR] /C:/Java/Vaadin/VaadinProjetcs/vaadin-excel-exporter-master/vaadin-excel-exporter-master/vaadin-excel-exporter-demo/src/main/java/org/vaadin/addons/excelexporter/demo/DemoUI.java:[12,61] package org.vaadin.addons.excelexporter.configuration.builder does not exist
I've tried mvn clean and also delete the full .m2/repository local repository
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)
After searching on different forums it looks like maybe this add-on is missing from Maven repo. I have tried version 2.1 and LATEST.
<artifactId>vaadin-excel-exporter</artifactId>
    <packaging>jar</packaging>
    <!--version>2.1-SNAPSHOT</version-->
    <version>LATEST</version>
    <name>Excel Exporter</name>

So I have two questions.

*

*Has anybody had the same problem wih this tool and/or  maybe can explain what i am doing wrong.

*If this tool is not maybe available anymore can anyone please share the tool which I can use to export the grid data to Excel. I am new with Vaadin so  providing the code examples will be highly appreciated

Thanks
Alex

A: If you look at the add-on through Vaadin directory, you'll find the necessary additions to your pom.xml in the Maven section of the sidebar. In this case, like Erik said in the comments, you are likely missing
<repository>
   <id>vaadin-addons</id>
   <url>https://maven.vaadin.com/vaadin-addons</url>
</repository>

The directory page also includes code samples for using the component after you get the dependencies fixed, as well as other information about the add-on. I haven't tested whether the demo within GitHub works, but the add-on itself should be usable in your project regardless. The newest version published through the directory is 2.0.
If you want to compile the add-on locally rather than use it through the add-on repository, you need to first successfully compile the add-on module, and then use the exact version configured in the pom.xml. Currently the master branch seems to be using <version>2.1-SNAPSHOT</version>.


text:
Q: ref or value class for a list of 20000 objects I would need to maintain a list of about 20000 objects of a class. This class would be a managed wrapper for a c++ one. I would like to know if a ref class or a value class is they way to go.
I was told the following for pros/cons w.r.t GC
In the case of a value class, there is a single point to garbage collect vs reference class with a pointer, where there would be 20000 objects to garbage collect. Also there is no finalizer or destructor for value class and hence these objects wont end up in the finalization queue which is single threaded.
Can someone elaborate on the functioning of the GC in both these cases for large lists of objects.

A: In an answer of a question which I could not find at SO, @Hans Passant suggested that a .net struct (value class of C++ Cli) should be 16 bytes atmost.
So do not hesitate, use ref class.
Here is a useful link.

A: It's definitely easiest to use reference types - the 'Don't make me think' balance really tips this way

FWIW, I can perfectly see myself allocating a buffer of roughly 2Mb to contain an array of valuetype objects.
The thing is, how many times will these have to be transferred. If it just for a lookup table, the array of value objects will win a bit of performance, and perhaps other benefits[1]. This could be useful in a 'FlyWeight' kind of pattern
Just take care to only pass indexes to such objects around or the copying will soon make life miserable on your application
[1] e.g. quick serialization; the array indexes are under the control of the app developer, in contrast to the identity of a reference value. This can make for very efficient 'shallow' serialization of such lookup items by index value, which is useful in a marshalling type of use case (instead of actually marshalling the full reference object, you can refer to it by using the 'ubiquitous constant ID' that you have designed for that purpose).


text:
Q: ASP.NET login fails when I move the application folder Note that applicationName="/MyApplication" in web.config is the same in both locations. I am using ASPNET Roles. If I create a member in root folder "localhost\MyApplication" and try to login with that username in the 'moved' application "localhost\Test\MayApplication", I can not login with that user name. It does validate the password against the user name and it is correct, it just about permission, I am denied access.
On the other hand if I create a user in localhost\test\MyApplication and try to login with that application in the root application, I can successfuly login.
What am I missing?
Thank you for taking the time to answering my question.
Edit : Code
<providers>
            <clear/>
            <add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ABC_Connection" applicationName="/MyApplication" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="true" passwordFormat="Hashed"/>
</providers>

Edit 2:
Checked folder permission (the actual folder) and added IUSR, ASPNET but did not work out yet

A: I will answer my own question. The AppName = "" must be provided for the database provide just as your do for application. If you move the application, websever changes the application name based on where the application is. If you provide the application name, that name will not be changed and login issue will be resolved. I may refine this answer but just to provide a quick solution.


text:
Q: Windbg find missing dlls Background:
I am writing a app using an open source library. This open source libarary comes with many plugin dlls. Some of which we are using in our project (NOT all of them).
While in developement, we just consumed the library as a whole and everything worked fine.
Now when we are trying to build a shippable binary package, seems like we need to sort things out and find only those plugin binaries (dlls) from the open source lib which are in use.
These library comes with 100 of plugin dlls. During runtime, we just using a primary lib plugin dlls, which in turn loads up other dlls (Curently when we run the App, it loads both essential or non-essential dlls). We need to find out a way how to only pack those dlls which we are using in the code. And since these are plugins only, if the primary dll don't finds the non-essential dlls, then it is completely fine (App won't crash). We just have to help it locate the essential ones (without that pur either won't work or will crash).
Approach:
In order to find only the essential dlls, what I have done is removed all the dlls from the path and started placing one dlls each time to check, until our App start working. The problem is that with this approach it is going to take a long time. Rather than randomly picking each dlls I trying to use WinDbg to find out which missing dlls has caused the failure.
Question:
Is there a way in Windbg to identify from a dump, to see which missing dll has caused failure?

A: Your Question As it Appears is Ambiguous.
Most of commenters have provided you hints For a live Debugging Session Like.

*

*Ldr Snaps

*ProcMon

*Etw Traces

you seem to have asked For looking at it in a dump

Question: Is there a way in Windbg to identify from a dump, to see which missing dll has caused failure?

a plugin by its nature will be allowed to  fail gracefully By its Parent Binary and as such it will Create an Unload Event
This Will Be  reflected in the dump by lm Command
the Unloaded Modules will be listed at the end of Module List
:\>cdb -c "lm;q" -z c:\odbgdmp.dmp |awk "/Unloaded/,/quit/"
Unloaded modules:
66940000 66957000   OllyDumpEx_Imm17.dll
quit:

ntdll maintains an array 0x40 last unloaded dlls windbg Retrieves this from the same place as the below code does.
#include <stdio.h>
#include <windows.h>
typedef struct _RTL_UNLOAD_EVENT_TRACE {
    PVOID BaseAddress;SIZE_T SizeOfImage;ULONG Sequence;ULONG TimeDateStamp;
    ULONG CheckSum;WCHAR ImageName[32];
} RTL_UNLOAD_EVENT_TRACE, *PRTL_UNLOAD_EVENT_TRACE;

typedef VOID (WINAPI* RtlGetUnloadEventTraceEx) (
_Out_ PULONG *ElementSize,_Out_ PULONG *ElementCount,_Out_ PVOID  *EventTrace
);

RtlGetUnloadEventTraceEx evt;

int main(void) {
    //ollydbg plugin wont load in curproc will create an unloaded mod event
    LoadLibraryA("OllyDumpEx_Od20.dll");
    HMODULE nt=LoadLibraryA("ntdll.dll");
    if(nt != NULL){
        evt=(RtlGetUnloadEventTraceEx)GetProcAddress(nt,
        "RtlGetUnloadEventTraceEx");
        PULONG  elsiz = NULL, elcnt = NULL;PVOID evarr = NULL;
        evt(&elsiz,&elcnt,&evarr);
        printf("%p %p %p\n" , elsiz,elcnt,evarr);
        printf("%x %x %x\n" , *elsiz,*elcnt,*(int*)evarr);
        PRTL_UNLOAD_EVENT_TRACE u1=((PRTL_UNLOAD_EVENT_TRACE)(*(int*)evarr));
        printf("bas\t%p\nsiz\t%x\nSeq\t%x\nstamp\t%x\nCsum\t%x\nname\t%S\n",
        u1->BaseAddress,u1->SizeOfImage,u1->Sequence,u1->TimeDateStamp,
        u1->CheckSum,u1->ImageName);
    }
    return 0;
}

on executing
:\>UnloadModList.exe
7706CDA0 7706CD9C 77067144
5c 40 1fafd8
base    676F0000
size    19000
Seq     0
stamp   55953f77
Chksum  12b14
imgname OllyDumpEx_Od20.dll

corroboration of dll details which failed to load
:\>dumpbin /headers OllyDumpEx_Od20.dll | grep -iE "CheckSum|Stamp|size of image|image base"
        55953F77 time date stamp Thu Jul  2 19:11:11 2015
        6A680000 image base (6A680000 to 6A698FFF)
           19000 size of image
           12B14 checksum


text:
Q: How to copy rows from one workbook to another based on text in a specific column? I want to copy all data in my template into four other workbooks based on the text in column "G".
I want it below any existing data in the target file.
All four workbooks would be open when this is running.
I get a compile error

"method or data member not found"

in For Each c In Source.Range("G1:G" & Source**.Cells**(Rows.Count, 1).End(xlUp).Row)
Sub CopyPastedata()
'copy and paste data from template into existing workbooks

Dim c As Range
Dim Source As Workbooks
Dim Target As Workbooks
Dim Target1 As Workbooks
Dim Target2 As Workbooks

'define source and targets for workbooks and worksheets
Set Source = Workbooks("CostIncreaseTemplate.xlsm").Worksheets("Sheet1")
Set Target = Workbooks("Fresh.xlsx").Worksheets("Fresh")
Set Target1 = Workbooks("CannedGoods.xlsx").Worksheets("CannedGoods")
Set Target2 = Workbooks("Baking.xlsx").Worksheets("Baking")

'Specify where to search and copy the entire row if criteria is met and paste in target file in the next blank cell

For Each c In Source.Range("G1:G" & Source.Cells(Rows.Count, 1).End(xlUp).Row)
    If c = "Fresh" Then
        c.EntireRow.Copy
        Target.Range("A" & Rows.Count).End(xlUp).Offset(1).PasteSpecial xlPasteValues
    ElseIf c = "CannedGoods" Then
        c.EntireRow.Copy
        Target1.Range("A" & Rows.Count).End(xlUp).Offset(1).PasteSpecial xlPasteValues
    ElseIf c = "Baking" Then
        c.EntireRow.Copy
        Target2.Range("A" & Rows.Count).End(xlUp).Offset(1).PasteSpecial xlPasteValues
    End If
Next c

End Sub

A: Export Rows

*

*The error occurs because you have declared Source as a workbooks collection object which has no .Range and no .Cells method or data member.

Sub ExportRows()

    Dim Source As Worksheet
    Set Source = Workbooks("CostIncreaseTemplate.xlsm").Worksheets("Sheet1")
    ' If the code is in 'CostIncreaseTemplate.xlsm', replace the previous line
    ' with:
    'Set Source = ThisWorkbook.Worksheets("Sheet1")
    Dim srg As Range
    Set srg = Source.Range("G2", Source.Cells(Source.Rows.Count, "G").End(xlUp))
    Dim scCount As Long: scCount = Source.Columns.Count

    Dim Target As Worksheet
    Dim Target1 As Worksheet
    Dim Target2 As Worksheet

    Set Target = Workbooks("Fresh.xlsx").Worksheets("Fresh")
    Set Target1 = Workbooks("CannedGoods.xlsx").Worksheets("CannedGoods")
    Set Target2 = Workbooks("Baking.xlsx").Worksheets("Baking")

    Dim sCell As Range
    Dim tCell As Range

    For Each sCell In srg.Cells
        If StrComp(CStr(sCell.Value), "Fresh", vbTextCompare) = 0 Then
            Set tCell = Target.Cells(Target.Rows.Count, "A").End(xlUp)
        ElseIf StrComp(CStr(sCell.Value), "CannedGoods", vbTextCompare) = 0 Then
            Set tCell = Target1.Cells(Target1.Rows.Count, "A").End(xlUp)
        ElseIf StrComp(CStr(sCell.Value), "Baking", vbTextCompare) = 0 Then
            Set tCell = Target2.Cells(Target2.Rows.Count, "A").End(xlUp)
        End If
        If Not tCell Is Nothing Then
            ' When copying values only, copying by assignment is most efficient:
            tCell.Offset(1).Resize(, scCount).Value = sCell.EntireRow.Value
            Set tCell = Nothing
        End If
    Next sCell

    MsgBox "Rows exported.", vbInformation

End Sub


text:
Q: Create a hr radial-gradient below the line There is a wonderful hr gradient here in the answer (the jsfiddle he links to shows an updated css) - Create a beautiful horizontal line with CSS only. It is exactly what I am after but I would like the gradient to appear below then line instead of above it.
The html is very simple -

hr.fancy-line {
  border: 0;
  height: 1px;
  position: relative;
  margin: 0.5em 0;
  /* Keep other elements away from pseudo elements*/
}
hr.fancy-line:before {
  top: -0.5em;
  height: 1em;
}
hr.fancy-line:after {
  content: '';
  height: 0.5em;
  /* half the height of :before */
  top: 1px;
  /* height of hr*/
}
hr.fancy-line:before,
hr.fancy-line:after {
  content: '';
  position: absolute;
  width: 100%;
}
hr.fancy-line,
hr.fancy-line:before {
  background: -moz-radial-gradient(center, ellipse cover, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 75%);
  background: -webkit-gradient(radial, center center, 0px, center center, 75%, color-stop(0%, rgba(0, 0, 0, 0.1)), color-stop(75%, rgba(0, 0, 0, 0)));
  background: -webkit-radial-gradient(center, ellipse cover, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 75%);
  background: -o-radial-gradient(center, ellipse cover, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 75%);
  background: -ms-radial-gradient(center, ellipse cover, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 75%);
  background: radial-gradient(ellipse at center, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 75%);
}
body,
hr.fancy-line:after {
  background: #f4f4f4;
}

I have tried various different things but cannot get it to work, plus whenever I change it, the line itself disappears.
Please can someone help... thank you

A: hr.fancy-line:after {
    content:'';
    height: 0.5em;
    top: -8px;  /*change or bottom:0; */
}

hr.fancy-line {
  border: 0;
  height: 1px;
  position: relative;
  margin: 0.5em 0;
}
hr.fancy-line:before {
  top: -0.5em;
  height: 1em;
}
hr.fancy-line:after {
  content: '';
  height: 0.5em;
  top: -8px; /*or bottom:0; */
}
hr.fancy-line:before,
hr.fancy-line:after {
  content: '';
  position: absolute;
  width: 100%;
}
hr.fancy-line,
hr.fancy-line:before {
  background: -moz-radial-gradient(center, ellipse cover, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 75%);
  background: -webkit-gradient(radial, center center, 0px, center center, 75%, color-stop(0%, rgba(0, 0, 0, 0.1)), color-stop(75%, rgba(0, 0, 0, 0)));
  background: -webkit-radial-gradient(center, ellipse cover, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 75%);
  background: -o-radial-gradient(center, ellipse cover, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 75%);
  background: -ms-radial-gradient(center, ellipse cover, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 75%);
  background: radial-gradient(ellipse at center, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 75%);
}
body,
hr.fancy-line:after {
  background: #f4f4f4;
}


text:
Q: Game of LIfe: Modifying array values in numpy while iterating with conditions I am a Physics student with very basic knowledge of Python and I have been trying to look for a simple solution to this problem, but I have only been running around in circles. I am writing my own rendition for a program called "The Game of Life" (WikiPage). The rules are straightforward:

The Game consists of so called cells that live on a 2 dimensional grid. These cells evolve in cycles. The initial pattern of dead and live cells is the first generation. The second generation evolves from applying some simple rules simultaneously to all cells. The rules are:
Cells die if they dont have enough company (less than 2 cells neighboring)
Cells die of overpopulation if there are 4 or more cells neighboring.
A dead cell is reborn if there are (exactly) 3 cells neighboring.

This is a part of an assignment, but I am not looking for a spoon-fed solution. We are required to use numpy and arrays.
My approach was to generate an array board with an initial feed of random 1's and 0's. Then, in a function, I create another array with one row and one column greater than board which will store the new values and then feed it back. I iterate (I know its not pythonic to iterate over an array, so I am open to suggestions and alternatives) over the elements i and j and make a sum (np.sum) of the subarray nBlock[i-1:i+1,j-1:j+1]. If the sum is greater than 4 or less than 4, then the element nBlock[np.array([i,j])] becomes zero (cell dies), otherwise, it is 1 (cell lives, or is reborn).
The problem is, this doesn't work. The code is as follows:
import numpy as np
import matplotlib.pyplot as plot
import time as t
%matplotlib inline

def printBoard(board):
    im = plot.imshow(board, cmap='Greys', interpolation='none')
    plot.show()
    plot.close()

def initializeBoard():
    board = np.random.randint(2, size=(100, 100))
    return board

board = initializeBoard()
printBoard(board)

def checkAlive():
    if 1 not in board:
        print("All cells are dead! Life is over!")
        return 0
    else:
        return board

def calculateNeighbours(board):
    nBlock = np.zeros((102, 102))
    nBlock[1:101, 1:101] = board

    for i in range(1, 100):
        for j in range(1, 100):
            checksum = np.sum(nBlock[i-1:i+2, j-1:j+2])

            nBlock[:,0] = 0
            nBlock[0,:] = 0

            if checksum == 4:
                nBlock[np.array([i,j])] = 1
            elif checksum > 4 or checksum < 4:
                nBlock[np.array([i,j])] = 0

    return nBlock

def play(board):
    for i in range(1, 10):
        neighbours = calculateNeighbours(board)

        board = neighbours[1:101, 1:101]

        board = checkAlive()

        printBoard(board)

play(board)

The array board doesn't get modified. It returns the same board.
Another odd thing I noticed is that if I remove the conditions in my for loop, the array is successfully modified. For example,
for i in range(0, 100):
    for j in range(0, 100):
        board[np.array([i,j])] = 1

gives me a matrix which has all elements changed to 1. So there is something about the if...else conditions which is not allowing me to manipulate the data in my array.
Any and all help is appreciated :)

A: Error:
Your major error is in your interface logic for checkAlive.  You have no parameters to the routine; when you do find a live cell, you return the symbiont board, which play immediately assigns to its parameter board.
The board in play is a local variable: changing this does not change the global board you initialized.  In contrast, since checkAlive has no local variable, what it returns is the global variable board, which is never changed, anywhere in the program.
Solution:
Since checkAlive doesn't alter the board, don't return it.  Instead, return a simple boolean.  play can check this and terminate the program, if needed.
Also:
Your cell health algorithm is wrong in a couple of respects.  Walk through the logic and repair.  Most notably, you use a value of 4 to let a cell live; this is massively incorrect.  2 neighbours leave the cell in its current state; 3 neighbours make the cell live; any other number kills it.
Your current logic includes the cell itself in the count.  This does not differentiate between a live cell with 3 friends and a dead cell with 4.  As a result, you're creating some cells incorrectly, and you're killing off viable cells (live cell with 2 friends).


text:
Q: VBS script to list interface and MAC I'm trying to make simple script that show computer name, logged user name, IP address, and ethernet interface (wired ) name and it's MAC:
intCount = 0
strMAC   = ""
' We're interested in MAC addresses of physical adapters only
strQuery = "SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID > ''"

Set objWMIService = GetObject( "winmgmts://./root/CIMV2" )
Set colItems      = objWMIService.ExecQuery( strQuery, "WQL", 48 )

For Each objItem In colItems
If objItem.AdapterType = "Ethernet 802.3" then
If InStr( strMAC, objItem.MACAddress ) = 0 Then
    strMAC   = strMAC & ", " & objItem.MACAddress
    Name = objItem.Name & vbCRLF
    intCount = intCount + 1
End If
End If
Next

' Remove leading comma
If intCount > 0 Then strMAC = Mid( strMAC, 2 )
dim NIC1, Nic, StrIP, CompName
Set NIC1 =
GetObject("winmgmts:").InstancesOf("Win32_NetworkAdapterConfiguration")
For Each Nic in NIC1
if Nic.IPEnabled then
StrIP = Nic.IPAddress(i)
Set WshNetwork = WScript.CreateObject("WScript.Network")
Dim objNetwork
Set objNetwork = CreateObject("WScript.Network")
CompName = WshNetwork.Computername
Dim WMI, Configs, Config, Adapters, Adapter
Set WMI = GetObject("winmgmts:{impersonationlevel=impersonate}root/cimv2")

strUserName = wshNetwork.UserName

MsgBox "IP Adres: "&StrIP & vbNewLine _
& "Computer Name: "&CompName & vbNewLine _
& "Login: "&strUserName & vbNewLine _
& "Interface and MAC: "& Name, & strMAC ,4160,"Information about  IP"

 wscript.quit
 end if
 next

but it's not working, could anyone help me?

A: Change
Set NIC1 =
GetObject("winmgmts:").InstancesOf("Win32_NetworkAdapterConfiguration")

to one line
Set NIC1 = GetObject("winmgmts:").InstancesOf("Win32_NetworkAdapterConfiguration")

and remove the , here:
& "Interface and MAC: "& Name, & strMAC ,4160,"Information about  IP"

==>
& "Interface and MAC: "& Name & strMAC ,4160,"Information about  IP"


text:
Q: google maps in webview app must be in google maps app I have an webview app. But i want to make a route description in it with navigation.
When i have an google link, i want to open the Google Maps APP. Now it's opening in the WebView.
How can i make this?
This is my app so far:
public class FullscreenActivity extends Activity {

private WebView webView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fullscreen);

    webView = (WebView) findViewById(R.id.webView);
    webView.setWebViewClient(new myWebClient());
    webView.loadUrl("http://www.mywebsite.nl");
    webView.setVerticalScrollBarEnabled(false);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
}

public class myWebClient extends WebViewClient
{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
    // TODO Auto-generated method stub
    super.onPageStarted(view, url, favicon);
}

@Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {

 if (url.startsWith("tel:")) {
         Intent intent = new Intent(Intent.ACTION_DIAL,
                 Uri.parse(url));
         startActivity(intent);
 }else if(url.startsWith("http:") || url.startsWith("https:")) {
     view.loadUrl(url);
 }
 return true;

    }
}

    public static void maps(Activity activity, String address) {

   try {

    Intent intent = new Intent(Intent.ACTION_VIEW,         Uri.parse("http://maps.google.com/maps?q=" + address));
    activity.startActivity(intent);

} catch (ActivityNotFoundException e) {
    Toast.makeText(activity, activity.getString(R.id.webView), Toast.LENGTH_SHORT).show();
}

public static void navigation(Activity activity, String address) {

try {

    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + address));
    activity.startActivity(intent);

} catch (ActivityNotFoundException e) {

    Toast.makeText(activity, activity.getString(R.id.webView), Toast.LENGTH_SHORT).show();
}
 }

public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
        webView.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
   }

Thanx,
Marvin

A: You can use this methods to start Maps or Navigation Apps :
public static void maps(Activity activity, String address) {

    try {

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?q=" + address));
        activity.startActivity(intent);

    } catch (ActivityNotFoundException e) {
        Toast.makeText(activity, activity.getString(R.string.error_no_app_found), Toast.LENGTH_SHORT).show();
    }
}

public static void navigation(Activity activity, String address) {

    try {

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + address));
        activity.startActivity(intent);

    } catch (ActivityNotFoundException e) {
        Toast.makeText(activity, activity.getString(R.string.error_no_app_found), Toast.LENGTH_SHORT).show();
    }
}


text:
Q: storing files in mongodb using gridfs and mongoose I have the following code
gridfs.js has the following code that writes file bytes
exports.putFile = function(path, name, options, fn) {
    var db;
    db = mongoose.connection.db;
    options = parse(options);
    options.metadata.filename = name;
    return new GridStore(db, name, "w", options).open(function(err, file) {
        if (err) {
            return fn(err);
        }
        return file.writeFile(path, fn);
    });
};

The mongoose schema is defined below. The mongoose schema has a file name and the file itself.
var fs = require('fs');
var mongoose = require('mongoose');
var db = mongoose.connection;
var gridfs = require('./gridfs');
var Schema = mongoose.Schema;

var trackDocsSchema = mongoose.Schema(
        {
            _id : Schema.Types.ObjectId,
            docName: 'string',
            files: [ mongoose.Schema.Mixed ]
        }
);

trackDocsSchema.methods.addFile = function(file, options, fn) {
    var trackDocs;
    trackDocs = this;
    return gridfs.putFile(file.path, file.name, options, function(err, result) {
        if (err) console.log("postDocsModel TrackDocs Error: " + err);

        trackDocs.files.push(result);
        return trackDocs.save(fn);
    });
};

var TrackDocs = mongoose.model("TrackDocs", trackDocsSchema);

The server code that is invoked is below.
exports.uploadFile = function (req, res) {
    console.log("uploadFile invoked");
          var trackDocs, opts;
        trackDocs = new TrackDocs();
        trackDocs._id = mongoose.Types.ObjectId(req.body._id);
        trackDocs.docName = req.body.docName;
        opts = {
            content_type: req.files.file.type
        };

        return trackDocs.addFile(req.files.file, opts, function (err, result) {
            if (err) console.log("api TrackDocs Error: " + err);

            console.log("Result: " + result);
            trackDocs.save();
            console.log("Inserted Doc Id: " + trackDocs._id);
            return res.json(true);
        });
    };
});

When I run the folowing code, I get an error
api TrackDocs Error: RangeError: Maximum call stack size exceeded and nothing is added to GridFS. However, if I upload the same file again, it does save it into GridFS.
Notice there are two trackDocs.saves. I am not sure if that is causing the issue or something else.
I am new to NodeJS and Mongoose so any assitance will be much appreciated.
Thanks,
Melroy

A: Not sure whether this helps or not, but it has helped me in the past.
Not surprisingly, different browsers have different call stack sizes. Also not surprisingly, the method that they use to determine the call stack varies as well. The various call stack sizes I could measure are (give or take, might be off by 1 or 2):
We ran some tests ourselves in order to get the call stack sizes on other browsers/hosts/OSs using this simple code:
var i = 0;

function recurse () {
    i++;
    recurse();
}

try {
    recurse();
} catch (ex) {
    alert('i = ' + i + '\nerror: ' + ex);
}

http://javascriptrules.com/2009/06/30/limitation-on-call-stacks/
In saying that an option could be passing --max-stack-size to node.
Set max v8 stack size (bytes)
node --max-stack-size 32000 app.js
NOTE: Help prints it as --max-stack-size, in node -v v0.10.x+ you need to use --stack-size instead.


text:
Q: iCloud & iCloud Drive saving core data multiple devices with and without iOS 9 I have searched and searched but it is not entirely clear, I haven't programmed much in years, I have to update an old app for a client that will be using iPods iOS 6 and new iPhones with iOS 9 logged into the same iCloud account.
Will changes to core data of app on an iOS 6 device update content for the iOS 9 device?
I have not experienced problems with updates to iCloud in NSSUserDefaults when testing on iOS 6 and ios9 devices (with iCloud drive disabled)
I cannot get iCloud for core data to work on ios9 iCloud drive disabled, so I need to update to iCloud Drive... But I am worried about data on other devices not updated.  Debugging nightmare?

A: Core Data with iCloud is really flaky, I really don't recommend it.
Devices that have switched to iCloud Drive will make changes that won't be visible to those that haven't (including those devices that don't support it, most definitely those running iOS 6). Not sure about the opposite, but it's probably the case as well.