text:
Q: How to extract links from a page using Beautiful soup I have a HTML Page with multiple divs like:

sample post – example 1 post

sample post – example 2 post

and I need to get the  value for all the divs with class post-info-wrap I am new to BeautifulSoup
so I need these urls:

*

*https://www.example.com/blog/111/this-is-1st-post/

*https://www.example.com/blog/111/this-is-2nd-post/

*and so on...
I have tried:
import re
import requests
from bs4 import BeautifulSoup

r = requests.get("https://www.example.com/blog/author/abc")
data = r.content  # Content of response

soup = BeautifulSoup(data, "html.parser")
for link in soup.select('.post-info-wrap'):
   print link.find('a').attrs['href']

This code doesnt seem to be working. I am new to beautiful soup. How can i extract the links?

A: You can use soup.find_all:
from bs4 import BeautifulSoup as soup
r = [i.a['href'] for i in soup(html, 'html.parser').find_all('div', {'class':'post-info-wrap'})]

Output:
['https://www.example.com/blog/111/this-is-1st-post/', 'https://www.example.com/blog/111/this-is-2nd-post/']

A: link = i.find('a',href=True) always not return anchor tag (a), it may be return NoneType, so you need to validate link is None, continue for loop,else get link href value.
Scrape link by url:
import re
import requests
from bs4 import BeautifulSoup
r = requests.get("https://www.example.com/blog/author/abc")
data = r.content  # Content of response
soup = BeautifulSoup(data, "html.parser")

for i in soup.find_all('div',{'class':'post-info-wrap'}):
   link = i.find('a',href=True)
   if link is None:
       continue
   print(link['href'])

Scrape link by HTML:
from bs4 import BeautifulSoup
html = '''

sample post – example 1 post

sample post – example 2 post

'''

soup = BeautifulSoup(html, "html.parser")

for i in soup.find_all('div',{'class':'post-info-wrap'}):
   link = i.find('a',href=True)
   if link is None:
       continue
   print(link['href'])

Update:
from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get("https://www.example.com/blog/author/abc")

soup = BeautifulSoup(driver.page_source, "html.parser")

for i in soup.find_all('div', {'class': 'post-info-wrap'}):
    link = i.find('a', href=True)
    if link is None:
        continue
    print(link['href'])

O/P:
https://www.example.com/blog/911/article-1/
https://www.example.com/blog/911/article-2/
https://www.example.com/blog/911/article-3/
https://www.example.com/blog/911/article-4/
https://www.example.com/blog/random-blog/article-5/

For chrome browser:
http://chromedriver.chromium.org/downloads
Install web driver for chrome browser:
https://christopher.su/2015/selenium-chromedriver-ubuntu/
selenium tutorial
https://selenium-python.readthedocs.io/
Where '/usr/bin/chromedriver' chrome webdriver path.


text:
Q: API for supporting Echo Cancellation in Windows Vista/7 In 2007, during the fever over DRM being included in Windows Vista, a Windows Vista Team blog was created to respond to a lot of the concerns. One of the questions responded to the ability of VoIP software to perform echo cancellation when running on Windows Vista.
This is what Nick White had to say by way of an FAQ:

Will echo cancellation work less well for premium content?
We believe that Windows Vista provides applications with access to sufficient information to successfully build high quality echo cancellation functionality.

What information does Windows Vista provide to allow applications to build high quality echo cancellation functionality?
Note: Reading that statement, i get the impression that Windows Vista provides sufficient information to allow applications to successfully build high-quality echo cancellation functionality. Presumably the way Windows provides this information is through an API.
Echo cancellation works by sampling the playing output, and "subtracting it" from the recorded microphone input.
Unfortunately, as MSDN notes, one cannot always sample playing output:

Windows Vista provides digital rights
management (DRM). Content providers
rely on DRM to protect their
proprietary music or other content
from unauthorized copying and other
illegal uses. WASAPI does not permit
loopback recording of digital streams
that contain DRM-protected content.
Similarly, a trusted audio driver does
not permit a loopback device to
capture digital streams that contain
protected content. Windows Vista
allows only trusted drivers to play
protected content. For more
information about trusted drivers and
DRM, see the Windows DDK
documentation.

Presumably that means that using Loopback Mode from WASAPI is not the intended method to provide echo-cancellation services.
What is the intended API to allow the implementation of high quality echo cancellation?
Note: This is related to, but separate from, another question i asked: How to sample output audio mix?. This question is specifically looking for an expansion of the response by the Window Vista team that echo-cancellation is possible in Windows. This question is looking for the API; it can be a separate question of how to use it.
Googling for an answer, i get the impression that (while performing echo-cancellation) an application is allowed to sample DRM protected content, but the content will be degraded (i.e. "sufficient information"). This would make any echo-cancellation worse, but still possible.
Or was the Windows team implying "sufficient for most cases, but not while the user is listening to a song or playing a movie" - and that it is in fact not possible to successfully build high quality echo cancellation functionality?

Update: It should be noted i'm not looking for an echo-cancellation API, i'm looking for an API to sample the playing output - which is what's required to implement echo cancellation. Unless of course Windows Vista provides an echo-cancellation API (which is how they continue to protect Premium content). But i've not seen an echo-cancellation API either.

A: http://msdn.microsoft.com/en-us/library/ff819492(v=VS.85).aspx
If you are looking for an API to do echo cancellation, it looks like the voice capture dsp has built in support for acoustic echo cancellation.
Example:
http://msdn.microsoft.com/en-us/library/dd443455(VS.85).aspx

redpajama_set_name: RedPajamaStackExchange


text:
Q: ¿Cargar un combobox desde código (sin DB) asignando un valor a cada uno? ¿Cómo puedo cargar datos desde código y por detrás valores para cada uno?
Valor   Tipo
  1     Perro
  2     Gato
  3     Ave

He tratado con el siguiente código:
comboBox1.Items.Add(1, "Perro");

A:

    public partial class Form : Form
        {
        private void ItemsCombobox()
            {
            comboBox1.Items.Add(new ClassItems("Perro", 1));
            comboBox1.Items.Add(new ClassItems("Gato", 2));
            comboBox1.Items.Add(new ClassItems("Ave", 3));
            }
        public FormXX()
            {
            InitializeComponent();
            ItemsCombobox();
            }
        private void btnVerDatos_Click(object sender, EventArgs e)
            {
            ClassItems ItemCmb = (ClassItems)comboBox1.SelectedItem;
            MessageBox.Show(ItemCmb.Name);
            MessageBox.Show(ItemCmb.Value.ToString());
            }
        }

tengo una clase ClassItems

    class ClassItems
        {
        public string Name;
        public int Value;

        public ClassItems(string name, int value)
            {
            Name = name;
            Value = value;
            }
        public override string ToString()
            {
            return Name;
            }
        }

Solucion Cercana : Stackoverflow


text:
Q: Why is the slope of an decreasing function is less than or equal to zero? Let $f(x)=(x^2+a)e^{-x}$ be a decreasing function on the set of real numbers. Find the range of a interval of the real numbers that allows a reduction in the total set of real numbers.
$${d\over dx} f(x)=2x \cdot e^{-x}-(x^2+a) \cdot e^{-x}
=(2x-x^2-a) \cdot e^{-x} \le 0$$
$$e^{-x} \gt 0,-x^2+2x-a \le 0\Rightarrow4-4a \le 0\Rightarrow4 \le 4a\Rightarrow1 \le a$$
Shouldn't it be $1 \lt a$?

A: If you think about it carefully you will see that a function can be strictly decreasing even if its derivative has isolated zeros. Consider $f(x)=-x^3$ for a simple example.
Note also that "decreasing" can be used to mean "non-increasing" in some contexts, with "strictly decreasing" used for functions which are never stationary.


text:
Q: Flutter keyboard_actions widget area scrolling is not working My task was to add button Done to text keyboard which hides keyboard after CupertinoTextField is filled with value. I used keyboard_actions lib and it worked fine, but the area of FormKeyboardActions() widget became unscrollable - scrolling is broken after my implementation of
keyboard_actions lib.
I tried to add directly CupertinoTextField to FormKeyboardActions() as a child, but it is also not working.
The code of parent PageTemplate widget:
@override
Widget build(BuildContext context) {
return GestureDetector(
  onTap: () {
    FocusScope.of(context).unfocus();
  },
  child: Scaffold(
    body: FormKeyboardActions(
      child: SafeArea(  //child
          child: Padding(
            padding: DesignPadding.V16__X,
            child: ListView(
              shrinkWrap: true,
              children: this.children
            ),
          ),
        ),
    ),
    floatingActionButton: Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 8),
      child: this.floatingActionButton,
    ),
    floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
  ),
 );
 }

The widget with CupertinoTextField:
class _ProductEditCommentState extends State<ProductEditComment> {
final FocusNode focusNode = FocusNode(skipTraversal: true);

KeyboardActionsConfig _buildConfig(BuildContext context) {
return KeyboardActionsConfig(
  keyboardActionsPlatform: KeyboardActionsPlatform.ALL,
  keyboardBarColor: Colors.grey[200],
  nextFocus: false,
  actions: [
    KeyboardAction(
      focusNode: focusNode,
      closeWidget: Padding(
        padding: DesignPadding.V8__X,
        child: Text(
          "Done",
          style: TextStyle(
            color: DesignColors.BLACK,
            fontSize: DesignFonts.FONT_SIZE__16,
            fontFamily: DesignFonts.FONT_FAMILY__MEDIUM,
          ),
        ),
      ),
    ),
  ],
);
}

@override
void initState() {
 FormKeyboardActions.setKeyboardActions(context, _buildConfig(context));
 super.initState();
}

@override
void dispose() {
 super.dispose();
}

@override
Widget build(BuildContext context) {
 ProductEditBloc bloc = BlocProvider.of(context);
 return  SingleChildScrollView(
       child: CupertinoTextField(
         focusNode: focusNode,
         maxLines: null,
         onChanged: this.widget.onChanged,
         controller: this.widget.controller,
         keyboardType: TextInputType.multiline,
         decoration: BoxDecoration(border: null),
         textCapitalization: TextCapitalization.sentences,
         placeholder: bloc.productComment == null || bloc.productComment.isEmpty
             ? "Добавить заметку"
             : bloc.productComment,
         placeholderStyle: TextStyle(
             color: DesignColors.GREY_CHROME,
             fontSize: DesignFonts.FONT_SIZE__14,
             fontFamily: DesignFonts.FONT_FAMILY__REGULAR),
         style: TextStyle(
             color: DesignColors.GREY_COAL,
             fontSize: DesignFonts.FONT_SIZE__14,
             fontFamily: DesignFonts.FONT_FAMILY__REGULAR),
         padding: EdgeInsets.only(
           left: DesignPadding.V10,
           top: DesignPadding.V14,
           bottom: DesignPadding.V20,
         ),
       ),
     );
   }
  }

The implementation of ProductEditComment widget:
@override
Widget build(BuildContext context) {
 return BlocProvider(
     bloc: bloc,
     child: PageTemplate(
children: <Widget>[
    Heading(
        title: "Заметка",
        style: DesignFonts.STYLE_TITLE,
      ),
      StreamBuilder<String>(
          stream: bloc.outComment,
          initialData: this.widget.product?.comment,
          builder: (context, snapshot) {
            return ProductEditComment(
              name: snapshot.data,
              onChanged: bloc.setComment,
              controller: bloc.commentController,
            );
          }),
 ]
 )


text:
Q: How to read thousands lines of code without any documentation? Previously I was searching for a good TimeLine control for a WPF project. I found an answer in Here which direct me to this CodePlex project.
Now I want to change code to feed my culture needs. But there are some mismatches!
My question is:
How you interact with such thousands lines of code?
EDIT:
Any shortcut will be great!

A: *

*Step through the code

*Rename as needed

*Refactor as needed

*Repeat until you completely understand

... and the code will thank you for it. ;-)

A: Take single action, debug (again and again) the code to find how that action is accomplished. Write down the same in simple language to get a better understanding!

A: Something that Joel Spolsky wrote way back when on his blog (can't find the article now) really stuck with me regarding this:
He said how code is not natural human language, but as programmers, we are easily lulled into thinking that it is, and that we should be able to read it as such. Consequently, a lot of us look at new code and expect to be able to just "read it" and understand it immediately, as if it was a block of text in English.
So I think the key is to basically just be slow, methodical, and scientific. And as others have said - comment it (and even refactor) as you go. Don't fall into the mindset of "I should just look at it and understand immediately".
Oh, and yes, I still fall into this trap myself sometimes. "Do as I say, not as I do", and all that. :)

A: SE-Radio interviewed Dave Thomas about this very subject
This podcast episode has many tips and techniques to enter the 'culture' of the project and understand how the original inhabitants lived.

A: You add comments to the source code when you have understood it enough to be able to do so.  Refactor these comments vigorously as you understand more and more.

A: I had to do this recently with a project of over 100,000 LOC.  My first idea was that it's easier to see patterns from graphs of 100 or even 1000 nodes than from 100,000 lines of text.
So I spent 45 minutes and wrote a short (<100LOC) Python program to parse what I needed from it, and draw the object relationships.  I generated Graphviz source, which is a really easy language to generate.  (There's nothing special about Python here: Ruby or C# or Common Lisp or whatever could do it just as well.)
On other projects, I've seen people use Graphviz for module dependencies, call graphs, version history, all kinds of things.  Greatest program visualization meta-tool ever.
(Maybe it's because I took compilers, but I find it weird that when a programmer is faced with a problem, the answer seems to always be "write a program!", except when the problem involves the source code to a program.  :-)

A: Step through it in the debugger as it runs, its nearly the only way to understand a new, large code base.

A: Understand that there really are no shortcuts to grokking in fullness.  (And if you have trouble with that phrase, your education has been SORELY neglected.  It is from "Stranger In a Strange Land", by Robert A. Heinlein.)
Read it, one page at a time, one routine at a time.  Add comments.  Draw pictures of major data structures.  Recognize algorithms.  Draw upon previous knowledge.
Resist the temptation to crank up the debugger.  The debugger viewport is too small: you see one line at a time, but you really don't see where you've been or where you're going.

A: Whatever you do write up as much as you can as you go along so no-one ever ends up in the same position as you have.

A: you need to use clues. get a clue of what you have to look for and extensively use the search functionality of your environment or IDE that can bring you to the desired section of the code that you need to make change to.
reading 14 thousand lines of java code does not make any sense. Search functionality is your life saver

A: Different people have different learning styles, so YMMV. The first thing I do in this situation is read the entire code base through at least once. That gives me a general idea of where everything is. Then I choose a section to examine in more detail. Data structures would be a good place to start. Once I have a general idea of what's going on, I do the same with another portion of the code that interacts with the first. After enough iterations, I have a good sense of how the code works.

A: The best way, as with all programming not just large chunks of uncommented code, is to break it down into pieces. This is both something you should do in your head as well as visually in the code. This may mean adding big bold comments or multiple line breaks. This helps while scrolling through it to see the pieces. Try to find the logical chunks of code.
Of course, as you understand bits, comment them for what you know at that time, possibly putting in notes about about something you don't understand.
I would also recommend not trying to understand the entire piece right from the start. Instead try to understand the pieces that you need to know right now and work on the rest later.

A: I would start by using the Leo Editor in @shadow mode with active use of cloned nodes. This allows one to add notes and comments for each section of code under study without changing the code, and the annotations will always be in context, next to the code it's talking about. Here's an example workflow the docs:

For example, when I fix a bug in Leo,
  I create an ordinary node to represent
  the bug. This bug node is my view of
  all the data in Leo's source code that
  relates to the bug. As I discover code
  related to the bug, I clone their
  nodes and move them under the bug
  node. I'll also add ordinary nodes as
  children of the bug node. These nodes
  contain the original bug report,
  descriptions of how I fixed the bug,
  test data, or any other notes I might
  want to keep.
Once I have created the bug node, I
  concentrate only on that node and its
  children. I can examine the bug node
  and its children without having to
  jump around the outline. Everything I
  need is in one place. When I get
  around to actually fixing the bug I
  can do so by changing the clones.
  Again, I do not have to jump around
  the outline. It doesn't matter how big
  or complex the entire outline is: I am
  only dealing with the bug node and its
  children. This extremely narrow focus
  makes it much easier to fix bugs.

A: Draw diagrams of the source: the data relationships, the functional relationships, the object relationships.  Determine aggregation, data flow, and code flow.  Pictures are far better than comments for this, and can be kept separate from the code.

A: Before you refactor anything write tests. Lots of tests. Very specific tests to small blocks of code that are at least callable, as it'll depend on how your inherited mess is written.
The advantage to writing tests to begin with is that you need to have some kind of understanding of the code before you can test it, so every test you write will hopefully be a little bit of knowledge gained. You can also heavily comment the tests with your assumptions alongside the assertions.
By doing it test first, you don't run the risk of altering something in the code that has knock-on effects you can't know about. You'll also have a safety net when you do come to refactor the code.

A: I use tools like doxygen, to generate an overall class diagram, than adds my understanding of what each of the classes do.
Then I pick up some easy bug from the bug queue (before my manager assign a hard one to me :P), then run through that functionality into debugger and try to generate a rough data flow or code flow model.
For example export functionality in some software: so I try to understand how the source data is read, from where in the code (base interface) can I evaluate the data is read correctly using my class and code flow diagrams, which classes are responsible for which type of exports, etc. I think half of the understanding is done, once you have the class diagrams and flow charts.

A: Approach a trivial defect, e.g., a NullPointerException.  Avoid anything regarding concurrency at first, anything that by its nature will involve understanding a lot of the code at once.
Once you've fixed a few bugs you'll probably have a pretty good idea.  Works for me, at any rate.

A: Basically the action to  write a clean code should start right from design.
If we are coding in OOP language come up with a UML ,share with peers and get convinced that design is not ambigous . In any case we developers should get convinced that design solves the problem and not ambiguos.
When it comes to coding we have to make sure the design is getting converted to code i.e. an Entity to a class or struct , an operation to function etc.
And i went through a white paper http://queue.acm.org/detail.cfm?id=2063168  which talks about coding style or how we can use space, indentation , Font variation as most IDEs do we can use to write MUCH CLEANER code where we humans can understand as much as machines do. It stresses more on writing comment free code so that our code will appear as paragraphs itself.


text:
Q: Hibernate - How to persist only the parent, keeping the children as they are Can someone please help me understand how to configure hibernate to do what i want.
I have a parent entity "Appartment" with a List of "Room"s as children.
I have a form to edit "Appartment"s and within that form i have listed all of the children "Room"s just for informative purposes. Rooms are added and edited in a separate form.
So because i am listing the rooms in the appartment-form i have set lazyloading to false:
    @OneToMany
@JoinColumn (name = "appartmentId")
@LazyCollection (LazyCollectionOption.FALSE)
private List<Room> room;

But if I edit an appartment and store it, all the appartments rooms suddenly dissappear. In the database they are not deleted, but dereferenced (as in appartmentId = null).
So how can I configure hibernate to only persist my Appartment-object. And not touch the children at all?
This is my save-action:
public String save() throws Exception {
    boolean isNew = (appartment.getAppartmentId() == null);

    appartment = appartmentManager.save(appartment);

    String key = (isNew) ? "appartment.added" : "appartment.updated";
    saveMessage(getText(key));

    return SUCCESS;
}

A: This is really simple. No need to repopulate your children, or create separate DTO's.
If you are never going to persist the children just add insertable=false, updatable=false to your joincolumn annotation. Like this:
@OneToMany
@JoinColumn (name = "appartmentId", insertable = false, updatable = false)
@Fetch(value = FetchMode.JOIN)
private List<Room> room;

A: *

*Don't disable lazy fetching in a mapping. Use fetching strategies for performance tuning.

*Hibernate will only remove the Rooms from an Apartment if you tell it to save/update an Apartment that has no Rooms in it.

A: Instead of using persistent entities, consider using DTOs (you can call them a page model in the case of web pages). They can give you a flexibility to depict information you want and show it in the format you want. But you should pay for this - you're adding new classes to your system and you have to come up with a way to transform entities to DTOs and backward.


text:
Q: How to import normalize, schema function from normalizr node package outside of React in a plain javascript file or simple node project I must be missing some very basic here about importing an external package function to my plain javascript project / file.
I have a simple project that I have started with npm init And then installed the normalizr package. I have to run the below kind of normalization code, and this is perfectly working when I run the below code inside a React Component.
But the import statement itself is failing in my simple plain JavaScript file/project.
const normalize = "./node_modules/normalizr/dist/normalizr.js";
const schema = "./node_modules/normalizr/dist/normalizr.js";

const articlesData = {
    articles: [
        {
            id: 1,
            title: "Dagon",
            tags: [{ id: 1, name: "old ones" }, { id: 2, name: "short story" }]
        },
        {
            id: 2,
            title: "Azathoth",
            tags: [{ id: 1, name: "old ones" }, { id: 3, name: "novel" }]
        },
        {
            id: 3,
            title: "At the Mountains of Madness",
            tags: [{ id: 4, name: "insanity" }, { id: 3, name: "novel" }]
        }
    ]
};

const tag = new schema.Entity("tags", {});
const article = new schema.Entity("articles", {
    tags: [tag]
});

// We assume articlesData is the (parsed) JSON object that we got
const normalizedData = normalize(articlesData, { articles: [article] });

console.log(articlesData);

I have also tried to import the 2 functions (normalize, schema) as below which did not work
 const normalize = require("normalizr");
 const schema = require("normalizr");

And also tried the below way to run the file, which also failed
node --experimental-modules ./file.js

Had gone through this official page but which was not much help for me.
The below is my package.json file
{
  "name": "test-js-codes-repo",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "babel": {
    "presets": [
      "@babel/preset-env"
    ]
  },
  "license": "ISC",
  "dependencies": {
    "@babel/cli": "^7.8.4",
    "@babel/node": "^7.8.7",
    "@babel/preset-env": "^7.8.7",
    "axios": "^0.19.2",
    "babel-core": "^6.26.3",
    "babel-eslint": "^10.1.0",
    "babel-loader": "^8.0.6",
    "babel-plugin-dynamic-import-webpack": "^1.1.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-register": "^6.26.0",
    "es6-promise": "^4.2.5",
    "esm": "^3.2.25",
    "https": "^1.0.0",
    "isomorphic-fetch": "^2.2.1",
    "lodash.flatten": "^4.4.0",
    "lodash.map": "^4.6.0",
    "lodash.omit": "^4.5.0",
    "lodash.orderby": "^4.6.0",
    "lodash.partialright": "^4.2.1",
    "lodash.pick": "^4.4.0",
    "lodash.sortby": "^4.7.0",
    "moment": "^2.22.2",
    "normalizr": "^3.6.0",
    "request": "^2.88.0"
  },
  "description": "",
  "devDependencies": {
    "babel-plugin-dynamic-import-node": "^2.3.0"
  }
}

A: Import it like you would any other module import in Node.js require docs
const { normalize, schema } = require('normalizr')


text:
Q: Linkage is equivalence relation Let $(R,m)$ be a Cohen-Macaulay local ring, I and J are ideals of height $r.$ Then we say $I$ is directly linked to $J$, i.e. $I \sim J$ if there exists an ideal K generated by a regular sequence $x_1,\ldots,x_r$ such that $K\subset I\cap J,$ $I=K:J$ and $J=K:I.$
We say $I$ is linked to $J$ if there exist ideals $I_1,\ldots,I_s$ of height $r$ and generated by regular sequences such that $I\sim I_1, I_1\sim I_2,\ldots, I_s\sim J.$
Question: Is the operation "$I$ is linked to $J$"  an equivalence relation? Particularly I do not understand how it is reflexive?
enter link description here
[Linkage and the Koszul Homology of Ideals - C. Huneke]

A: If $I$ is an ideal with $R/I$ CM, pick a regular sequence $x_1,\ldots, x_r\in I$, where $r$ is the height of $I$. If we call $K$ the ideal generated by the $x_i$s, we can define $J=(K:I)$. One checks that $I=K:J$ and then we are done once we also check that $R/J$ is also CM.


text: Q: Unable to access some websites(Google) in android simulator behind proxy? I am unable to access to certain websites like www.google.com in android emulator. We are in a secured corporate  network and use proxy to connect to the internet. I tried by adding the http-proxy in the startup command, still the same problem. I am able to access certain sites like msn.com, and favicon is loading for almost all the sites, but still the browser says "The web page at  might be temporarily down". Please throw some light on this?


text:
Q: Counting sublists inside a list in Python I have a list like p = [[[[[[[[1, 2, 3]]]]]]]], I want to get the count of the items in the list including  empty lists, so for this list I should get 10. I am trying to enumerate the list like -
for idx, item in enumerate(p):
    count = count + idx

but I am not able to get the empty lists there. Please advice.

A: Shorter version of code below:
>>> def recur_len(l):
        return sum(1 + recur_len(item) if isinstance(item,list) else 1 for item in l)

>>> recur_len([[[[[[[[1, 2, 3]]]]]]]])
10

More detailed code
>>> def recur_len(l):
        count = 0
        for item in l:
            if isinstance(item,list):
                count += 1 + recur_len(item)
            else:
                count += 1
        return count

>>> recur_len([[[[[[[[1, 2, 3]]]]]]]])
10

A: If you only want to count lists (or subclasses of list) and nothing else, except the content of the final list not just containing another list:
def len_counting_containers(inlist):
    count = 0
    current = inlist
    while len(current) == 1 and isinstance(current[0], list):
        count += 1
        current = current[0]
    return count + len(current)

len_counting_containers([[[[[[[[1, 2, 3]]]]]]]])

Which gives us:
10

Note that this is a pretty fragile operation (as with any case you use isinstance() in python) - so you want to be sure that your incoming data is always structured as you expect. If your data is coming from a source you control, I would recommend looking at how you produce the data and seeing if you can give it in a nicer form - e.g: (7, [1,2,3]).
You could also implement this recursively:
def len_counting_containers(current):
    return len_counting_containers(current[0])+1 if len(current) == 1 and isinstance(current[0], list) else len(current)

len_counting_containers([[[[[[[[1, 2, 3]]]]]]]])

This gives the same result in less code, but if you are working with an insanely large lists this could hit recursion limits.

A: def depth(a):
    return 1 + depth(a[0]) if type(a) is list else 0

Demo:
a = 'x'
for n in range(10):
    a = [a]
    print a, depth(a)

## ['x'] 1
## [['x']] 2
## [[['x']]] 3
## [[[['x']]]] 4
## [[[[['x']]]]] 5
## [[[[[['x']]]]]] 6
## [[[[[[['x']]]]]]] 7
## [[[[[[[['x']]]]]]]] 8
## [[[[[[[[['x']]]]]]]]] 9
## [[[[[[[[[['x']]]]]]]]]] 10


text:
Q: Preferred way of data upgrade considering abstraction of data storage format The core question is how to properly execute upgrade of data while applications versions differ in matter of data representation? E.g. for databases it is often to use SQL scripts to modify persisted data model. I can easily imagine similar way using XSL for XML and so on. But I would like to create abstraction of data persistence model in that way that upgrade method does not consider way of storing data - it is suffice that it can read previous version data and save new ones.
I tried doing such thing in C# like loading previous version of assembly containing data definition classes through reflection while having current version deployed with application. It is quite complex and tricky solution. Other option is to keep previous model classes redundantly with some version based naming convension - this solution is easier as it gives full access to types at compile time.
My idea asking this question is, what is the proper solution of such upgrades of data?


text:
Q: Jabber Psi+ message history There's openfire-4.0.2 IM sender connected to Samba AD server. As a jabber client Psi+ v0.16.330 is used.
When User1 sends message to User2 this outgoing message doesn't written to User's1 message history. But User2 in his history has message from User1. In other words, all histories of all users contains only incoming messages, not the full "dialog".
In "Account" settings in Psi+ checkbox "Keep history" is on. "History Keeper" plugin is turned off.
What's wrong?

A: Well, don't know, whether this is a bug or feature, but such mess with chat/message history is done by Psi+ client.


text:
Q: Creating Neural Network for un-encountered inputs I am creating a simple Multi-layered feed forward Neural Network using AForge.net NN library. My NN is a 3 Layered Activation Network trained with Supervised Learning approach using BackPropogation Learning algorithm.
Following are my initial settings:
//learning rate
learningRate=0.1;

//momentum value
momentum=0;

//alpha value for bipolar sigmoid activation function
sigmoidAlphaValue=2.0;

//number of inputs to network
inputSize=5;

//number of outputs from network
predictionSize=1;

//iterations
iterations=10000;

// create multi-layer neural network
            ActivationNetwork network = new ActivationNetwork(new BipolarSigmoidFunction

(sigmoidAlphaValue), 5, 5 + 1, 3, 1);

//5 inputs
//6 neurons in input layer
//3 neurons in hidden layer
//1 neuron in output layer

// create teacher
BackPropagationLearning teacher = new BackPropagationLearning(network);

// set learning rate and momentum
teacher.LearningRate = learningRate;
teacher.Momentum = momentum;

Now I have some input series which looks like this,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
Using window sliding method (as described here) for input as a time series, my input and
expected output array looks something like this
//Iteration #1
double input[][] = new input[0][5] {1,2,3,4,5};
double output[][] = new output[0][0] {6};

//Iteration #2
double input[][] = new input[1][5] {2,3,4,5,6};
double output[][] = new output[1][0] {7};

//Iteration #3
double input[][] = new input[2][5] {3,4,5,6,7};
double output[][] = new output[2][0] {8};
.
.
.
//Iteration #n
double input[][] = new input[n][5] {15,16,17,18,19};
double output[][] = new output[n][0] {20};

After 10k iterations as such using
teacher.RunEpoch(input, output);

my network is successfully trained for the given training set. So now, if I compute using inputs as 4,5,6,7,8 the network successfully gives 9 as answer fantastic!
However, when the input is provided as 21,22,23,24,25 the NN fails to produce 26!
My Question:
How do I train my network to accept such unencountered inputs of such fashion to produce a correct sequence pattern as found in training set during learning?

A: As @runDOSrun said, your model seems to be overfitting the (training) data. To avoid this problem you could split your set (time series) in 3 parts.
Training Set
The first one could be the training set where you just train your network.
Validation Set
The second one is the validation set, where for each epoch of training, you test the neural network on the validation set and take the error and store this error in a variable and a copy of the neural network (clone). On the next epoch, you have to test the (modified) neural network and if the new error on the validation set is lower than the last you have tested, you store a new "validation neural network". It will provide for you a neural network which generalize better in a set which is not the training set. So you avoid to overfit the training set.
At the end of training you have two neural networks. The training neural network which is the best neural network for training set and the validation neural network, which can provide for you a neural network which generalize better out of training set.
Test Set
This last part, you just test your model in a unseen set and check the errors. The propose for test set is to check the behaviour of the neural network in the unseen test. A real test.
In general, you could slipt the all entire set in 3 equals parts, or for sample

*

*60% for training

*20% for validation

*20% for test

For sample, look the image bellow:

A sample of pseudo-code of how implement it could be:
int epochs = 1;
double error = 0;
double validationError = 10000;
object validationNetwork;
do
{
    // train your network

    error = getError(trainingSet);

    //validation part...

    var currentValidationError = getError(validationSet);
    if (currentValidationError < validationError)
    {
       validationError = currentValidationError;
       validationNeuralNetwork = neuralNetwork.Clone();
    }

} while (epochs < 2000 && error < 0.001);

Cross-Validation for Time Series
On the other hand, you also could try to do the cross-valdidation for time series. First you split your set in 6 parts (or more) and train neural networks to validate the model like this:

*

*1 : training [1], validate [2], test [3]

*2 : training [2], validate [3], test [4]

*3 : training [3], validate [4], test [5]

*4 : training [4], validate [5], test [6]

You could split in more parts if you want.


text:
Q: RegEx for comma seperated list I want to validate a list of values seperated by commas, without a comma after the last value:
Shoud be valid:

altdns1.at, altdns2.de.fr, altdns3.de

Should be invalid:

altdns1.at, altdns2.de.fr, altdns3.de,

My RegEx:
^([^,]+,)*([^,]*)$

My thoughts:

*

*([^,]+,)   beginning of string: any character except comma - one to unlimited times - followed by a comma

** all this zero to unlimited times

*([^,]*)  end of string: any character except comma - one to unlimited times

Regex101 shows this string matches my pattern:

altdns1.de.de,altdns2.de.de,altdns3.de.de,

Why?

A: Use this:
^[^,]+(?:,[^,]+)*$

Explanation:
^           : begining of line
  [^,]+     : 1 or more not comma
  (?:       : start non capturing group
    ,       : a comma
    [^,]+   :  1 or more not comma
  )*        : end group, may appear 0 or more times
$           : end of line


text:
Q: Install SQL Server 2012 to Windows Server 2008 I'm trying to install SQL Server 2012 in Windows Server 2008 R2 Standard Operating System. However this Error keep appearing even though I installed both .NET Framework 3.5.1 and 4.0

The operating system on this computer does not meet the minimum requirements for SQL SERVER 2012. For Windows Vista or Windows Server 2008 Operating System. Service Pack 2 or later is required. For windows 7 or Windows Server 2008 R2, Service Pack 1 or later is required. For more information, see hardware and Software Requirements for installing SQL Server 2012 at

A:
However this Error keep appearing even though I installed both .NET Framework
  3.5.1 and 4.0

And why do you think that the .NET framework version would fix that when the error CLEARLY says:

For windows 7 or Windows Server 2008 R2, Service Pack 1 or later is required.

THe solution is simple. IGNORE the error - it really is more a warning. And then once you installed SQL Server 2012, immediately patch it.


text:
Q: Mysql объединить две выборки в одну Первый запрос у меня сортируется по моему списку
select * from posts where id IN (1, 2, 3) order by field(id, 2, 3, 1);

Вторая запрос так
select * from posts order by `ctr` desc limit 7

мне надо объединить результаты в одну выборку, в сортировке как в первом запросе + второй запрос

A: SELECT *
FROM ( select *, 0 as num from posts where id IN (1, 2, 3) order by field(id, 2, 3, 1);
       UNION ALL
       select *, 1        from posts order by `ctr` desc limit 7
     ) tmp
ORDER BY num, CASE WHEN num THEN `ctr`
                            ELSE -field(id, 2, 3, 1) DESC
              END;


text:
Q: NVDA ignoring aria-hidden="true" in IE 11 and 10 Putting a  with an aria-hidden="true", NVDA will still read "Your browser does not support the video tag." while the video is loading.  Once the video is loaded, it will play.  For some reason when using IE, NVDA will not ignore that text.  It does not read it when using Chrome nor does VoiceOver read it. Has anybody run across this and no how to fix it?
here is the code:
<video id="view-video" controls>
    <source src="#" type="#">
    Your browser does not support the video    tag.
 </video>

A: It would help if you provide more details of specific versions of IE and NVDA and whether you are using a keyboard or mouse. I am assuming mouse interaction because that's usually the culprit one in IE.
With that assumption, I don't think it's something you can really fix with just HTML or CSS https://github.com/nvaccess/nvda/issues/5320. NVDA in IE in mouse mode ends up reading a fair amount of unnecessary items. I assume this is what it relates to.
You can try display none, role=presentation, aria-hidden, position off screen, etc. and it will still seem to read it (whether it is inside or outside of the video tag).
So then it comes to why you are wanting this to be hidden. I figure this is not your real code, since you do have sources and they do load. So if the text is there just for older browsers, I would suggest not having the span at all initially. You might want to use modernizr, or do checks to see if the video tag is supported and then if it isn't add in the span. Or if you just want to account for older versions of IE you could put the content within conditional tags.
Unfortunately there doesn't look to be an easy answer from everything that I've found.

A: Sorry, found the issue was a problem between IE 11 and Edge and NVDA 2016. The bug has been reported.


text:
Q: print_r() PHP function in C# So I'm trying to write a C# function print_r() that prints out information about a value passed much in the same way that the PHP print_r() function works.
What I'm doing is taking in an object as an input in to the function, and depending on what type it is, I'll output the value, or loop through an array and print out the values inside the array. I have no problem printing out basic values, but when I try to loop through the object if I detect it is an array, I get an error from C# saying "Error  1   foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'".
Now I'm assuming this is just because object doesn't implement IEnumerable<>, but is there any way that I can process this taking in the input as type object?
This is my current code for the function (the IEnumerable<> part is blank in terms of content, but this is the code that is giving me an error.
Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void print_r(object val)
        {
            if (val.GetType() == typeof(string))
            {
                Console.Write(val);
                return;
            }
            else if (val.GetType().GetInterface(typeof(IEnumerable).FullName) != null)
            {
                foreach (object i in val)
                {
                    // Process val as array
                }
            }
            else
            {
                Console.Write(val);
                return;
            }
        }

        static void Main(string[] args)
        {
            int[] x = { 1, 4, 5, 6, 7, 8 };
            print_r(x);
            Console.Read();
        }
    }
}

A: val is declared as an Object. After checking if it's an IEnumerable (which you can do simply with is, as shown, but this works also with your original code) you have to cast it explicitly
else if (val is IEnumerable)
{
    var e = val as IEnumerable;
    foreach (var i in e)
    {
        Console.WriteLine(i.ToString());
    }
}

A: There is LINQPad that has Dump() extension method, but you can use it only in LINQPad
We can write our own extension method to dump any object to html and view it in browser.
You need to reference LINQPad.exe
public static class Extension
    {
        public static void Dump<T>(this T o)
        {
            string localUrl = Path.GetTempFileName() + ".html";
            using (var writer = LINQPad.Util.CreateXhtmlWriter(true))
            {
                writer.Write(o);
                File.WriteAllText(localUrl, writer.ToString());
            }
            Process.Start(localUrl);
        }
    }

A: You would have to use reflection to do this I think, I want a similiar function and ouputted my objects into tables using reflection.
I dont have the code to hand but found the basis of my solution here!


text:
Q: PHP print variable from input I have following code and it doesn't works for me.
I need print variable from input.

    <form action='#' method="post">
        <input type="text" name="name">
        <input type="submit" name="submit">
    </form>

      <?php
         $name = name
         echo $name;
      ?>
   </form>

Thanks.

A: you have to use POST to get text from input.
This is right code:

<form action='#' method="post">
<input type="text" name="name">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit']))
{
$name = $_POST['name'];
echo $name;
}
?>
</form>


text:
Q: Printing class member So I'm making multiplayer minesweeper. I am at the end where I want to print score of each player. For player I have a class like this:
public class Player
{
    public string name;
    public int score;
}

For each client that connects I run a new thread:
clientThreads[i] = new Thread(new ParameterizedThreadStart(HandleClient));

And then at the end of HandleClient method I have this:
foreach(Player p in players)
{
    this.BeginInvoke((Action)(() =>
    {
        label8.Text += p.name + ":" + p.score.ToString();
    }));
}

I also tried with MessageBox if that changes anything, but problem is that I do get name of a player, like it does print out but score doesn't get printed, even ":" is not printed. I placed a breakpoint and p.score does have a value so its not like its null or something. And I don't get any error neither there is any error shown while editing. What is maybe strange is that even if I remove ToString() there is still no error even tho I am adding text to label.text where it should all be string. I never faced problem like that and I don't know why its happening.
I also added picture from breakpoint. Read "tocke" as score.

EDIT: Solved! Problem was that name had too many of "\0"

A: \0 is a "null character" -- a type of a string terminator in C#.
Your names have lots of them trailing, so the rest of the line simply doesn't fit in.
You can use something like name.Trim() to get rid of them in the label.


text:
Q: MVC - Change background colour of divs using database rgb value I've got a table that displays the colour of my items using this expression.
 @Html.DisplayFor(l => item.Colour)

That shows the word for the colour that I've assigned (you can see that in the attached image).
How the colour shows I've also got a 'ColourRGB' value for all my items and I want to make this the background colour for each  tag. Can anyone help me? Thanks

A: @Html.DisplayFor(l => item.Colour)

A: In css, one can define a particular color such as
table th {
    padding: 6px 5px;
    text-align: left;
    background-color: #e8eef4;
    border: solid 1px #e8eef4;
}

The in the .cshtml file:


text:
Q: Difference between static function and non static function in C I'm developing an embedded application on VxWorks.
I know that the static function is called only in the file where defined and the non static function is called in any file in the source project.
I'm wondering if there is a difference between static and non static function concening execution time and concerning memory

A: It depends on your compiler.  Static functions can theoretically be optimized better because the compiler will know all the places where they are being called.  You should be able to get an assembly listing from your compiler and find out for yourself if they are more efficient.

A: There is no difference in execution times or runtime memory requirements.
Some (many?) linkers will find it easier to spot unused static functions and drop them so they  might encourage smaller code size.

A: There is absolutely no performance difference. The the only thing the static keyword does on functions is given them internal linkage, which means they are only accessible in the file they are defined in.


text:
Q: Is there a prime number less than the product of consecutive primes, but greater than the last consecutive prime? Let $P(k)$ be the product of $k$ consecutive primes $p_1, p_2, \dots, p_k$. So, e.g. $P(4)$ is $2 \cdot 3 \cdot 5 \cdot 7 = 210$.
Is anything known about whether $P(k) > p_{k+1}$ is always true (for $k > 1$)? It seems like it should be true, since $P(k)$ gets large quickly (faster than $k!$), but I'm having trouble seeing how to construct a counterexample.
If there were a counterexample, then it seems like this would violate PNT locally if it were true since the primes would have to be very sparse in that region. But that's not definitive. Is there an elementary proof one way or another?

A: By Bertrand's Postulate, which has been a theorem for a long time, there is always a prime between $n$ and $2n$.

A: Look at the integer $n=P(k)-1=p_1p_2\dots p_k - 1$.
Here $n>p_k$, as long as we look for cases for $k>1$.
If $n$ is prime, then certainly $p_k<p_{k+1}\leq n$.
Then we are done since $P(k)=n+1\implies P(k)>n\geq p_{k+1}\implies P(k)>p_{k+1}$.
Hence suppose $n$ is a composite.
Let $r$ be any divisor of $n$, then $n\equiv 0(\text{mod }r)$.
Since $n\equiv-1\not\equiv 0(\text{mod }p_i)$, we conclude that $r\not\in\lbrace p_1,\dots,p_k\rbrace$.
Edit: As $p_k$ are consecutive primes, this means
$$p_{k+1} \leq r$$
We then derive
$$p_{k+1} \leq r <n <n+1=P(k) $$
Therefore $P(k)>p_{k+1}$.
i.e. the statement is always true.

 i.e. there is a prime $p_k<r<n$.
Since $n$ is finite, we may find a minimal $r$.
This $r$ must be $p_{k+1}$, which certainly satisfies $p_{k+1}<n<P(k)$.
Therefore we reach the conclusion that $P(k)>p_{k+1}$.
i.e. the statement is always true.


text:
Q: Groovy - Regex match the string with last char numbers My input string
pdfe_bc
pdfe_orSE
pdfe_oo1
pdfe_och1
pdfe_oo2
pdfe_och2
pdfe_oo10
pdfe_och10 and so...

I want to collect the below-formatted string and stored in a separate ArrayList.
pdfe_oo1
pdfe_oo2
pdfe_oo10

I'm using below regex to find and match the string
Pattern p = Pattern.compile("[pdfe_oo]\\d+")

and my complete code is
for ( WebElement e : allIDs ) {
    String iD = e.getAttribute("id")
    println iD
    Matcher m = p.matcher(iD)
    if(m.matches){
        formID.add(iD)
    }
}

But it's getting below exception
groovy.lang.MissingPropertyException: No such property: matches for class: java.util.regex.Matcher

import
import java.util.regex.Matcher
import java.util.regex.Pattern

A: You may use Groovy directly to test the whole string against a regex using ==~ operator (it requires a full string match as String#matches() in Java does) and make sure you remove square brackets from the regex (as [abc] matches a single char, either a, b or c and not an abc substring):
if (iD ==~ /pdfe_oo\d+/) {
    formID.add(iD)
}

Note the use of slashy string (/pdfe_oo\d+/) that allows using a single backslash to define regex escapes.


text:
Q: Cannot stop debug mode/traceback window in package function in R I was debugging a helper function I myself wrote, by clicking "Rerun with Debug". RStudio then opened up debug mode on the function stats::model.frame.default. Since then whenever I re-run the helper function, RStudio triggers read-only debug/traceback mode on the stats::model.frame.default function.
I tried undebug(model.frame.default) to "turn off" the read-only debug/traceback mode on the function but it doesn't work, the debug/traceback window keeps popping up.
Edit: I have toggled options(error = traceback) but it stops triggering traceback altogether, which is not ideal and overdone. I am looking for a solution that ends the traceback mode in that particular ``stats::model.frame.default``` function.


text:
Q: "Will have heard by now" sounds like bad usage to me; what is your opinion? I posted the question here
https://ell.stackexchange.com/questions/295727/bad-usage-of-will-have
but it was closed due to insufficient details or clarity. I'm trying here.

The following sounds wrong to me; what do you think:

*

*"As you will have heard, Aotearoa New Zealand will remain at alert level 4 until at least 11.59 pm on Friday 27 August."

*"As you will have no doubt heard, there are two more confirmed cases of COVID-19 in Wellington today, bringing the total number in the region to eight."
Why I think it's wrong. 'Will have' should be used to reference a point in the future:
https://dictionary.cambridge.org/grammar/british-grammar/future-perfect-simple-i-will-have-worked-eight-hours
That's not the case in both sentences. Their meaning is:

*

*As you probably have heard by now, ...

*As you must have heard, ...

I got an opinion:

both of them are fine, grammatically.
"as you will have heard"  - referring to the past from the point in
the future when the reader is reading (which is in the future relative
to the time of writing).
"As you will have no doubt heard,"   is the same, with the extra
assertion that the writer has no doubt that the reader will have
heard.

I don't agree with it. It's not snail mail: by the time you get this letter, you will have heard... It's email: you get it immediately, and I'm assuming you are reading it now, and I'm expressing myself as if I'm speaking to you in person.

A: "Will" can refer to the future but it can also refer to what is likely
will modal verb (LIKELY)
(also 'll)
used to refer to what is likely:
That'll be Scott at the door.
That'll be his mother with him.
As you all will know, election day is next week.
https://dictionary.cambridge.org/dictionary/english/will
So the quotations are correct and mean that it is likely that the addressee will have heard.


text:
Q: Writing to a file from a TextBox Lua Lately Ive been trying to make a basic word added. I want to make it so you tap on the text field and then you type what you need then it writes it to a .txt file (precreated or not) Im not great with coding and Im struggling to use the samples/other peoples Stack Exchange question to learn off. All I have is bits of code that dont work together and im not sure what I need to do to make them work (the code isnt mine)
local textBox = native.newTextBox( 200, 200, 280, 140 )
textBox.text = "This is line 1.\nAnd this is line2"
textBox.isEditable = true

local file = io.open( filePath, "r" )
if file then
-- read all contents of file into a string
local contents = file:read( "*a" )

print( "Contents of " .. filePath )
print( contents )

io.close( file ) -- Important to close (python knowledge)

local t = display.newText( "Contents of ", 5, 80, nil, 16 ); -- w, h, ?, size
t:setFillColor( 1, 1, 135/255 ); -- edit
local t = display.newText( filePath, 5, 100, nil, 10 );
t:setFillColor( 1, 1, 135/255 );

local ylast = 130 -- how far down the Y value it can make words on the screen
for line in io.lines(filePath) do
    local t = display.newText ( line, 15, ylast, nil, 14); -- dont understand
    t:setFillColor( 1, 1, 1 );
    ylast = ylast + 20
    end
end

local function inputListener( event )
if event.phase == "began" then

    -- user begins editing textBox
    print( event.text )

elseif event.phase == "ended" then
    textBox.text = event.text
    local path = system.pathForFile( "myfile.txt", system.DocumentsDirectory )

    local file = io.open( path, "w" )
    file:write( textBox.text )
    io.close( file )
    file = nil

elseif event.phase == "editing" then

    print( event.newCharacters )
    print( event.oldText )
    print( event.startPosition )
    print( event.text )

end
end

textBox:addEventListener( "userInput", inputListener )

A: I suggest using the loadsave functions it makes it easier.
You can download these functions from here.
https://github.com/robmiracle/Simple-Table-Load-Save-Functions-for-Corona-SDK
Once downloaded just drop the loadsave.lua file into your main project folder.
Now you can use it like this.
Example:
local loadsave = require("loadsave")

local tableToSave = {}

-- load text into a table
tableToSave ['saved-text'] = textYouWantToSave

-- save text
loadsave.saveTable(tableToSave, "filename.json")

local savedTable = {}

-- load text
savedTable = loadsave.loadTable("filename.json")

-- text is stored here
savedTable['saved-text']


text:
Q: THREE.js Move camera on orbit with mouse I am trying to orbit a camera on an inclined orbit around a scene while the camera always points to the scene's origin. (Think of the camera rig installation for filming the bullet dodging scene in the first Matrix movie.)
The idea is to let the x-component of the mouse position on screen determine the position of the camera on the orbit. Hence, I created a dummy object whose position  is changed in the mousemove-listener. The camera is attached to the dummy object, and the dummy object is attached to a pivot which creates the orbit inclination.
var pivot = new THREE.Object3D();
var cameraPos = new THREE.Object3D();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
cameraPos.add(camera);
pivot.rotation.y = Math.PI/4;
pivot.add(cameraPos)

I've put a minimal example together here: codepen.
The result is this erratic camera movement. Any idea WHY that happens?

I cannot figure out what I am doing wrong.
A solution
I will add that I know already how to fix it.

*

*Step 1: Detach the camera from the dummy object cameraPos

*Step 2: Set the camera position manually to the position cameraPos.

var target = new THREE.Vector3();
cameraPos.getWorldPosition(target)
camera.position.copy(target);

Outro
I really like the idea of attaching the camera to an object which follows then a prescribed path. But does attaching the camera to an object create unwanted interaction? What is the explanation for this behavior?


text:
Q: Figure appears in bibliography i used all possible options for the figure placement [h], [!h], [ht], [htb]
and the figure always appears in the middle of the bibliography, since the figure is near the end of the paper.
is there an option to "flush" everything before the bibliography?
So it would even look something like
[NEW PAGE]
bla bla bla
[some vertical space]
[NEW PAGE]
[figure]
bibliography
because now it looks like:
[NEW PAGE]
bla bla bla
bibliograhy
[NEW PAGE]
[figure]
bibliography (continuing)

A: The simplest way to flush floats is \clearpage which outputs all floats (potentially on new pages) and afterwards starts a new page.
If a new page is not desired then the use of the package placeins will help. It offers a command \FloatBarrier that forces floats to be placed before further text will be typeset. It offers some finer control through package options.
Also something like [!t]might help (which was not listed in your placement options you tried), as it turns off some of the restrictions for placing the current float on the top of the page.


text:
Q: extract text from tex, remove latex tags I have some .tex files from which I want to receive the plain text without any latex tags such as \section{...} or \newpage.
Does anybody have any idea on how to achieve this?
I also have the .pdf file but when I just copy the code from there, some words get concatenated which is real bad.
Is there any tool you know?

A: opendetex   is available both for windows and Linux
download the program opendetex from here
http://opendetex.googlecode.com/files/opendetex-2.8.1.tar.bz2
http://code.google.com/p/opendetex/downloads/list
Usage:
http://code.google.com/p/opendetex/wiki/Usage
extract it to any directory of your choice.
Say u extract it to Downloads directory.
make another directory of any name in that (optional. but its good if u create). say the directory name is "my_paper". Put your paper in the "my_paper" directory. say your paper name is project.tex
Navigate through the path
cd ~/Downloads/opendetex

Run the command
detex -n my_paper/project.tex  > out.txt

generic form
detex -n full_path_to_tex_file.tex > output_text_file.txt

A: detex(1):

Please see the OpenDetex GitHub page for the latest version of OpenDetex. It is a more modern, derivative version of my original DeTeX.
My legacy DeTeX home page is available here.
If you just want the legacy detex-2.8.tar source, you can get it here.

A: Maybe not 100% what the OP requested, but maybe it is of some help.
There is pdftotext in poppler-utils. This can convert a PDF file to a TXT file via
pdftotext yourPDF.pdf

Of course this incurs the overhead of installing this package, but I think it's neglible, since it is the standard library to render PDF on Linux if I remember correctly, so if you have a PDF viewer installed (Think Evince or Okular), it will be installed already.
Find here some more instructions.


text:
Q: How to speed up the matching of columns in pandas dataframe I'm trying to find matching values in a pandas dataframe. Once a match is found I want to perform some operations on the row of the dataframe.
Currently I'm using this Code:
import pandas as pd

d = {'child_id': [1, 2,5,4], 'parent_id': [3, 4,2,3], 'content':     ["a","b","c","d"]}

df = pd.DataFrame(data=d)

for i in range(len(df)):

        for j in range(len(df)):

            if str(df['child_id'][j]) == str(df['parent_id'][i]):
                print(df.content[i])
            else:
                pass

It works fine, but is rather slow. Since I'm dealing with a dataset with millions of rows, I would take months. Is there a faster way to do this?
Edit: To clarify what, I want to create is a dataframe, which contains the Content of Matches.
import pandas as pd

d = {'child_id': [1,2,5,4],
 'parent_id': [3,4,2,3],
 'content': ["a","b","c","d"]}

df = pd.DataFrame(data=d)

df2 = pd.DataFrame(columns = ("content_child", "content_parent"))

for i in range(len(df)):

    for j in range(len(df)):

        if str(df['child_id'][j]) == str(df['parent_id'][i]):
            content_child = str(df["content"][i])

            content_parent = str(df["content"][j])

            s = pd.Series([content_child, content_parent], index=['content_child', 'content_parent'])
            df2 = df2.append(s, ignore_index=True)
        else:
            pass

 print(df2)

A: The fastest way is to use the features of numpy:
import pandas as pd

d = {
  'child_id': [1, 2, 5, 4],
  'parent_id': [3, 4, 2, 3],
  'content': ["a", "b", "c", "d"]
}
df = pd.DataFrame(data=d)

comp1 = df['child_id'].values == df['parent_id'].values
comp2 = df['child_id'].values[::-1] == df['parent_id'].values
comp3 = df['child_id'].values == df['parent_id'].values[::-1]

if comp1.any() and not comp2.any() and not comp3.any():
  comp = np.c_[ df['content'].values[comp1] ]
elif comp1.any() and comp2.any() and not comp3.any():
  comp = np.c_[ df['content'].values[comp1], df['content'].values[comp2] ]
elif comp1.any() and comp2.any() and comp3.any():
  comp = np.c_[ df['content'].values[comp1], df['content'].values[comp2], df['content'].values[comp3] ]

print( df['content'].values[comp] )

Which outputs:
[]


text:
Q: How to declare sass variables using sass variable values to create color scheme? I have a list of my main color variables (taken from flatuicolors.com).
$turquiose: #1abc9c;
$green-sea: #16a085;
$emerald: #2ecc71;
$nephritis: #27ae60;
$peter-river: #3498db;
$belize-hole: #2980b9;
$amethyst: #9b59b6;
$wisteria: #8e44ad;
$wet-asphalt: #34495e;
$midnight-blue: #2c3e50;
$sun-flower: #f1c40f;
$orange: #f39c12;
$carrot: #e67e22;
$pumpkin: #d35400;
$alizarin: #e74c3c;
$pomegranate: #c0392b;
$clouds: #ecf0f1;
$silver: #bdc3c7;
$concrete: #95a5a6;
$asbestos: #7f8c8d;

I want to create a lighter and darker version of each, like so:
$turquiose: #1abc9c;
$turquiose-light: saturate($turquiose, 5%);
$turquiose-dark: desaturate($turquiose, 5%);
$green-sea: #16a085;
$green-sea-light: saturate($green-sea, 5%);
$green-sea-dark: desaturate($green-sea, 5%);
$emerald: #2ecc71;
$emerald-light: saturate($emerald, 5%);
$emerald-dark: desaturate($emerald, 5%);
$nephritis: #27ae60;
$nephritis-light: saturate($nephritis, 5%);
$nephritis-dark: desaturate($nephritis, 5%);
$peter-river: #3498db;
$peter-river-light: saturate($peter-river, 5%);
$peter-river-dark: desaturate($peter-river, 5%);
$belize-hole: #2980b9;
$belize-hole-light: saturate($belize-hole, 5%);
$belize-hole-dark: desaturate($belize-hole, 5%);
$amethyst: #9b59b6;
$amethyst-light: saturate($amethyst, 5%);
$amethyst-dark: desaturate($amethyst, 5%);
$wisteria: #8e44ad;
$wisteria-light: saturate($wisteria, 5%);
$wisteria-dark: desaturate($wisteria, 5%);
$wet-asphalt: #34495e;
$wet-asphalt-light: saturate($wet-asphalt, 5%);
$wet-asphalt-dark: desaturate($wet-asphalt, 5%);
$midnight-blue: #2c3e50;
$midnight-blue-light: saturate($midnight-blue, 5%);
$midnight-blue-dark: desaturate($midnight-blue, 5%);
$sun-flower: #f1c40f;
$sun-flower-light: saturate($sun-flower, 5%);
$sun-flower-dark: desaturate($sun-flower, 5%);
$orange: #f39c12;
$orange-light: saturate($orange, 5%);
$orange-dark: desaturate($orange, 5%);
$carrot: #e67e22;
$carrot-light: saturate($carrot, 5%);
$carrot-dark: desaturate($carrot, 5%);
$pumpkin: #d35400;
$pumpkin-light: saturate($pumpkin, 5%);
$pumpkin-dark: desaturate($pumpkin, 5%);
$alizarin: #e74c3c;
$alizarin-light: saturate($alizarin, 5%);
$alizarin-dark: desaturate($alizarin, 5%);
$pomegranate: #c0392b;
$pomegranate-light: saturate($pomegranate, 5%);
$pomegranate-dark: desaturate($pomegranate, 5%);
$clouds: #ecf0f1;
$clouds-light: saturate($clouds, 5%);
$clouds-dark: desaturate($clouds, 5%);
$silver: #bdc3c7;
$silver-light: saturate($silver, 5%);
$silver-dark: desaturate($silver, 5%);
$concrete: #95a5a6;
$concrete-light: saturate($concrete, 5%);
$concrete-dark: desaturate($concrete, 5%);
$asbestos: #7f8c8d;
$asbestos-light: saturate($asbestos, 5%);
$asbestos-dark: desaturate($asbestos, 5%);

I want to create a mixin (or function) that would automatically declare the lighter and darker version of each. Perhaps something like this:
@mixin color-variation($name, $color) {
    $#{$name}: $color;
    $#{$name}-light: saturate($color, 5%);
    $#{$name}-dark: desaturate($color, 5%);
}

Also, I would like to declare lighter and darker versions of a color automatically when set to a button or an element. For example:
$success-color: $green-sea; // Here I would like $success-color-light to be $green-sea-light and so on.

In the future all I want to change is the colors and the saturate/desaturate percentage to produce the theme of the style.

A: I decided to use $theme-saturation: 5%;and then saturate and desaturate whenever necessary. That way all I have to change is the that one value.


text:
Q: Getting the value of the polygon in the selected layer, in Google Earth Engine I am using Google Earth Engine to display a shapefile. I have also added an inspector to get lat/long. However I want to get the value of the column based on the polygon clicked inside this shapefile.
var text = require('users/gena/packages:text')

var shp = ee.FeatureCollection(p)

Map.addLayer(shp, {},'Divison Layer');
Map.setCenter(74.7973,34.0837, 7)

// // Create an empty image into which to paint the features, cast to byte.
// var empty = ee.Image().byte();
// // Paint all the polygon edges with the same number and width, display.
// var outline = empty.paint({
//   featureCollection: shp,
//   color: 'AREA',
//   width: 3
// });
// Map.addLayer(outline, {palette: 'FF0000'}, 'edges');

var Scale = Map.getScale()*1
var labels = shp.map(function(feat){
  feat = ee.Feature(feat)
  var name = ee.String (feat.get("DIVISION_N"))
  var centroid = feat.geometry().centroid()
  var t = text.draw(name, centroid,Scale,{
    fontSize: 10,
    textColor:'Red',
     OutlineWidth:0.5,
     OutlineColor:'white'

  })
  return t
  })
  var Labels_Final = ee.ImageCollection(labels)
  Map.addLayer(Labels_Final,{},"Division Labels")

//   // Create an empty image into which to paint the features, cast to byte.
// var empty = ee.Image().byte();

// // Paint all the polygon edges with the same number and width, display.
// var outline = empty.paint({
//   featureCollection: shp,
//   color: 1,
//   width: 3
// });
// Map.addLayer(outline, {palette: 'FF0000'}, 'Division Edges');

Map.style().set('cursor', 'crosshair');

// Create a panel and add it to the map.
 var inspector = ui.Panel([ui.Label('Click to get info')]);
Map.add(inspector);

Map.onClick(function(coords) {
  // Show the loading label.
  inspector.widgets().set(0, ui.Label({
    value: 'Loading...',
    style: {color: 'gray'}
  }));

  var click_point = ee.Geometry.Point(coords.lon, coords.lat);
  var list = shp.reduceColumns(ee.Reducer.toList(), ['DIVISION_N']  ).get('list');

    console.log(list);
   inspector.widgets().set(0, ui.Label({value: 'Long: ' + coords.lon + ' Lat:'+ coords.lat}))
  // inspector.clear()

});

Complete code:
https://code.earthengine.google.com/5f22fd8c771c05e86968236a435e03b4?accept_repo=users%2Ftylere%2Fg4g18-ee101


text:
Q: Is null possible for static final variable when Android is low on memory? I read that when Android are low on memory, it will kill the activity that is on background.
When returning to application, Android will restore from the top most stack, so when the Activity called other killed Activity that has 'static', it could return null because it hasn't recovered yet.
Question is, how about static final variable ? My understanding is that since it's final, it won't be nulled by Android and keep it's value, even when Android killed the Activity holding it.
The use case is fyi :
Activity A :
private static final String EXTRA_KEY = "key"

void goToB(){
    Intent intent = new Intent(this, B.class);
    intent.putExtra(EXTRA_KEY,"value");
}

Activity B:
void getExtra(){
   getIntent.getExtras(A.EXTRA_KEY);
}

If I'm on Activity B, put the apps on background and Android kill the activities because of memory, is it possible for A.EXTRA_KEY to be null ?
Also is this the recommended way to use EXTRA_KEY as a constant ? Thank you

A: Static variables are tied to the class. And classes rarely get Garbage Collected here's a nice answer. Generally static variables are avoided in android due to the reference issues it can create.
Here's an alternative to keep constant values such as keys, urls etc
At your app gradle file
buildTypes {
    debug {
        buildConfigField "String", "EXTRA_KEY ", "\"key\""
    }
}

retreive it like that
BuildConfig.EXTRA_KEY


text:
Q: What does an AWS Glue Crawler do I've read the AWS glue docs re: the crawlers here: https://docs.aws.amazon.com/glue/latest/dg/add-crawler.html but I'm still on unclear on what exactly the Glue crawler does. Does a Crawler go through your S3 buckets, and create pointers to those buckets?
When the docs say "The output of the crawler consists of one or more metadata tables that are defined in your Data Catalog" what is the purpose of these metadata tables?

A: The CRAWLER creates the metadata that allows GLUE and services such as ATHENA to view the S3 information as a database with tables. That is, it allows you to create the Glue Catalog.
This way you can see the information that s3 has as a database composed of several tables.
For example if you want to create a crawler you must specify the following fields:
Database --> Name of database
Service role    service-role/AWSGlueServiceRole
Selected classifiers --> Specify Classifier
Include path   --> S3 location

A: Crawlers are needed to analyze data in specified s3 location and generate/update Glue Data Catalog which is basically is a meta-store for actual data (similar to Hive metastore). In other words it persists information about physical location of data, its schema, format and partitions which makes it possible to query actual data via Athena or to load it in Glue jobs.
I would suggest to read this documentation to understand Glue crawlers better and of course make some experiments.


text:
Q: Call Github Actions in CookieCutter template I am building a template repo that uses CookieCutter. The template itself will contain github action files that execute the tests in the template.
When I make changes to the template itself, in the PR, I want to instantiate the template with the default options and then call the github action files in the template to test the template itself.
What I have working now is I instantiate the template and then use Tox and Pytest to run the tests directly.  This works but I would like to call the template action files in order to test the CICD of the template itself.
Is this possible?
TIA!


text:
Q: How do I make a query for if value exists in row add a value to another field? I have a database on access and I want to add a value to a column at the end of each row based on which hospital they are in. This is a separate value. For example - the hospital called "St. James Hospital" has the id of "3" in a separate field. How do I do this using a query rather than manually going through a whole database?
example here

A: Not the best solution, but you can do something like this:
create table new_table as
select id, case when hospital="St. James Hospital" then 3 else null
from old_table

Or, the better option would be to create a table with the columns hospital_name and hospital_id.  You can then create a foreign key relationship that will create the mapping for you, and enforce data integrity.  A join across the two tables will produce what you want.
Read about this here:
http://net.tutsplus.com/tutorials/databases/sql-for-beginners-part-3-database-relationships/

A: The answer to your question is a JOIN+UPDATE. I am fairly sure if you looked up you would find the below link.
Access DB update one table with value from another

A: You could do this:
         update yourTable
         set yourFinalColumnWhateverItsNameIs = {your desired value}
         where someColumn = 3

Every row in the table that has a 3 in the someColumn column will then have that final column set to your desired value.
If this isn't what you want, please make your question clearer.  Are you trying to put the name of the hospital into this table? If so, that is not a good idea and there are better ways to accomplish that.
Furthermore, if every row with a certain value (3) gets this value, you could simply add it to the other (i.e. Hospitals) table. No need to repeat it everywhere in the table that points back to the Hospitals table.
P.S. Here's an example of what I meant:
Let's say you have two tables
HOSPITALS
id
name
city
state

BIRTHS
id
hospitalid
babysname
gender
mothersname
fathername

You could get a baby's city of birth without having to include the City column in the Births table, simply by joining the tables on hospitals.id = births.hospitalid.

A: After examining your ACCDB file, I suggest you consider setting up the tables differently.
Table Health_Professionals:
ID First Name Second Name Position hospital_id
1  John       Doe         PI                 2
2  Joe        Smith       Co-PI              1
3  Sarah      Johnson     Nurse              3

Table Hospitals:
hospital_id Hospital
          1 Beaumont
          2 St James
          3 Letterkenny Hosptial

A key point is to avoid storing both the hospital ID and name in the Health_Professionals table.  Store only the ID.  When you need to see the name, use the hospital ID to join with the Hospitals table and get the name from there.
A useful side effect of this design is that if anyone ever misspells a hospital name, eg "Hosptial", you need correct that error in only one place.  Same holds true whenever a hospital is intentionally renamed.
Based on those tables, the query below returns this result set.
ID Second Name First Name Position hospital_id Hospital
1  Doe         John       PI                 2 St James
3  Johnson     Sarah      Nurse              3 Letterkenny Hosptial
2  Smith       Joe        Co-PI              1 Beaumont

SELECT
    hp.ID,
    hp.[Second Name],
    hp.[First Name],
    hp.Position,
    hp.hospital_id,
    h.Hospital
FROM
    Health_Professionals AS hp
    INNER JOIN Hospitals AS h
    ON hp.hospital_id = h.hospital_id
ORDER BY
    hp.[Second Name],
    hp.[First Name];


text:
Q: Doubts about the source code of connection on net/http in golang I am learning source code about golang , at the source code create new connection for each request in net/http, like:
// Create new connection from rwc.
func (srv *Server) newConn(rwc net.Conn) (c *conn, err error) {
    c = new(conn)
    c.remoteAddr = rwc.RemoteAddr().String()
    c.server = srv
    c.rwc = rwc
    c.w = rwc
    if debugServerConnections {
        c.rwc = newLoggingConn("server", c.rwc)
    }
    c.sr.r = c.rwc
    c.lr = io.LimitReader(&c.sr, noLimit).(*io.LimitedReader)
    br := newBufioReader(c.lr)
    bw := newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
    c.buf = bufio.NewReadWriter(br, bw)
    return c, nil
}

why new(conn) at this place, is there can improve performance do with get conn from sync.Pool

A: Does this question stem from measuring performance of an application or simply, as the title implies, from reading the source code? The basic rule of performance optimisation is "measure, don't guess" (see, for example, this article).
Apart from performance, there may be a good reason for not using sync.Pool here. You would need to know at what point the connection is no longer used and can safely be put back in the pool.
That said, your suggestion may have some merit if it is obvious at what point(s) in the code the connection needs to be returned to the pool. Why not measure the performance improvement for a (realistic if small) application that could benefit? If there's a really significant benefit, it might be worth proposing to the Go community. However, the main benefit of sync.Pool is to reduce GC overhead, so the application would have to create many connections for there to be a noticeable benefit.


text:
Q: how to create a security group with dynamic IP address on amazon web service i need to run an instance and access with my ip address..but the problem is that myISP changes my IP adress every day.plz help me how do i create a security group so that my instance remains accessible even if my ip changes....
thanks in advance..

A: Here's a way to restrict AWS security group to your dynamic IP address for SSH.
You can write a cronjob to regularly repeat the steps below:

*

*Fetch external IP address (e.g. http://checkip.amazonaws.com/)

*Fetch security group details using AWS SDK

*Loop through all security rules, check for port 22

*If IP address mismatches that from step 1, update it.

A: *

*Create a security group with port 22 ingress access from your current ip.

*Add a Tag to the security group with the key ssh-from-my-ip and the value true

*Whenever your IP changes run this script (or run it periodically via cron)

#! /bin/bash

# This script makes it easier to maintain security groups that allow SSH access
# from a computer with a dynamic IP, such as a computer on a home network or ISP.
#
# Using the script will allow you to SSH to an EC2 without having to allow
# access to the whole world (0.0.0.0/0). If you run this script whenever your IP
# changes then the security groups in your account specified by your AWS profile
# will be updated.
#
# The script will find any security groups for your current profile that are
# tagged with a Tag with a Key of "ssh-from-my-ip" and a case insensitive value
# of "true" or "yes".
#
# For each security group found it will revoke any existing tcp ingress on
# port 22 and authorize ingress on port 22 for your current IP.
#
# Dependencies - AWS CLI and jq

# need my current ip
MY_IP=$(curl --silent https://checkip.amazonaws.com)
echo "Your IP is ${MY_IP}"

# need security group id(s) and existing CIDR for the SG
pairs=$(aws ec2 describe-security-groups | aws ec2 describe-security-groups | jq -c '.SecurityGroups[]? | select( (.Tags[]? | select(.Key == "ssh-from-my-ip") | .Value | test("true|yes"; "i"))) | if .IpPermissions | length == 0 then {sg: .GroupId, cidr: null } else {sg: .GroupId, cidr: .IpPermissions[].IpRanges[].CidrIp} end')

for p in $pairs
do
  SG=$(echo "$p" | jq -r '.sg')
  OLD_CIDR=$(echo "$p" | jq -r '.cidr')

  echo "Updating security group ${SG}"
  if [[ $OLD_CIDR != 'null' ]]
  then
    echo "Revoking ingress permission for ${OLD_CIDR} in security group ${SG}"
    # remove the existing ingress permission
    aws ec2 revoke-security-group-ingress \
        --group-id "${SG}" \
        --protocol tcp \
        --port 22 \
        --cidr "${OLD_CIDR}"
  fi

  # authorize my new IP CIDR
  NEW_CIDR="${MY_IP}"/32
  echo "Authorizing ingress permission for ${NEW_CIDR} in security group ${SG}"
  aws ec2 authorize-security-group-ingress --group-id "${SG}" --ip-permissions '[{"IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "IpRanges": [{"CidrIp": "'"${NEW_CIDR}"'", "Description": "Rule0"}]}]'
done

A: #!/bin/bash

# User specific data:
SECURITY_GROUP_NAME="" # Setup here your group name
REGION=${1:-"us-east-1"} # Change default region if needed

USER=`aws iam get-user --query "User.UserName" | tr -d '"'`
RULE_DESCRIPTION='DynamicIP'$USER
echo 'User: '$RULE_DESCRIPTION', Region: '$REGION', Security group: '$SECURITY_GROUP_NAME

checkip () {
    OLD_CIDR_IP=`aws ec2 describe-security-groups --region $REGION --query "SecurityGroups[?GroupName=='$SECURITY_GROUP_NAME'].IpPermissions[*].IpRanges[?Description=='$RULE_DESCRIPTION'].CidrIp" --output text`
    NEW_IP=`curl -s http://checkip.amazonaws.com`
    NEW_CIDR_IP=$NEW_IP'/32'

    if [[ $OLD_CIDR_IP != "" ]] && [[ $OLD_CIDR_IP != $NEW_CIDR_IP ]]; then
        echo "Revoking $OLD_CIDR_IP"
        aws ec2 revoke-security-group-ingress --region $REGION --group-name $SECURITY_GROUP_NAME --protocol tcp --port 22 --cidr $OLD_CIDR_IP --output text >> /dev/null
    fi

    if [[ $NEW_IP != "" ]] && [[ $OLD_CIDR_IP != $NEW_CIDR_IP ]]; then
        echo "Setting up new ip $NEW_IP"
        aws ec2 authorize-security-group-ingress --region $REGION --group-name $SECURITY_GROUP_NAME --ip-permissions '[{"IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "IpRanges": [{"CidrIp": "'$NEW_CIDR_IP'", "Description": "'$RULE_DESCRIPTION'"}]}]'
    fi

    sleep 30
    checkip
}

checkip

A: You can use a Source CIDR of 0.0.0.0/0 to allow universal access.
You could restrict it to your ISP's address space by looking up their allocations or just monitoring what IP addresses you end up with.
To do it properly and restrict access to a single IP dynamic address you could write an application that monitors your public IP address and when it changes call the EC2 API AuthorizeSecurityGroupIngress method and delete the old address with RevokeSecurityGroupIngress.


text:
Q: If const doesn't allocate memory, why I can get address of const? C++ Primer said if the const can initialize while compile, it will swap the identifier to the value used when initialize, so why I can get the address of a const initialize while compile?

A: The key word in that statement is can. If the compiler can then it may replace your constant with a literal at compile time. If you take the address of the constant then the compiler must allocate memory for it so that there is something to point to. Even if you do this it may still use the literal instead of the memory location when you use the constant in other places.


text:
Q: Numpy comparing vectors of length m and n resulting in boolean matrix of size m,n I am wondering if there is a more efficient way to run the comparison (or really many other functions) using numpy.
a = np.array([1,2,5,7])
b = np.array([0,4,6])

np.repeat(a, len(b)).reshape(-1, len(b)) > b

> array([[ True, False, False],
       [ True, False, False],
       [ True,  True, False],
       [ True,  True,  True]])

Basically each output (m, n) is the comparison if A_m > B_n

A: You can use broadcasting to make this operation more efficient. Indeed, repeat creates a new temporary array. Here is the resulting code:
a.reshape(-1, 1) > b


text:
Q: if-else in stream filter java Right now I am using a  forloop to filter a list like so
LinkedList < classABC > filteredList = new LinkedList < > ();
for (ClassABC classABC: classABCList) {
 if (classABC.getName() == "ABC" && classABC.before(timestamp1)) {
  filteredList.add(classABC)
 } else if (classABC.before(timestamp2)) {
  filteredList.add(classABC)
 }
}
return filteredList

I was wondering if I could use a stream().filter() to do the same. I tried filter using multiple logical expressions but could not get it to work for compound logical expressions like (a && b) || (c)

A: As it seems Stream filter can handle compound logical expressions. So I converted the if else like so.
filteredList = classABCList.stream()
             .filter(abc ->(abc.getName() == "ABC" && abc.before(timestamp1))
                    || abc.before(timestamp2)
             ).collect(toList());

Here is an ideone example suggested by RadioDef(Thanks for the example!)
Example


text:
Q: ScrollView should have only one chilld I hava a ScrollView with one RelativeLayout as a direct child, and multiple layouts inside it. However, at runtime the app crashes, saying ScrollView can have only one direct child. What is the mistake I am making.
P.S. Sorry if the question was stupid, I have no experience with Android Programming.
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.appex.android.inquisitor.QuestionActivity"
android:background="@drawable/bg" >
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:textStyle="bold"
        android:id="@+id/textviewname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_marginTop="150dp"
        android:textColor="@color/text2"
        android:textSize="13pt"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <EditText
        android:id="@+id/edittext1"
        android:layout_width="fill_parent"
        android:maxLines="1"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:textSize="12pt"
        android:textColor="@color/text2"
        android:imeOptions="actionDone"
        android:layout_gravity="center"
        android:layout_below="@+id/textviewname"
        android:layout_marginTop="15dp"

    />
    <TextView
        android:layout_width="wrap_content"
        android:textStyle="bold"
        android:layout_height="wrap_content"
        android:id="@+id/hintview"
        android:textSize="12pt"
        android:textColor="@color/text2"
        android:layout_below="@+id/edittext1"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true" />
    <Button
        android:id="@+id/done_button"
        android:textSize="12pt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:text="@string/done_button"
        android:background="@android:color/transparent"
        android:textColor="@color/text2"
        android:layout_alignTop="@+id/hintbutton"
        android:layout_marginLeft="189dp"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12pt"
        android:textStyle="bold"
        android:id="@+id/hintbutton"
        android:text="@string/hintbutton"
        android:background="@android:color/transparent"
        android:textColor="@color/text2"
        android:layout_marginLeft="101dp"
        android:layout_marginTop="14dp"
        android:layout_below="@+id/hintview"
         />
    <TextView
        android:id="@+id/attemptview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/text2"
        android:textSize="10pt"
        android:layout_marginTop="75dp"
        android:layout_alignLeft="@+id/done_button"
        android:layout_alignStart="@+id/done_button"
    />
</RelativeLayout>
</ScrollView>

A: You should wrap everything within the scrollView in a LinearLayout with wrap_content for the height.
This question is already answered here:
Scrollview can host only one direct child

A: Try adding a Relative layout  before ScrollingView.


text:
Q: LayerSlider: Hide slide in the sequence I am using LayerSlider plugin in Wordpress.
I tried to use event callbacks to run custom code when certain actions occur in sliders like described in this tutorial.
Is there a way to hide slide in the sequence.
I tried the below code where I want to jump to slide "4" based on condition but this didn't work (It still show all slides).
function( event, slider ) {
    if(slider.slides.current.index == 2){
        $('#slider').layerSlider(4);
    }
}

Please any idea.


text:
Q: SQL Insert with sub-select and multiple rows I have an existing documents table and a new permissions table. I want to create a script that will give all permissions to all of the existing documents. The documents_permissions table will need the document_id and permission_id (1,2,3). So for each document I will need to insert 3 rows. This is where I am at atm:
INSERT INTO `documents_permissions` (`document_id`, `permission_id`)
SELECT `id`, '1' FROM `documents`

but I'd need to repeat that for each permission. What is the best way to do this?

A: try this:
USe CROSS JOIN
INSERT INTO `documents_permissions` (`document_id`, `permission_id`)
select  `id`,a.permissions
 from(
select 1 as permissions union all
select 2 union all
select 3 )a
cross join
`documents` d

A: INSERT INTO `documents_permissions` (`document_id`, `permission_id`)
select id, pid from `documents`
cross join (select 1 as pid union select 2 union select 3)X


text:
Q: PYTHON: How should I change my code to reorganize files by day rather than by month? I've got a bit of code that renames and reorganizes NetCDF files into monthly folders. I would like to change this code so that it gives me daily folders rather than monthly folders.
import os
from datetime import datetime

destination_directory = input("Now please provide the destination directory in the same format:")

wd = os.chdir(destination_directory)
for f in os.listdir():
    file_name, file_ext = os.path.splitext(f)
    f_1, f_2, date = file_name.split('.')
    dt = datetime.strptime(date,"%Y%m%d%H%M")
    newname = "{}{}{}{}.{}".format(str(dt.year),str(dt.month),str(dt.day),str(dt.time().hour)+str(dt.time().minute),'nc')
    dst = os.path.join(str(dt.year),str(dt.month),newname)
    if os.path.isdir(os.path.join(str(dt.year),str(dt.month))) == False:
        os.makedirs(os.path.join(str(dt.year),str(dt.month)))
    os.rename(f, dst)
    print(dst, newname, 'created')

A: All you have to do is to add day to your paths. Like this:
dst = os.path.join(str(dt.year),str(dt.month),str(dt.day),newname)
if os.path.isdir(os.path.join(str(dt.year),str(dt.month),str(dt.day))) == False:
    os.makedirs(os.path.join(str(dt.year),str(dt.month),str(dt.day)))


text:
Q: line color change based on logic in apache echarts Due to the company policy I can't share any kind of code but I have been struggling with apche echarts. The requirement is I have a line whose color should change at certain points based on logic. I tried achieving using linestyle and piecewise using dimension. I came pretty close to visualmap but the issue persisted when The parallel or adjacent lines started to get affected and caused wrong color changes on the graph. Here is the requirement the line on the chart is supposed to be red unless we come across a point where the color could be changed to green and back to red when the event is done. please refer to the image and I am open to any and all suggestions. I would prefer a sandbox as an answer link so i can test if that works with the requirement or not.
EDIT 1 The closest I came is this
option = {
    title: {
        text: '一天用电量分布',
        subtext: '纯属虚构'
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross'
        }
    },
    toolbox: {
        show: true,
        feature: {
            saveAsImage: {}
        }
    },
    xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['00:00', '01:15', '02:30', '03:45', '05:00', '06:15', '07:30', '08:45', '10:00', '11:15', '12:30', '13:45', '15:00', '16:15', '17:30', '18:45', '20:00', '21:15', '22:30', '23:45']
    },
    yAxis: {
        type: 'value',
        axisLabel: {
            formatter: '{value} W'
        },
        axisPointer: {
            snap: true
        }
    },
    visualMap: {
        show: false,
        dimension: 0,
        pieces: [{
            lte: 6,
            color: 'green'
        }, {
            gt: 6,
            lte: 8,
            color: 'red'
        }, {
            gt: 8,
            lte: 14,
            color: 'green'
        }, {
            gt: 14,
            lte: 17,
            color: 'red'
        }, {
            gt: 17,
            color: 'green'
        }]
    },
    series: [
        {
            name: '用电量',
            type: 'line',
            smooth: true,
            data: [300, 280, 250, 260, 270, 300, 550, 500, 400, 390, 380, 390, 400, 500, 600, 750, 800, 700, 600, 400],
        }
    ]
};

which renders

how can I use logic to calculate the visualmap points based on event.

A: You can do that using the visualMap component which maps the data to visual channels.
Like in your example, in a Line series chart you have:
visualMap: {
 show: false,
 dimension: 0,
 pieces: [
  {
    lte: 6,
    color: 'green'
  },
  {
    gt: 6,
    lte: 8,
    color: 'red'
  },
  {
    gt: 8,
    lte: 14,
    color: 'green'
  },
  {
    gt: 14,
    lte: 17,
    color: 'red'
  },
  {
    gt: 17,
    color: 'green'
      }
   ]
 },

The data for the Line chart is an array of 20 values so the above means: draw the line green for the first 6 values, draw red for values between 6 and 8, then green till 14th value, then red for 14th to 17th value and then green for the values thereon.

See the example here.


text:
Q: Query String issue when it contains Arabic text I am trying to get query string from url With this code:
this.site_query = Request.Url.Query;

When I have get url:

http://localhost:1751/ar/search?q=سيارة

It gives me blow output in code:

http://localhost:1751/ar/Search?q=%D8%B3%D9%8A%D8%A7%D8%B1%D8%A9&Location=%D8%A3%D8%A8%D9%87%D8%A7,Abha

But I need Arabic text that I send in query string. When query string contains   text in English then in c# it is correct.

A: There is nothing wrong with the second URL you have shown in your answer, it's just being URL encoded due to the limitations of what characters are allowed in URLs.
If you wish to get parts of the query string in code, you can use code like this:
var query = Request.QueryString["q"];

Additionally, if you are building your URLs in code, you should always URL encode and values that may contain non standard characters:
var urlEncodedValue = HttpUtility.UrlEncode(someValue);

A: As others said already: it's an encoded URL. You can decode with
var decodedUrl = HttpUtility.UrlDecode(url);

or
var decodedUrl = Uri.UnescapeDataString(url);

Is that what you need? If not, show us your expected output.

A: For this use
string name = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim()));
    string technology = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value));
for encoding url.


text:
Q: ListViewDataItem does not contain a property with the name 'CommentId' when using DataBinder.Eval I have a ListView which displays all the comments made by users on a specific news article.
I need the comment's and author's ids for each comment so I can show a delete button next to it (if it is made by the respective user).
The problem is that the line DataBinder.Eval(dataItem, "CommentId") throws the following error

System.Web.UI.WebControls.ListViewDataItem' does not contain a property with the name 'CommentId'.

I also tried changing from CommentId to Comments.CommentId, but with no luck.
What I am doing wrong?
Any help is appreciated.
Thanks!
In News.aspx
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" OnItemDataBound="ListView1_ItemDataBound">

                    <ItemTemplate>

                                        <asp:Label Text='<%# Eval("UserName") + ":"%>' runat="server" ID="UserNameLabel" Font-Bold="true" />

                                        <asp:Label Text='<%# Eval("body") %>' runat="server" ID="bodyLabel" />

                                        <asp:Button ID="DeleteCommentButton" runat="server" Text="Delete" OnClick="DeleteCommentButton_Click" />

                    </ItemTemplate>

                    <LayoutTemplate>

                    </LayoutTemplate>

                </asp:ListView>
                <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ ConnectionStrings:DefaultConnection %>' SelectCommand="SELECT Comments.CommentId, Users.UserId, Comments.body, Users.UserName FROM Comments INNER JOIN Users ON Comments.UserId = Users.UserId WHERE NewsId = @NewsId">
                    <SelectParameters>
                        <asp:Parameter Name="NewsId" Type="Int32" />
                    </SelectParameters>
                </asp:SqlDataSource>

In News.aspx.cs:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = (ListViewDataItem)e.Item;

            int commentId = (int)DataBinder.Eval(dataItem, "CommentId");
...

A: I solved it like this:
ListViewDataItem dataItem = e.Item as ListViewDataItem;
int commentId = (int)DataBinder.Eval(dataItem.DataItem, "CommentId");
Guid authorId = (Guid)DataBinder.Eval(dataItem.DataItem, "UserId");