position text in top of EditText

Question: i have this for an xml Edittext , which i may made a little bigger allowing the user to type a longer text , but the hint is always showing up in the middle of the text Area , and i want to put it in the top of the Edit Text , How can id do this ?
<EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textMultiLine"
                android:padding="5dp"
                android:minHeight="200dp"
                android:layout_marginTop="50dp"
                android:background="@drawable/textlines"
                android:hint="@string/text"
                android:layout_marginRight="35dp"
                android:layout_marginLeft="35dp"/>

Comment: Did you try `android:gravity`..?
Comment: yes , and it didn't work .
Comment: Try this too..set the `android:includeFontPadding` attribute to false in your XML
Comment: Tried it , didn't work always .
Comment: Try adding theese too in your xml file..` android:lines="5"   android:singleLine="false"` along with gravity..
Comment: even that is not working
Comment: Try chnaging `android:layout_height="wrap_content"` to `android:layout_height="fill_parent"`
Answer: <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textMultiLine"
                android:paddingBottom="15dp"
                android:paddingTop="5dp"
                android:paddingLeft="5dp"
                android:paddingRight="5dp"
                android:minHeight="200dp"
                android:layout_marginTop="50dp"
                android:background="@drawable/textlines"
                android:hint="@string/text"
                android:layout_marginRight="35dp"
                android:layout_marginLeft="35dp"/>

Comment: this is more of a hack than a logical solution , is this the only way to do it  ?
Answer: You need to set the gravity to top and mask it with left
sample:
 <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textMultiLine"
                android:padding="5dp"
                android:minHeight="200dp"
                android:layout_marginTop="50dp"
                android:hint="I am hint"
                android:gravity="top|left"
                android:layout_marginRight="35dp"
                android:layout_marginLeft="35dp"/>

result:

position text in top of EditText


Bing Map offline development? Is this possible?

Question: I am trying to add 3d images to Bing maps, however I do not have an internet connection at my work pc and I would like to know how I could work on adding things to bing maps when no internet is available. Is there a way I can download samples of bing map that allow me to work with bing map and the bing map api?
Thanks
Answer: Whilst technically easy to do, the Bing Maps Terms of Use explicitly prohibit creating a local copy of the API or any Bing Maps content (with no internet connection, you'd also need to create a local copy of all the base map tiles that would normally be served to the client) - see http://www.microsoft.com/maps/product/terms.html
The only legal way of creating a local Bing Maps installation with no internet connection that I'm aware of is by purchasing a licence for the Bing Maps Server provided by Vexcel - http://www.vexcel.com/geospatial/bingmapsserver/index.asp. However, don't expect it to be cheap...
Answer: From the Vexcel website's FAQ:

Q. Can I import DEM's or 3D models into Bing Maps Server or Bing Maps
  Desktop?
A. This capability is under development.

By the way, Vexcel Corporation, as Microsoft's geospatial subsidiary, is the exclusive provider of the Bing Maps Server.


How do I setblock at the location of an item?

Question: When I was trying out MrGarettos Command Combiner
I wanted to place a fire block at 2 items which they are...
Netherrack and Flint and steel.
But the question is how do I do /setblock at an item??
Answer: This command should work.
<code>execute @e[type=item,(some other condition like name or specific item)] ~ ~ ~ /setblock ~ ~ ~ fire
</code>
Comment: I want to look for more than one item though, I want to look for Netherrack and Flint and Steel together.


How to spit in the black pool?

Question: During the League of Monster Slayers admission quest, you are required to spit in the Black Pool.
I found the pool, fought some monsters in and around it, but cannot spit in the pool itself.
How can I accomplish this tier of the quest?
Answer: There are "emotes", that is, gestures and movements you can trigger from the chat box. They are much like IRC and such; enter "/help" and you get a list of all the available emotes.
"/spit", then, will allow you to spit - so stand by the pool and do it!
Comment: I can confirm the emote will do it.  Take care not to step IN the pool while you do it!
Comment: type "/spit" in chat works

How to spit in the black pool?


UIVisualEffect view Should not have value less than 1, this interferes with blurring in iOS

Question: In one of my iOS app i am using iOS native component VisualEffectView with Blur to get blur effect.
For my User Interface requirement, i had set visual effect view's alpha value as 0.85, then Xcode throwing a compile time warning saying UIVisualEffect view Should not have value less than 1, this interferes with blurring. How do i bypass this warning without making my alpha value as 1.
I am using Xcode 8.3.1.
Answer: The Apple Documentation  state :

When using the  UIVisualEffectView  class, avoid alpha values that are
  less than 1
Comment: @krishnarjun-banoth you can not set alpha value less than 1 on visual effect view but you can set alpha on its content view.
Comment: Thanks for your patience but i am not benefitted by setting alpha on content view.
Comment: Apple is saying, Setting the alpha to less than 1 on the visual effect view or any of its superviews causes many effects to look incorrect or not show up at all. Then why can't apple restrict to set alpha value less than 1.


Changing basement tub drain to shower drain - double 90 degree while horizonal, is this bad?

Question:
We are finishing our basement and had a plumber come out to move the toilet drain and install a drain for a tub/shower combo to fit the floor plan we decided on.  He installed the tub, but we changed our minds and are putting in a shower instead.  The shower base I am using is slightly wider than the tub was (36" vs 30"), and the drain is further to the right and further from the wall from where the tub drain is, so I need to move it.
I raised the valve and capped off the bottom that went to the tub spout so that it will work for the shower.  That part went fine, but the drain I am unsure of.
After digging up the tub drain I see he used what may have been a potential tub/shower drain for the original floorplan that was just left buried (there is no stub out from the floor, only for the toilet) and there are two 90 degree elbows, a 45, then a P-trap, then vertically a couple of 45 elbows.
I thought about putting a horizontal section above the two vertical 45 degree elbows to reposition the drain, but I'm worried about increasing the possibility of clogs.  A second thought was that since the short section between the P-trap and the horizontal elbows is 7/8" I could cut that off and put a new ptrap, and use 45 degree elbows to reposition the drain since there should be enough vertical room.
First, Are either of those 2 solutions going to cause problems?  Would keeping those horizontal elbows (two 90 degree and one 45 degree) make it easier to get clogs?
Answer: Is this what you mean? This looks like the only way you are going to get it where  you need it to go.
Comment: Yep that's what I was thinking would need to be done to get it to fit
Comment: Good deal, with a 2" line for a shower or tub, clogging should not be an issue. All clogs I have ever seen in this occasion are always at the drain. Besides, looking at the existing conditions, that was about the only way to get a drain in place.


Rails - Why would I get the following output?

Question: In running through the basic rails tutorial section about outputting comments, I get the following displayed:
Comments

Commenter: Me
Comment: Hi

#<Comment:0x1052af610>

In the view I have:

Comments

<%= @post.comments.each do |comment| %>

  Commenter:
  <%= comment.commenter %>

  Comment:
  <%= comment.body %>

<% end %>

and in the controller I have:
class CommentsController < ApplicationController
  def create
    @post = Post.find(params["post_id"])
    @comment = @post.comments.create(params[:comment])
    redirect_to post_path(@post)
  end
end

So where is the bit: #<Comment:0x1052af610> coming from?
Answer: Replace %= with % before @post.comments.each do |comment|
... but it's been a few years since I've used Rails, so I could be totally nuts.


node v6.11.0 JavaScript heap out of memory when no memory is used in the program

Question: Getting an out of memory of error when no memory storage is used except two variables(i & j). Can someone please clarify.
I'm not storing anywhere in memory or writing it to any storage, whatever is generated gets spits to console and need to move to next instruction.
console.log('num,num2,op,result');
for(i=9.0;i>=0;) {
  for(j=9.0;j>=0;) {
     console.log(i.toFixed(3) + ',' + j.toFixed(3) + ',+,'  + (i+j).toFixed(3));
     j =parseFloat((j - 0.001).toFixed(3));
  }
     i =parseFloat((i - 0.001).toFixed(3));
 }

Executing this getting stack error,
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [/usr/local/bin/node]
 2: node::FatalException(v8::Isolate*, v8::Local<v8::Value>, v8::Local<v8::Message>) [/usr/local/bin/node]
 3: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/local/bin/node]
 4: v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationSpace) [/usr/local/bin/node]
 5: v8::internal::Runtime_AllocateInTargetSpace(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/local/bin/node]
 6: 0x3006473079a7
Abort trap: 6

Please let me know what I'm missing to avoid memory crash.
More Research:

To our code, it does not make any difference whether console.log is
  async or not, it does not provide any kind of callback or so; and the
  values you pass are always referenced and computed at the time you
  call the function.

Reference:
console.log() async or sync?
It references the data only at the time of referring the data associated with it.
Will also check for any memory leaks associated with parseFloat or toFixed.
Comment: @Kannaiyan `console.log` will use a lot of ram, also the `toFixed` and `parseFloat` functions will use ram - just like every other operation that doesn't fit into registers.
Comment: *memory* means RAM here, and every variable etc. resides in the RAM. But no, your code does not use much memory so the memory leak must be somewhere else
Comment: The only variable used is i & j. I'm not seeing anything holding on to RAM.
Comment: But once console.log completes, it goes to console and ram will be cleared right. Is there anyway I can flush it out of process? I under toFixed and parseFloat are functions, they should also clear their memory once function is complete right? Also assuming they are synchronous. I'm not seeing that will run their asynchronously.
Comment: Yes, the only thing that continues to acquire memory is the console output buffer, the rest should remain in constant memory. Do you actually see anything on the console? How far does it run?
Comment: 7.843,3.483,+,11.326
7.843,3.482,+,11.325

Those are the last values seen. I'm trying to generate these for ml data learning.
Answer: console.log is buffering and exceeding memory limits.
Using buffer flush to flush it to the system console, it will be able to proceed indefinitely.
Here is how I could solve it,
var logbuffer = require('log-buffer');
console.log('num,num2,op,result');
for (i = 9.0; i >= 0;) {
    for (j = 9.0; j >= 0;) {
        console.log(i.toFixed(3) + ',' + j.toFixed(3) + ',+,' + (i + j).toFixed(3));
        j = parseFloat((j - 0.001).toFixed(3));
    }
    logbuffer.flush();
    i = parseFloat((i - 0.001).toFixed(3));
}

I will wait for comments and any issues anyone may find before I accept it as an answer.
Thanks for all the comments in the questions which helped to debug and solve further.


Can I show the global menu on all displays?

Question: Let's say I have a two monitor setup.
I open Firefox on display #1. If I hover my mouse to select a menu item on display #1, the global menu will show. But if I hover the mouse to select a menu item on display #2 nothing will show, unless I move the Firefox window to the second display. But then the global menu will not show on display #1.
Can I make the global menu show on all displays, no matter on which display the application is visble?
Please note that I do not want to disable the auto-hide feature.
Edit: Adding a reason on why I need this:
One of the reasons I ask for this, is because I regularly connect my laptop to my TV Set and watch movies (I use VLC). So, most of the times I want to access the menu of VLC without the need of interrupting the playback.
And even if I did interrupt the playback, VLC's playlist can be undocked from the main window, and become a window on its own.
So I always keep the playlist on the laptop display, and the movie on full screen on the TV display. And even if the playlist is the active window, since VLC's main window is on the TV display, the menu would only show on the TV display, and not on the laptop.
Comment: I can't figure out how can be VLC's playlist undocked from the main window. Can you?
Comment: @RaduRădeanu Yeah, sure. In VLC's menu go to `Tools`. In it, there is an menu option called `Docked playlist`. Uncheck it.
Comment: I found it. For me *Dock playlist* is in *View* (I use VLC media player 2.0.6). Now, as you can check the problem is that the Playlist doesn't have any kind of menu when the focus is on it (appearing only *VLC media player* in global menu) indifferent in which display is the Playlist window. So this is a problem with Playlist menu (you can [report it like a bug](http://askubuntu.com/questions/5121)) and nothing to do with global menu. As an alternative, **you can use the VLC menu from notification area** (system tray) which is visible in every display, indifferent where is VLC window.
Answer: No, you can't (only if someone will make an application/program to do so or if you select Mirror displays in System settings > Hardware > Displays). The thing you're asking is inconsistent.
Think that you have one application (Firefox) opened on the display #1 and another one (let say Chromium) on the display #2. Now, you look at the display #2, so you use Chromium and you will see in global menu the menu for Chromium. What reason do you have now to see in global menu the menu for Firefox that is displayed on display #1? And vice versa. This makes no sense...
Comment: I'm not saying you are not right, but this is not an answer to the question, should be posted as a comment?
Comment: The global menu is supposed to be shown for the activated application. If I'm using Firefox, and Chromium is on the other screen, I still want to see the Firefox menu since it's the application I'm using.
Comment: @RaduRădeanu I edited the question to shed some light on a reason behind this, and to explain why this would make sense.
Comment: @Dan *"The global menu is supposed to be shown for the activated application"* **on the display where you are using the respective application**. I think that the global menu is a "child" process of the display, not the other way.
Comment: @Nanne I am sorry for a neggative answer, but this is the answer.
Comment: After your edits it does look more like an answer indeed, the comment was ofcourse aimed at your answer before your edits....
Comment: @RaduRădeanu I don't think you're right about it being inconsistent. In your example, the current behavior is to show Chromium's menu on display #2 and an _empty_ bar on display #1. Implementation details aside, there's conceptually no reason the empty bar couldn't be replaced with another copy of Chromium's menu.
Comment: @ændrük Conceptual, the global menu it shows you a menu with what you have in front (the application on which you are focused) on the current display. See [this comment](http://askubuntu.com/questions/305674/can-i-show-the-global-menu-on-all-displays/306739?noredirect=1#comment386444_306739).
Comment: @RaduRădeanu Yes, that is what it does, and this is a question about making it do something different.
Comment: @ændrük No, the question is "*Can I show the global menu on all displays?*" and the short answer is "*no*". Or, as I said, we can wait someone to make a script/application/program to do so. Unlikely to see that will happen.
Answer: If dosn't matter in wich screen apper firefox you can duplicate screen so you will be able to see the same in bouth screens.
Sorry for my speling
Comment: That's mirrored displays, I do not want that.


Keeping trailing zeros

Question: I would like to keep trailing zeros, for example, if I type:
round(5.2, 3)

I would like the output to be:
5.200

Answer: If this is for printing purposes, sprintf is what you are after:
> sprintf("%.3f", round(5.2,3))
[1] "5.200"

See ?sprintf for formatting details.
Comment: @Marco: I think no, a numeric value does not have trailing zeros.
Comment: @Chase: Is there the possibility to output a numeric value instead of a character???
Comment: @Marco `5.2` == `5.200` they are the same number, the only difference is how the number is represented as a String
Comment: @tim_yates: Yes, of course this is the same. The reason why I was wondering is, as it was suspected, is printing purpose.
Comment: If it's not for printing purposes what could be used instead of `sprintf(...)`?
Comment: @rnorouzian then we use as is: `5.2`.
Answer: When you print it out, you should be able to do:
formatC( round( 5.2, 3 ), format='f', digits=3 )

Comment: Is there anything that could be changed using 'options()' in order to keep trailing zeros? I understand 5.2 == 5.200 but, in my case, for visual consitency it would be nice to keep trailing zeros. Since I am using annotate  with 'parse=T' a string such as provided by 'formatC' isn't enough.
Comment: Thank you. I am sorry, I cannot accept more than one answer. I have chosen to accept the previous one since Chase has a lower reputation score. However, your solution is very good as well.
Thank you again!
Comment: I don't understand what you mean
Comment: How about something that works both for printing and non-printing purposes?
Comment: Previously, I rounded like that but stopped because I thought there was an unnecessary step with the round() function. Do you remember why we are/were doing this:
formatC(round( 5.455, 2), format='f', digits=2 )
and not this:
formatC(5.455, format='f', digits=2 )
It seems as if both are rounding according to the IEEE standard (next even number).

Keeping trailing zeros


How to get shuch effect of AppBar title in Flutter?

Question: How I can get such effect of AppBar title, sample:

The big title "Coffee shop" disappears when page scrolls and appears in appBar. Thanks.
Answer: probably you need SliverAppBar

You can also check this tutorial

An example based on the article:
<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'App',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MainCollapsingToolbar());
  }
}

class MainCollapsingToolbar extends StatefulWidget {
  @override
  _MainCollapsingToolbarState createState() => _MainCollapsingToolbarState();
}

class _MainCollapsingToolbarState extends State<MainCollapsingToolbar> {
  ScrollController _scrollController = ScrollController();
  double offset = 0.0;
  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      setState(() {
        offset = _scrollController.offset;
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: DefaultTabController(
        length: 2,
        child: NestedScrollView(
          controller: _scrollController,
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              SliverAppBar(
                expandedHeight: 200.0,
                floating: false,
                pinned: true,
                flexibleSpace: FlexibleSpaceBar(
                  centerTitle: (offset == 0) ? false : true,
                  title: Text("Collapsing Toolbar",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.0,
                      )),
                ),
              ),
              SliverPersistentHeader(
                delegate: _SliverAppBarDelegate(
                  TabBar(
                    labelColor: Colors.black87,
                    unselectedLabelColor: Colors.grey,
                    tabs: [
                      Tab(icon: Icon(Icons.info), text: "Tab 1"),
                      Tab(icon: Icon(Icons.lightbulb_outline), text: "Tab 2"),
                    ],
                  ),
                ),
                pinned: true,
              ),
            ];
          },
          body: Center(
            child: Text("Sample text"),
          ),
        ),
      ),
    );
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate(this._tabBar);

  final TabBar _tabBar;

  @override
  double get minExtent => _tabBar.preferredSize.height;
  @override
  double get maxExtent => _tabBar.preferredSize.height;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new Container(
      child: _tabBar,
    );
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return false;
  }
}
</code>
Comment: I tested a lot of examples of using the slivers, but did not find a suitable one. I need to get exactly the same effect as in the example.
Comment: The problem is placing a large header. There is an option to use a sliver with a FlexibleSpaceBar, but I get an "error" described here: https://github.com/flutter/flutter/issues/23864
Comment: I don't think you will find exactly the same example. You have to experiment a little bit to figure out how you can fix it. I updated the answer with an example based on the Medium article. Hope it will help
Comment: Using a ScrollController and checking the scroll status is a solution. Thank!


Installing Theano on Windows - DLL load failed

Question: I am trying to install Theano on Windwos 8
Have followed these steps.
I try to test using:
import numpy as np
import time
import theano

print('blas.ldflags=', theano.config.blas.ldflags)
A = np.random.rand(1000, 10000).astype(theano.config.floatX)
B = np.random.rand(10000, 1000).astype(theano.config.floatX)
np_start = time.time()
AB = A.dot(B)
np_end = time.time()
X, Y = theano.tensor.matrices('XY')
mf = theano.function([X, Y], X.dot(Y))
t_start = time.time()
tAB = mf(A, B)
t_end = time.time()
print("NP time: %f[s], theano time: %f[s] (times should be close when run on CPU!)" % (
np_end - np_start, t_end - t_start))
print("Result difference: %f" % (np.abs(AB - tAB).max(), ))

I am aware that the script is comparison between numpy and theano computation time.
But somehow, some dll is not found. Pl find the following log:
[Py341] C:\>python ML\Deep\TheanoSetupTesting.py
blas.ldflags= -LE:\Things_Installed_Here\Theano\openblas -lopenblas
Traceback (most recent call last):
  File "ML\Deep\TheanoSetupTesting.py", line 12, in <module>
    mf = theano.function([X, Y], X.dot(Y))
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\compile\function.py", line 317, in function
    output_keys=output_keys)
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\compile\pfunc.py", line 526, in pfunc
    output_keys=output_keys)
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\compile\function_module.py", line 1778, in orig_function

    defaults)
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\compile\function_module.py", line 1642, in create input_storage=input_storage_lists, storage_map=storage_map)
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\gof\link.py", line 690, in make_thunk
    storage_map=storage_map)[:3]
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\gof\vm.py", line 1037, in make_all
    no_recycling))
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\gof\op.py", line 932, in make_thunk
    no_recycling)
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\gof\op.py", line 850, in make_c_thunk
    output_storage=node_output_storage)
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\gof\cc.py", line 1207, in make_thunk
    keep_lock=keep_lock)
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\gof\cc.py", line 1152, in __compile__
    keep_lock=keep_lock)
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\gof\cc.py", line 1602, in cthunk_factory
    key=key, lnk=self, keep_lock=keep_lock)
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\gof\cmodule.py", line 1174, in module_from_key  module = lnk.compile_cmodule(location)
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\gof\cc.py", line 1513, in compile_cmodule
    preargs=preargs)
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\gof\cmodule.py", line 2196, in compile_str
    return dlimport(lib_filename)
  File "E:\Things_Installed_Here\Anaconda_Py\envs\Py341\lib\site-packages\theano-0.7.0-py3.4.egg\theano\gof\cmodule.py", line 331, in dlimport
    rval = __import__(module_name, {}, {}, [module_name])
ImportError: DLL load failed: The specified module could not be found.

being new to python world, I am not able to find out which Dll in not found. I would install it if missing and would add the path the system path variable. But how do I get to know which dll it is. I tried using pdb and set a breakpoint in cmodule.py at various locations, but none gets hit.

Are you familiar to this kind of error and its resolution?
Otherwise, help me find that missing dll name, and I'll do the rest.
I do not mind a walking a completely different path in installing theano. I came across few posts which suggest microsoft compiler works just fine. But I am already sitting on a problem since past 14 hours continuously and would want a method which works. Ultimately I want theano on my system.

BTW, do not have a CUDA. I am trying on CPU only.
Comment: Hi there. Suffering from the same problem here. Really, theano on Windows 64bit is a catastrophy. One problems hunts the next, and if your depatment just does not use/allow linux, what choice is there?
Answer: This may be a little bit late. I followed the exact same guide as you, and ran into the same error.
Turns out that it can be fixed by adding the openblas directory to system path. In your example, add "E:\Things_Installed_Here\Theano\openblas" to system path variable.
Note that depending on where you put the DLL files, you either need to add "E:\Things_Installed_Here\Theano\openblas" or "E:\Things_Installed_Here\Theano\openblas\bin".
Windows 10 64 bit, Python 3.5.1 (Anaconda 2.5), Theano 0.8.2.
For those who need it, I am able to install Theano in Windows 10 thanks to these three guides guide1, guide2 and the guide attached by OP.
Comment: unfortunately, I cannot test it, i am enjoying the world of `linux`. For the people this works, add it in comments, over a period of time, this might become the working solution
Answer: OK, I finally found the reason at least for my installation using WinPython, python188.8.131.52, Win 7 64bit and mingw64:
In the .theanorc[.txt] file, I ha, after installing blas, a section [blas] with a line including the openblas include path. I removed that line and left the area below [blas] blank. Restarted WinPython/Spider, opened a new console and it worked.
Testet afterwards with running mnist.py from Lasagne using Theano.
Comment: I had done this, but it did not work for me. I have surrendered to it and moved to linux - things are blazing fast :P. I appreciate your efforts.
Answer: I was struggling with getting theano to work on Windows 10 x64 as well, and after reading several help guides, what worked for me in the end was the following:

Install Intel Distribution for Python (make sure c:\intelpython27\ and c:\intelpython27\scripts are in the PATH)
Open a command line and do: conda install mingw libpython
Then do: pip install theano
Download the precompiled libopenblas.dll from  http://sourceforge.net/projects/openblas/files/v0.2.14/ (I got OpenBLAS-v0.2.14-Win64-int32.zip)
Download mingw64_dll.zip as well from http://sourceforge.net/projects/openblas/files/v0.2.14/mingw64_dll.zip/download
extract OpenBLAS-v0.2.14-Win64-int32.zip to c:\openblas, for example
extract mingw64_dll.zip to c:\openblas\bin
Add c:\openblas\lib and c:\openblas\bin to PATH
Create .theanorc.txt in c:\Users\{username}
Put the following in .theanorc.txt:
[global]
floatX = float32
device = cpu

[blas]
ldflags = -LC:\\openblas\\bin -LC:\\openblas\\lib -lopenblas

Hope this helps someone.
Answer: Just to add my experience with Win10 64bit and theano (and keras). I was getting the  DLL load fail error as well. Tried all the stuff I have found on theano win install  webpage and in the different forum and blog posts (mentioned here in Uradium's post).
It didn't work for me, but here is what worked:

I installed TDM-GCC-64 and openblas, using regedit I have added their /bin directories to PATH (and /lib directory of openblas as well)
made clean venv under miniconda3 - installed prerequisites for theano and keras (scipy, numpy, pyyaml), python 3.5.2
conda install mingw libpython
conda install theano (installs all the mingw libraries as well)
at this point - it worked - so I didnt use any .theanorc.txt file configuration, no fiddling with Windows environment variables. It even worked for keras based python scripts, even-though I had not installed keras into my conda venv it was working in...(I have keras installed in my "normal" non-conda python3, and later I pip installed keras under my conda venv as well).
Answer: Quite late, but for future reference. I stumbled upon this thread trying to run an OpenBLAS test script on the CPU. It worked fine on the GPU but the CPU gives me the same errors as the OP. I tried the suggestions here, but that didn't work. Turns out that the line in .theanorc:
ldflags=-LE:\OpenBLAS-v0.2.14-Win64-int32/bin -lopenblas

shouldn't have the space after bin and before -l. So it should be:
ldflags=-LE:\OpenBLAS-v0.2.14-Win64-int32/bin-lopenblas

Now everything works. Tried it on:
Windows 10
Python 3.5
Theano 0.9
Cuda 8 (with CudaMEM and CudaDNN)
Visual Studio 2015 Community

Answer: I have this problem and I get this solution,
after install theano,again I reinstall numpy . I solved this problem
pip uninstall numpy
pip install numpy


Anaconda enterprise connection to cloud vs. 'offline'

Question: On my company PC, I do not have full permissions to install Python packages(usually this has to be requested for approval from IT, which is very painful and takes a very long time).
I am thinking to ask my manager to invest in Anaconda Enterprise so that the security aspect of open source Python use will not be an issue anymore. However, also to consider, my boss is looking to move to the cloud and I was wondering if Anaconda Enterprise can be used interchangeably on-premise (offline from cloud, i.e., no use of cloud storage or cloud compute resources) and when needed for big data processing, switched to 'cloud mode' by connecting to any of AWS, GCP, Azure to rent GPU instances? Any advice welcome.
Comment: Ask Anaconda Enterprise support - this sounds off topic for SO.
Answer: Yes, that can be a good approach for your company, I used it in many projects on GCP and IBM cloud over Debian 7,8 and 9, and is a good approach, you can also depend on your need to create a package channel with the enterprise version and manage the permissions over your packages and it has a deploying tool where you can manage the deploys and audit the different for projects and API's as well also track the deployments and assign them to owners.
You can switch your server nodes to different servers or add and remove as well when you work with those depending on your environment can be difficult at the beginning but is pretty good after implemented.
Below are some links where you can see more information about what I'm talking about:
using-anaconda-enterprise
conda-offline-install-update
server-nodes
Answer: Depending on your preferences it may not be necessary to use anaconda enterprise on GCP. If you're boss is looking to move to the cloud then GCP has some great options for analyzing big data. Using the AI Platform you can deploy a new instance choose R, Python, CUDA, TensorFlow etc. Once the instance is deployed you can start your data preprocessing. Install whatever libraries you desire, Numpy, Scipy, Pandas, Matplotlib etc. And start your data manipulation.
If using something like Jupyter Notebooks you can use that offline to prepare your work before entering the GCP platform to run the Model Training.
Oh, also GCP has many labs to test out their Data Science platform.
https://www.qwiklabs.com/quests/43
GCP has many free promos these days below is a link to one.
GCP - Build your cloud skills for free with Google Cloud
Step by step usage for AI Platform


How do I hook up a washing machine drain line to this box?

Question: I had a plumber come out and install a drain line and hook up the supply water for a washing machine. This is the state he left the project:

How am I supposed to hook up the waste line? Do I need to drill out that center hole?
Comment: Pretty installation behind wallboard.
Comment: @User58220 Per the [product info sheet](http://www.ipscorp.com/pdf/watertite/WT_SharkBite_Outlet_Boxes_sellsheet.pdf) there should be shut-offs in there, it looks like they're just not visible due to the angle of this photo.
Comment: Interesting box; I haven't seen that before. Is the intent to catch any potential leak from the hot and cold water connections, or is this just intended to permit pretty installation behind wallboard?
Comment: As a side issue, did the plumber install any shut-off valves on the hot and cold supplies, **upstream** of the connection points shown?
Comment: Hope he didn't melt the insulation off the wires in the conduit behind the water pipes. The copper and conduit should not be touching as they will corrode each other over time.
Comment: @keshlam The info sheet I linked above claims "raised drip guard contains and directs potential leaks down
the drain". No idea how well it actually works, though.
Comment: Just checked. They are not touching. Thanks for the advice.
Answer: It should be a knockout, meaning that a hard sharp blow will pop it out. The plumber should have done this before he glued the drain line in place, since knocking it out now could cause the plug to fall down the drain. This could lead to clogs in the future, since the trap is glued and cannot be disassembled.
Put the tip of a flathead screw driver on the knockout, and tap the back of the screwdriver with your hand or a hammer. Try to get it so that only part of the knockout breaks free. Then grab the loosened disk with a pair of pliers, and twist it free. Be very careful not to drop it down the drain.
Once the hole is open, simply hang the washing machines waste line in the hole. The washer should come with a piece of plastic used to make a hook in the waste line. Install that, and hang the waste line in the hole.
Comment: You can also cover the knockout with tape, with a wire or string under the tape.  This would allow you to retrieve the knockout if it falls into the drain.
Comment: The spec sheet for the box claims "Oversized KOs will not fall down drain". I'm not sure know how that actually works here though.
Comment: @AndrewMedico Yeah that certainly doesn't *look* oversized in this case. However that may have something to do with GuestPost's answer - the box appears to be upside-down, and the port on the bottom (now top) seems to be larger and could potentially have a larger KO. Just my best guess though.
Comment: Saved my bacon with this post. To keep it from falling in, I drove a wood screw into it and tied some twine to the top, and the other end to my thumb. Whacked edge with screwdriver, pried it out, done.
Answer: I would say that the box might be upside down, as the drip guard appears to be on the top. However, they are often designed to be used either way.
Nevertheless, yes, there should be a knockout. It is possible the plumber did not want the possibility of sewer gas coming back up while you wait to attach the washer, so s/he left the knockout in. It would have been better to remove the knockout and insert a plug that you could remove.
And I concur about the hope that there are shutoff valves above somewhere. Clearly the plumber used that space for air-hammer arrestors.
Comment: I would say it's two sided and not upside down. Just pop that plug and hang the hose there. Nice touch having the water hammer reducers installed. I have them on mine too.
Comment: You can just barely see the tip of the shutoff valve handle to the left of each open threaded connection.  They're integral to the fitting.
Comment: It's surely upside-down. You can have the water lines come in from the top or bottom, but only one side appears to have the "lip" to catch any water dips and guide them down the outlet pipe.
Answer: Let's try to simplify/clarify for someone reading this now.
A. The box is NOT upside down. There are identical KNOCKOUTS on top and bottom to accomodate water supply from above or below. The drain could have been on just the bottom side, but that's just the way they made it.
B. Several ways to remove knockout without it going down the drain. Knock in with screwdriver (as suggested), then pry up and grab with pliers. One could drill a coulple of holes and secure with zip tie or string, etc etc.
C. Clearly there are shutoff valves. I believe I see the red handle on left and blue on right. These are 90 deg ball valves.
D. The water hammer arrestors are NOT upside down and will work just fine. They can be installed "at any angle" per the mfgr website:
http://www.ipscorp.com/plumbing/watertite/protectivesystem/hammerarresters
They are mechanical - involvong an air filled bladder and spring, I believe.
E. Note that the trap is glued up. This should be fine as washer drains are inherently self-cleaning. (Yes the trap is there to block sewer gasses. It only works once it is filled with water.
** A footnote to those who have floor drains in basements/utility rooms. You need to pour a few cups of water into them once in a while. This will flush out the dust/dirt, but most importantly keep the water level up. Especially important in dry climates where the water can evaporate quite quickly.
Answer: The water hammer devices are designed to hold air to stop water hammer. Your valves are upside down and will not stop water hammer. If water hammer is not an issue you can either knock out the plastic or drill it. You should have removed the knockout prior to installing it since when you knock it out the part might fall into the drain blocking it. You installed an "S" trap that cannot be easily removed to clear the drain. PVC fittings are available to make it removable. It might be advisable to cut the existing pipe, instal a sweep "Y" with threaded cap for easy clean out then a removable "S" trap. Just make shure you leave enough of the PVC thatin the box to have enough room to make the splice. Remove the drain knockout before doing the drain pipe.
Comment: That's not an "S" trap, it's a "P" trap.
Answer: The plug is there to simplify pressure testing the drain line.  That is done when a new plumbing system is installed or amended (as for a remodel adding some plumbing) by inserting a pneumatic plug (or at Home Depot), inflating, and filling the system with water.

Once the plumbing inspector has verified the pipes maintain several minutes of steady water level (indicating no plumbing leaks), the system can be drained and then the knockout can be (ahem) knocked out.
I would use a sharp flatblade screwdriver and a hammer to punch the screwdriver piercing through the knockout and then pry it up.
Answer: If you were immediately hooking up a washing machine then the plumber might as well have knocked it out. If not then it is good he left it in to keep sewer gases from backing up into the house.
Comment: @mmathis if there is no water in the trap it won't keep gas out.
Comment: The trap at the bottom keeps sewer gases from backing up in to the house.


How to collapse one dataset to get incremental instances in a new dataset?

Question: I'm trying to collapse one dataframe that has the following unit of analysis: country-pta-yea into country-year. I tried group_by and summarise but it would sum up all the values instead of incrementally adding them as each observation of "value" is present for each PTA in different years. Below is the dataframe (df) I have and the dataframe I would like to achieve (df2).
What should I do next?
country <- c("USA","USA","USA","USA","USA","USA")
year <- c(2000,2001,2002,2000,2001,2002)
pta <- c("a","a","a","y","y","y")
value <- c(0,1,1,0,0,1)

df <- data.frame(country, year,pta, value)

country1 <- c("USA","USA","USA")
year1 <- c(2000,2001,2002)
value1 <- c(0,1,2)

df2 <- data.frame(country1,year1, value1)

Answer: It is a group by sum i.e. grouped by 'country', 'year', get the sum of value
library(dplyr)
df %>%
   group_by(country, year) %>%
   summarise(value = sum(value, na.rm = TRUE), .groups = 'drop')

Comment: @ThaiTeasy Basedon your dataset, if I check the 'y' value, then the output is not the same as expected output
Comment: Also, how do I ignore NAs when summarising? I see in some other post that I would have to use summarise_all(funs(),na.rm=TRUE). I'm not trying to summarise everything, is there a way to integrate na.rm=TRUE in this function?
Comment: @ThaiTeasy just specify `sum(value, na.rm = TRUE)` updated


Layout background messing on margin

Question: I'm trying to make a trimmerbar to my video player
trimmer_bar.xml
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:id="@+id/thumbsBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        tools:background="@color/trimmerBarSelected">

        <ImageView
            android:id="@+id/leftThumb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription=""
            android:scaleType="fitStart"
            android:src="@drawable/ic_left_thumb" />

        <ImageView
            android:id="@+id/rightThumb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:contentDescription=""
            android:scaleType="fitEnd"
            android:src="@drawable/ic_right_thumb" />

    </RelativeLayout>
    <ImageView
        android:id="@+id/progressIndicator"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="60dp"
        android:layout_marginTop="3dp"
        android:contentDescription=""
        android:scaleType="centerCrop"
        android:src="@android:drawable/btn_star_big_on" />

</FrameLayout>

activity_video_viewer:
 <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="#a8c71c"
        tools:context=".activities.VideoTrimmerActivity">

        <com.tomatedigital.instagram.longstories.ui.TrimmerBar
            android:id="@+id/trimmerBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/trimmerBarSelected"
            />
    </FrameLayout>

it's logic is working great: when the user touches, i detect if it was on the any of the thumbs and case on the left thumb I adjust the left margin of the thumbsBar, case on the right I adjust the right margin...
As the two imageview are aligned to the edges this behavior makes them to move... but what is actually moving is the whole RelativeLayout
The problem is even adjuting the margins and moving the imageviews the relative layout is still showing the background in the margin area
ignoring the whole calculation i set the margins using:
this.thumbsBar= (RelativeLayout) findViewById(R.id.thumbsBar);
this.thumbsBarLayout = (LayoutParams) this.thumbsBar.getLayoutParams();
this.thumbsBarLayout.leftMargin = this.leftMargin;
this.thumbsBarLayout.rightMargin = this.rightMargin;
this.thumbsBar.setLayoutParams(this.thumbsBarLayout);

===============================================================
UPDATE:
to make it easier to understand
I've this:

I should have:
Answer: com.tomatedigital.instagram.longstories.ui.TrimmerBar has the same background as your RelativeLayout and has a width of match_parent. You don't really specify how your layout is being loaded and I assume it is in your custom view.
For a test, change the color of the background of the custom view to see if the background you are seeing in the margins is coming from the RelativeLayout or the custom view. My guess is that it's coming from the custom view and changing the background color in the custom view will solve your problem.
Comment: you are right it's comming from the custom view.... i changed the color and the whole bar color changed, now i've the oposite problem: the blue color from the relativelayout background, it's supposed to be in between the thumbs... simple doesn't exist https://stackoverflow.com/questions/50358393/layout-background-color-disappears-on-runtime
Comment: @RafaelLima Did the answer about "tools" on the referenced question solved that problem? Looks like it should. "tools=" is just for design time and doesn't effect runtime.

Layout background messing on margin


gcc --version and package version is not the same

Question: When i enter following command in the terminal:
gcc --version

It's output something like this:
gcc (Ubuntu 6.5.0-2ubuntu1~18.04) 6.5.0 20181026
...

But when i enter below command to see version of the installed gcc package:
apt-cache show gcc | grep Version

I see this:
Version: 4:7.4.0-1ubuntu2.2
Version: 4:7.3.0-3ubuntu2.1
Version: 4:7.3.0-3ubuntu2

Is it normal?
Which version used by software that needs gcc?
Answer: gcc is installed on your Ubuntu (18.04, 18.10 or 19.04) as well gcc-6 and possibly some other gcc version(s). Although gcc is installed, gcc-6 is currently the default version of gcc. To show all the versions of gcc installed on your OS, run the following command:
apt policy gcc gcc-5 gcc-6 gcc-7 gcc-8 gcc-9

As you can see from the results of the above command, there are several different alternative versions of gcc in the default Ubuntu repositories, and multiple versions of gcc can be installed alongside each other. You can select which version of gcc to use if multiple versions are installed by following the instructions in How to use multiple instances of gcc?.
Comment: Although this probably is right, I don't see how in answers OPs question.
Comment: @SorenA After adding the last sentence, I'm explaining two things. 1. Why there are two different non-matching versions of gcc returned by `gcc --version` and `apt-cache show gcc | grep Version`. 2. How to choose which gcc version to use if multiple versions of gcc are installed.
Answer: /usr/bin/gcc is normally a symbolic link, and it normally points to the default current version of gcc for your system - which in your case appears to be gcc-7.4.0
If the link is pointing to a different version, that's likely because it has been linked manually using ln, or via the update-alternatives system.
Software doesn't "need" gcc at runtime - so it would only affect what version of the compiler is used when you build software from sources.
Comment: Yes, you'r right. There is no need for runtime purposes. I want to install cuda. As it refered [https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html]here, cuda needs gcc as a prerequisites.


Taking a photo results in an app crash with no error message

Question: As soon as I press the button to take a photo, the app crashes with no error message. The only log messages I get are as follows:
2016-02-17 23:29:47.773 OMC[254:4325] Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates.
2016-02-17 23:29:49.449 OMC[254:4325] Received memory warning.

I can post any relevant code, but I'm not sure what would be of use here.
Comment: have u manage camera permision off or on....!!!
Comment: @yagneshdobariya the camera permission is correct as this worked several days ago, but much has changed in the meantime
Comment: `Received memory warning` --> this error comes arrives in many sceanrios, like your app may be increase the more memory else your device has less memory space , in which device are you tried this
Comment: @Anbu.Karthik I was testing on an iPhone 4S when this happened.
Comment: for that first error see this link may be it helps you http://stackoverflow.com/questions/25884801/ios-8-snapshotting-a-view-that-has-not-been-rendered-results-in-an-empty-snapsho
Comment: I expected this answer , try once in iphone 5s (32 GB ) or iphone 6 (32 gb) or above
Comment: @Anbu.Karthik That appears to work, but how can I be sure that it will work on iPhone 4S / 5?
Comment: It would be just for memory constraint .... look into it
Answer: I am not sure it will work for you .
on your app
you are just using too much memory didReceiveMemoryWarning gets called , Check the Memory of each objects , Another cause is bad usage of memory. It is possible that you are creating objects and holding on to them with a strong reference for longer than you need to. Without seeing your code it's hard to tell where you are doing this. If you dont need the particular object release the memory manually like in ViewWillDisappear or in every time refresh.
on your Device
Clear the unwanted messages, songs or videos or else whatever you think like it is unwanted delete them and free up your device and try once , may be it helps.
Comment: I found a place where I could release a bunch of memory.Thanks for the help!


Sorting argv value by strcmp with a function

Question: I want to do it with my own function (I know that qsort would probably be a better option).
Here's what I've done:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void order(int count, char** strings);

int main(int argc, char** argv)
{
    int i = 0;
    for (i = 1; i < argc; i++)
    {
        printf("%s, ", argv[i]);
    }
    printf("\nAfter: \n");
    order(argc, argv);
    for (i = 1; i < argc; i++)
    {
        printf("%s, ", argv[i]);
    }

    getchar();
    return 0;
}

void order(int count, char** strings)
{
    char temp[50] = { 0 };
    int x = 0, y = 0;
    for (x = 1; x < count - 1; x++)
    {
        for (y = 0; y < count - x - 1; y++)
        {
            if (strcmp(strings[y], strings[y + 1]) > 1)
            {
                strcpy(temp, strings[y]);
                strcpy(strings[y], strings[y+1]);
                strcpy(strings[y+1], temp);
            }
        }

    }
}

It doesn't change anything in the array, I would appreciate any kind of help, thanks!
Comment: `strcpy(strings[y], strings[y+1]);` : They does not necessarily have the same size.
Comment: how strcmp can help you in sorting????, for you all the inputs will be of different length???
Comment: @piyushjaiswal: The behavior of `strcmp` with strings of different lengths is well defined, consistent, and usually regarded as 'correct'.
Comment: what have you done so far to try and debug  this? e.g. print out a list of things which are swapped in the innermost loop.
Comment: @RadLexus true, that's why i wanted to confirm the same, as its never mentioned in the question, that inputs will be of different length :)
Answer: You are using the result of strcmp wrong. According to its man pages, it

return an integer greater than, equal to, or less than 0, if the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2, respectively.

and so this line is wrong:
if (strcmp(strings[y], strings[y + 1]) > 1)

Compare against 0 to make it work.
Comment: Thank you so much! Can't believe I forgot how strcmp works.


Get the minimum of a function using numpy fmin within limits

Question: I need to constrained minimization of some data (ie so that I get the minimum value within a certain range). Currently I can only get the minimum over all of space. For example, if valid possible answers for the problem at hand are only in the range -5<=x<=5, then having fmin tell me the minimum of the function is at -10505 is useless. I need restrict the possible output to within the problem limits.
<code>        p = [0,0,0]
        fit_quad = lambda p,w: p[2]*w**2 + p[1]*w + p[0]
        errfunc = lambda p,l,w: fit_quad(p,w) - l
        fit, success = leastsq(errfunc, p, args=(y,x), maxfev=5000) #x and y are the input datasets
        #find the minimum tilt
        quad = lambda w,p: p[2]*w**2 + p[1]*w + p[0]
        min_tilt = fmin(quad, 0.0, args=([fit]))[0]
        #check for range violations
        if min_tilt < min_angle #the minimum on the quadratic can sometimes end up negative, especially if there are not enough good points
            min_tilt = 0.0
        elif min_tilt > max_angle: #if things are extremely tilted the minimum of the fit quadratic can end up unrealistically high. This pulls it back.
            min_tilt = max_angle
</code>
Note that just setting a simple check for above or below as in the above is not enough. I can end up on the wrong side of the range depending on the precise part of the function that is inside the range.
Answer: Use fmin_cobyla or fmin_slsqp.
Comment: A question: with eg `fmin_cobyla`, how do you define the constraint function if you want eg `10 < param < 100` instead of simple `param > 0`?
Comment: Define two constraint functions, one for `100 - param > 0` and one for `param - 10 > 0`.
Answer: your can filter your data:
<code>ll = np.array([100,20,-30,1,2,3,4,5])

min(np.array(filter(lambda x:-5 < x < 5, ll)))
</code>
Comment: The OP, needs a constrained minimization, this doesn't do that.
Comment: Whosh, seriously the question is by far to convoluted. The word constraint maximization is not mentioned.
Comment: Wasn't sure what the terminology was.


Resize Cursor - Col/Row vs East-West/North-South

Question: I have a website with 2 panels. The user can resize these two panel using drag-n-drop.
I want to change the mouse cursor, when the mouse is hovering over the edge of these two panels, to a Resize-Cursor.
However, I've noticed that there are two types of cursor icons for resize (for both vertical and horizontal).
Cursors East-West (aka ew) and North-South (aka ns):

Cursors Col and Row:

What is the difference between these two pairs of icons, and when should I use each one of them?
Answer: According to Microsoft Mouse and Pointers documentation,

Behaviours:
Behaviour 1
Dragging the edge increases the size of the two panels combined. The panels' size increases with some defined logic(usually the last panel size like End A or in a proportional way like End B).

Behaviour 2
Dragging a partition increases the size of the two panels combined.

Behaviour 3
Dragging a partition changes the sizes of the panels but the panels' combined size remains the same.
Answer: Both options are intuitive enough. I would choose first because it is simpler ("less visual noise"). Also second one is usually associated with spreadsheets, that's why the names are Col and Row.


Converting array to hash with empty params

Question: I have an array:
arr = ["dog", "cat", "eel"]

And I'd like to convert it into a JSON like so:
'{"dog": {}, "cat": {}, "eel": {} }'

I've tried using map like so:
arr.map{ |a| { a => {} } }

Then using .to_json, but it doesn't quite work.
Answer: I'd use each_with_object thusly:
h = arr.each_with_object({}) { |k,h| h[k] = { } }

then you can JSONifiy h as needed.
Answer: Alternative using Hash::[]:
arr = ["dog", "cat", "eel"]
Hash[arr.map { |key| [key,{}] }]
# => {"dog"=>{}, "cat"=>{}, "eel"=>{}}
puts JSON.dump(Hash[arr.map { |key| [key,{}] }])
# => {"dog":{},"cat":{},"eel":{}}

Comment: Ah, there it is.  If there wasn't an answer using `Hash[]`, I was going to add it.
Answer: in ruby 2.1.0
 a = [...]
 a.map{|k| [k,{}] }.to_h

Answer: Simple solution would be:
arr = [...]
hash = {}
arr.each {|k| hash[k] = {} }

Answer: arr = ["dog", "cat", "eel"]
@hash = {}

arr.collect{|a| @hash[a] ={}}

@hash.to_json
# "{\"dog\":{},\"cat\":{},\"eel\":{}}"

You are trying to initialize an empty hash to each element of array, to_json wont work like that
Answer: arr = ["dog", "cat", "eel"]

# For Hash
hash = arr.inject({}) {|h, element| h.update(element => {}) }
# => {"dog"=>{}, "cat"=>{}, "eel"=>{}}

# For JSON Hash
json_hash = arr.inject({}) {|h, element| h.update(element => {}) }.to_json
# => "{\"dog\":{},\"cat\":{},\"eel\":{}}"


SQL Server query for count per hour

Question: Using SQL Server 2014 - I am struggling with a query that would search/filter with 2 criteria (one of them is per hour). I have found various solutions that work separately but I have dificulties in joining them together as one.
I have
UserID, event1, timestamp

I would like to select: if the UserID has records 10 or more times in event1 column per hour for each hour (24hrs)
Comment: Here is a great place to start so we don't have to guess. http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/
Answer: Try this one:
SELECT UserID, COUNT(event1) as EventsPerHour, DATEPART(HH, timestamp) as Hour
FROM [TABLE]
GROUP BY UserID, DATEPART(HH, timestamp)
HAVING COUNT(event1) >= 10

EDIT
If your table contains data for more than 24 hours you probably want to specify the date you want to filter:
Only data from today:
SELECT UserID, COUNT(event1), DATEPART(HH, datetime)
FROM [TABLE]
WHERE DATEPART(HH, datetime) = DATEPART(DAY, getdate())
GROUP BY UserID, DATEPART(HH, datetime)
HAVING COUNT(event1) >= 10

Only data from the last 24 hours:
SELECT UserID, COUNT(event1), DATEPART(HH, datetime)
FROM [TABLE]
WHERE datetime between GETDATE() and DATEADD(HH, -24, GETDATE())
GROUP BY UserID, DATEPART(HH, datetime)
HAVING COUNT(event1) >= 10

Comment: This one returned some results, however 2nd and 3rd column has (No column name) as names, and I am not sure how to read through them.

the first row for example returns:

360642 14 13

that I assume would be - this id_Number has> 14events at>from13:00to13:59.59?
Comment: You are assuming correctly. the user with the ID 360642 has 14 events in the 13th hour.
Comment: Could I also ask if I am to do the same but for 5 events in 30 minutes stretch, should I do -> (DATEPART(HH, datetime)/2) or  (DATEPART(MI, Transaction_Time) /30), both queries return different results, I am unsure how to set the minutes value. Also the last column seems to be showing random numbers with HH and zeroes with MI? Any suggestions?
Comment: if you want the User with the most events on top of the resultlist just add ORDER BY COUNT(event1) DESC at the end of the query
Comment: For 5 events (per Hour) just adjust the HAVING part accordingly.
But (DATEPART(HH, datetime)/2) or (DATEPART(MI, Transaction_Time) /30) doesn't work the way you want it.
Comment: In my case the table holds only 24hr framed data. But this is really helpful for another occasion!
Comment: Try the query with ORDER BY UserID, DATEPART(HH, datetime) ASC so you will get a list sorted by UserID first and second by the hour they had more than 10 events.
Or leave out the HAVING part, so you can see all ervents evry User had per Hour (if the user has no event, there will be no entry for that user and that hour.)

SQL Server query for count per hour


sudo sh -c 'echo "deb http://archive.canonical.com/ubuntu trusty partner" >> /etc/apt/sources.list.d/canonical_partner.list' not woking

Question: I'm trying to skype on ubuntu 14.04, but when I type:
sudo sh -c 'echo "deb http://archive.canonical.com/ubuntu trusty partner" >> /etc/apt/sources.list.d/canonical_partner.list'

It says "Permission denied."
Please help, or tell me another way to get Skype.
Answer: The problem here has nothing to do with redirection, it's that you've copied curly quote characters. They are not the same as straight quotes (which the terminal understands as special characters) so the command does not mean the same thing at all.
This is largely the fault of the website you've copy-pasted the commands from (you should let them know).
To fix, simply replace the curly version with their straight counterparts:
sudo sh -c 'echo "deb http://archive.canonical.com/ubuntu trusty partner" >> /etc/apt/sources.list.d/canonical_partner.list'

Yes, tee might look nicer but there's nothing wrong with redirection.

There was some question about whether this really was the cause. It is, but I'll prove it. The redirect in the original command is being interpreted first. Bash attempts to open a write handle (as the current user) on the output file first and fails.
$ sudo afoijaf2 > /rawr
-bash: /rawr: Permission denied

That's why we don't see a command not found. afoijaf2 here is clearly non-existent and 'echo is also clearly an invalid command. Neither are being executed —sudo hasn't even run— because Bash failed to get a write handle. That errors out first.
Comment: More importantly, enabling the Canonical repositories can be done using the Software Sources GUI. In fact the entire process of installing Skype can be done via GUI. Why use a command line method, which you don't understand and may end up with you borking the system, when an easy alternative exists?
Answer: You can not redirect with sudo, use tee
echo foo | sudo tee -a file

There are other ways as well
Comment: You *can* redirect with `sudo`. `sudo sh -c 'foo >> file'` is a perfectly valid way of doing it... Provided you use the right quote characters.
Comment: That works, but technically you are running a root shell (sudo sh) and re-directing within the root shell. `sudo foo >> file` does not work.
Answer: Install Skype with GUI
for Skype you should go to download_skype, you probably need
multiarch_version
but I can't know that in advanced. It is something based on your ubuntu version.
Long story short when the .deb file is down on your system , open and install
with ubuntu software center and basically that was it !

sudo sh -c ‘echo “deb http://archive.canonical.com/ubuntu trusty partner” >> /etc/apt/sources.list.d/canonical_partner.list’ not woking


Did I install this motion detecting light switch correctly?

Question: It works, I just want to make sure I did it correctly. It's a Leviton ODS10-ID Decora 120/277-Volt Wall Switch with Occupancy Sensor
When I took the original switch off the wall it had no ground connected and a red and black wire going to it.
I installed the green ground wire from the switch into the existing 3 bare copper wires that were in a yellow wire nut which I upgraded to a red since I was now adding a 4th wire. One bare wire connected to the metal box and the other two go into the wall.
I attached the black hot from the new switch into the black wire in the wall that was connected to the old switch. I attached the blue wire from the new switch to the red wire that was attached to the old switch.
Comment: If you have a metal box which is grounded, a switch can self-ground via the mounting screws, provided the yoke (the screws go through) and the screws are metal.  So in this case there is no requirement to use the ground wire also.   This method does not work on receptacles unless they make hard-flush contact with the metal box.
Answer: Looks good. If you were concerned about the "red" .vs. "black" on your load wiring, don't be. Generic instructions often don't do well in specific cases.


Add view between 2 rows Gridview

Question: I have a GridView, with 3 elements per row, and when I click on an item, a new view comes below the row. It's a bit like a folder application on iOS. I didn't find any answer on SO or on Google. Maybe you can give me some hints.
Comment: The image you posted is exactly what you want?
Comment: More or less. When I click on an thumb, I want the view to open and show the details actually :)
Comment: Yes, but do you want the same appearance like in the image, basically of a new row(with an indicator of the actual clicked item)?
Comment: why do not you try [ExpandableListView](http://androidtrainningcenter.blogspot.in/2012/07/android-expandable-listview-simple.html). and Customize its click events
Comment: It's actually an ExpendableGridView that I'd need :/
Answer: You can do this easily with GridLayout but not with GridView.
To find out the available width of the grid before you place your items and set the number of columns, either set a ViewTreeObserver.OnGlobalLayoutListener (which can then place your items) or extend GridLayout and override onMeasure (int widthMeasureSpec, int heightMeasureSpec).
Insert a row after every row of content and set it's visibility to Visibility.GONE and it's columnSpec to the number of columns of your GridLayout. When the user taps an item, you can get it's info, populate the view under it and expand or animate it's visibility toggling.
Finally, for the indicator, I would just add it as a child of the hidden row and, when a user taps the item, calculate the horizontal center of said item and exactly place this view's center on the X axis to that coordinate (margins would be OK for this).
Please note that for very large lists of items this is not recommended as you'll have to instantiate every item to display immediately, regardless if they all fit on the screen or not. Unlike GridView, GridLayout is not a child of AbsListView.
Comment: Can you add sample Code for this?
Answer: I use TableLayout.addView to add an ImageView, it might need another variable to removeView, currently I just remove it and add another one when button been click.
I change the imageView by their position which you can base on that to change the background so the user will assume it related to the one they click
ImageView imag;
boolean imageOn = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imag = new ImageView(this);
    final TableLayout table = (TableLayout) findViewById( R.id.tableLayoutCategoryButtons );
    int buttonsInRow = 3;
    String[] itemNames = getResources().getStringArray(R.array.categories_array);

    int numRows=(itemNames.length/buttonsInRow);
    if (itemNames.length%buttonsInRow!=0)
        numRows++;

    Button[] buttons = new Button[itemNames.length];
    LinearLayout[] tablerowLayout = new LinearLayout[numRows];
    tablerowLayout[0] = new LinearLayout(table.getContext());
    int rowcount=0;
    for (int i=0; i<itemNames.length; i++){
        buttons[i]= new Button(table.getContext(), null, android.R.attr.buttonStyleSmall);
        buttons[i].setText(itemNames[i]);
        buttons[i].setId(i);
        buttons[i].setTextColor(Color.BLACK);
        buttons[i].setVisibility(View.VISIBLE);
        buttons[i].setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                if(imageOn){
                    table.removeView(imag);
                    imageOn = false;
                }
                int index = v.getId()/buttonsInRow+1;
                if(v.getId()%buttonsInRow==1)
                    imag.setImageResource(R.drawable.reta);
                else if(v.getId()%buttonsInRow==2)
                    imag.setImageResource(R.drawable.reta2);
                else
                    imag.setImageResource(R.drawable.reta3);

                imageOn = true;
                table.addView(imag, index);

            }});

        LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        tablerowLayout[rowcount].addView(buttons[i], buttonLayoutParams);

        if (((i+1)%buttonsInRow==0)&&(i!=0)){

            table.addView(tablerowLayout[rowcount++]);
            if(rowcount<numRows)
                tablerowLayout[rowcount] = new LinearLayout(table.getContext());
        }
    }
    if(rowcount<numRows)
        table.addView(tablerowLayout[rowcount]);

Comment: No way to do the same with a GridView?
Comment: No, I don't how to do that.
Comment: @QuentinDOMMERC : Were you able to achieve the same using gridView? Please help if You figured it.
Answer: Although obviously there's no native component to accomplish what you want to do here, there's several ways to get the effect you want by combining other methods.
One way i can think of is by creating your own Adapter and add the functionality to insert 3 more elements below the row clicked tagged with some kind of enum so you can differentiate it from the regular view, of course at the getView method of the Adapter, you will have to do the validation to know which view to inflate and return, after refreshing the view those 3 elements will be inserted below the clicked element and of course you can get rid of them by modifying the list the adapter is displaying. (This approach requires quite good knowledge of custom adapters, i've done something like this and is a clean and good approach).
Another approach to this issue which is not as good as the first one however would absolutely do the trick is by, creating kind of a "Template" of the Effect that you want to get (like the one in the picture you have), keep that template as part of the activity on top of your grid view invisible, once someone taps on a element, fill the template accordingly to the info you want to show, make the grid invisible and bring the "template" visible on top of the grid, with the info that you want to show properly filled, the user wouldn't notice the change and when you want to go back to the grid view, just remove this "template" view and it will do the effect of having the grid the way it originally was.
Hope this helps.
Regards!

Add view between 2 rows Gridview


Can we always define the projection in a ball of raius $R$ for any Polish metric space $X$?

Question: I'm generalizing some theorems to Polish metric spaces, which were originally proved for $\mathbb R^n$. Hence, as I'm adapting the proofs, I'm checking whether where I can reuse the same arguments. In one of my proofs, I had the following:
"Define $\pi_R : \mathbb R^n \to B(R)$ to be the projection operator on the closed ball with radius $R$ and centered at zero".
Now I'd like to use this for an $X$ metric Polish space. Can I "safely" assume that there exists such projection operator $\pi_R: X \to B(R)$ such that the closed ball is centered at some
$x_0 \in X$? How can I know that this map is well defined?
Comment: Sorry, you mean the argmin, right? Surely your projection isn't real valued!
Comment: There are Polish spaces $X$, $x\in X$ and $r>0$ such that there is *no* continuous retraction of $X$ on the closed ball of radius $r$ around $x$ regardless of how you define them
Comment: When you say a "projection", what do you mean? Are you talking about a metric projection?
Comment: I mean $\pi_R(y):= arg\min_{x \in B(R)} d(x,y)$ for the Euclidean space with the ball centered at 0.
Comment: Yeah, sorry I was fixing it.
Comment: @AlessandroCodenotti, I see, so perhaps I cannot use the argument with the closed ball.
Comment: You can retract $X$ on $B_r(x)$ whenever $B_r(x)$ embeds as a convex subspace in a locally convex metrizable topological vector space, which is not a good criterion to work with, but it gives some more Polish spaces
Answer: The answer is "no". Consider the separable real Banach space $\ell^2$. Any closed subspace of $\ell^2$ is Polish, a fact we shall soon use.
Let $e_n$ be the $n$th basis vector, i.e. $e_n$ is the sequence such that the $n$th entry in the sequence is $1$, while the other entries are $0$. Let
$$C = \left\{\frac{1 + \frac{1}{n}}{4}e_{n+1} : n \ge 1\right\}$$
and
$$X = C \cup \{2e_1\}.$$
Note that every point in $X$ is isolated, and hence $X \subseteq \ell^2$ is closed, and hence a Polish space in its own right. If we have distinct $\frac{n + 1}{2n} e_n$ and $\frac{m + 1}{2m} e_m$ in $C$, then
$$\left\|\frac{n + 1}{4n} e_n - \frac{m + 1}{4m} e_m\right\|^2 = \left(\frac{n + 1}{4n}\right)^2 + \left(\frac{m + 1}{4m}\right)^2 \le \frac{1}{2} + \frac{1}{2} = 1,$$
but
$$\left\|\frac{n + 1}{4n} e_n - 2e_1\right\|^2 = \left(\frac{n + 1}{4n}\right)^2 + 4 \ge 4.$$
Therefore, $C$ is the closed unit ball in $X$, centred at any point in $C$. We can now show that $2e_1$ has no closest point, i.e. the projection map simply does not extend to this point in $X$. We see that
$$\left\|\frac{n + 1}{4n} e_n - 2e_1\right\|^2 = \left(\frac{n + 1}{4n}\right)^2 + 4  \to \frac{17}{4},$$
while remaining strictly greater than $\frac{17}{4}$ for every $n \ge 2$. Therefore, there is no point in $C$ that achieves the infimal distance of $\frac{\sqrt{17}}{2}$ to any unit ball centred in $C$.
Comment: Did you mean to write $X=C\cup\{2e_1\}$? Because $2e_1$ is not in $X$ as written
Comment: @AlessandroCodenotti I did, thanks.


Which strategy best ensures survival?

Question:
Possible Duplicate:
How do I keep up with the power curve?

So, currently I've only managed to get a high score of 1200. I tend to play in my lunchbreak as most games only last about 25 minutes.
I have tried to race through the game, avoiding conflict where I can and this proved to be effective to get me 6 sectors in before I died to an uncontrollable blaze, systems outage, solar flares and a 5 man mantis boarding party.
What ground rules and strategies are suggested to increase the chances of your ship surviving the first, let's say 10 sectors?
Should I upgrade my shields and engines as a priority? Focus on stocking up scrap to buy new weapons? Or save up all my scrap to just spend on hull repairs and new crew?
I'm focused on staying alive, so I can see the later parts of the game.
Comment: This question seems very similar to http://gaming.stackexchange.com/questions/83387/how-do-i-keep-up-with-the-power-curve
Comment: I'm pretty sure the game is only ten sectors long...
Answer: Are you playing Easy or Normal?  The advice won't change much, but be aware that "easy" difficulty is actually quite tough and normal is very difficult.
Your first problem lies in "avoiding conflict".  You must maximize the amount of scrap you take in.  It's worth pushing it to get every last piece.  On easy there's a certain buffer you have that you won't on normal, but even there you are looking to collect scrap at every opportunity.  Fight everything you can.  Fight when you get a chance to run unless you are near dead.  If someone offers to surrender, you'll have to do your own calculations.  Surrendering generally gives more consumeables (fuel, missiles, drone parts) than scrap; destroying an enemy gives more scrap and less of the other stuff.  You need to think in terms of maximizing your scrap intake.  Hit as many planets in a sector as possible and fight as much as you can.
You must also walk a fine line. You do want to horde scrap, but you need to spend some scrap to help in the early going.  Generally, you spend early scrap where it's most cost-effective.
Early upgrades:
Engine Upgrades: generally speaking, you want to upgrade your engines quickly.  Engine upgrades snowball; each engine upgrade increases dodge by 5% (up to a breakpoint at like 6 levels of engines).  Your pilot and engines crew can skill up whenever your ship dodges.  Once they gain a level, your dodge chance goes up, and so on and so forth.  Engine upgrades are cheap.  At the start of the game 1 level of engine upgrades (and the reactor upgrade to power it) is easily less than half the cost to add 1 point of shielding.  The first couple of engine upgrades are some of the best scrap you will spend.  I get 1 very quickly, and usually have 3-4 by the end of sector 2 at the latest.  Dodge is the only defense against ballistic (missiles, bombs) weaponry, and is also useful against regular energy weapons (which are the most common type of weapon).  Useless against beams, though.
Weapons: if you can find a weapon, upgrading your offensive capabilities is an excellent idea.  I like to hold scrap in reserve for this possibility.  The next store might have a Blaster Mk I or II, and these are typically must-buy for me.  Always be on the lookout for more weapons.  Weapon upgrades get expensive fast.  Most of your scrap saving is about hoping for weapon upgrades, or saving for things like drone control/crew teleporter.  As to what to look for, Blasters Mk I and II are exceptional items (being very efficient from a power/system standpoint, requiring 2 weapons/power each).  Small Bombs, Ion Bombs, and Artemis Missiles all require 1/1/ (system upgrade/power) but do at least 2 damage (Ion Bombs do 4 ion damage).
Shields: You can ignore these at first.  Shield upgrades are great- they're the only beam defense, remember, and they're really helpful in asteroid fields.  However it's a pricey upgrade.  I won't touch this until I have at least 4 points of engines, typically.  And I usually don't get a third point of shields until late (that upgrade is likely to cost 150-160+ scrap in total).
Systems: Both the crew teleporter and the drone control give you a lot of flexibility.  You'll need to find drones and crew-entities to use with them, of course (drone control always comes with one drone though).  These upgrades cannot help you out that much if purchased early.  Note, they are very common, so you don't need to worry about passing on them early.  By the end of sector 2 I'm saving scrap to get one or the other, if not both.  Note that the teleporter, once you can use two decent crew in tandem, will really maximize scrap gains.  Capturing ships gives the best rewards.
Augments: I consider automated re-loader a must buy (pre-igniter as well, but it's super expensive).  However, augments generally only help in the long term.  Still, I will alter early game plans to buy a choice one (I'll get a scrap arm as well; if you plan on going drone heavy a drone arm is nice.  I usually avoid the repair arm).
Crew: adding crew can be helpful.  If you start with under 4, you should get to 4 asap to work the "primary" systems (pilot, weapons, shields, engines).  If you want to use teleporters, keep an eye out for more.  Mantis and Rocks are the best "combat" crew (Mantis do extra damage, Rocks have 150 hp).  Note that when you fight slavers, they will typically offer you a slave to let them live.  This can be an excellent way to pick up crew early.  Consider the cost benefits; the cheapest crew is a human at 40 scrap, iirc. The most expensive cost 65 scrap, and it's not common to find them at stores.  In the first sector, killing a ship probably nets you under 40 scrap.  So if a slaver offers, take the deal (even if it feels a little icky)!
Sub systems: do not neglect your doors!  If you start with doors 1, the first upgrade is 20 or 25 scrap.  I don't do it on sector 1 but I usually get it in sector 2.  This is a huge help in controlling fires and dealing with boarders.  I don't always get the third point, and when I do it's usually late.  Sensors 2 can be useful in some circumstances.  Doors upgrades are great though.

Which strategy best ensures survival?


Does soul collection conflict with item collection?

Question: I was farming in The King's Passage using the Jester's Hat and the Covetous Gold Serpent Ring +1, but at the same time I had the Jester's Gloves and the Covetous Silver Serpent's Ring +2 on as well to boost my soul collection. I was also consuming Rusted Coins with every run to help boost the item find rate.
After all 7 runs (the enemies had stopped spawning) all I had found was one Stone Parma and a set of Llewelyn Leggings. That's pretty terrible considering the last few times I ran through there I managed to get at least 4 shields, 2 armour sets, 2 stone twin blades and 3 titanite slabs.
Is it possible that my soul farming gear was interfering with my item farming gear?
Comment: I don't think so. Kings passage is kind of a crappy place to farm IMO. What were you trying to get?
Comment: Whatever was available. Mainly the Llewelyn set. But like I said, my latest attempt was a very big contrast from previous attempts.
Comment: I have read rumors where sometimes drop rate is actually lowered when stacking jester, gold serpent ring, and rusted coins.
Answer: From my experience, no I don't think so.
I used to farm Desert Sorceress Top (you know how popular that thing is). If stories from Reddit is to be believed, some people experienced extreme trouble in obtaining it, I got one when I was wearing both Silver Serpent and Gold Serpent. In practice I pretty much never take off the soul farming ring, and I only wear my item farming ring when I'm trying to farm, got quite a few good items that way
Most probably, you're just being extremely unlucky


Failed to bind to port

Question: So I want to start a small Minecraft server to raise money toward a bigger one, so I download a Spigot server (and I have owned some servers in the past so I knew how to set it up). When I finish setting up port forwarding and all that crap, then when I start it up it says this:
**** FAILED TO BIND PORT!

So I went online to find how to fix it and I was met with a number of different methods. I tried changing the port, changing the IP, using the cmd, using task manager, closing Java, and then started it back up. I was met with the same message. I tried to fix again, but it still gave me the error.
Comment: Showing your IP is not wise. You should be careful to censor it in the future.
Comment: No that didn't help. The ip feild is filled and the other tasks running on the same port are closed. Thanks tho
Comment: Yes thank you. I caught that right after i posted it. And i could not figure out how to change it. thank you for doing so
Answer: If you are running your server in your private (home) network, be sure that the server IP is the local IP of your computer/server in your network not the one who is accessible from public.
You can check if your current IP is a local one:
10.0.0.0 to 10.255.255.255
172.16.0.0 to 172.31.255.255
192.168.0.0 to 192.168.255.255

If your current IP in server.properties is included in above ranges, there you go.
As Aidan Mueller mentionend, left it blank will automatically take your local IP.
Comment: Yes! Thank you that worked! One more question. Where do i find the ip to share it w/ friends when i leave it blank? Is it the ipv4 address?
Comment: If i type in the ipv4 nothing comes up except: **_java.net.ConnectExeption: connection timed out: No further information_**
Answer: IP
I'm not sure if you ever need to fill the IP field. I have always left it blank, so try that first.
Port
A BindException is usually caused by a port being in use. It looks like another program may be using that port. This question has information on checking for open ports. That should help you find an open port. One answer says that this command will show you ports that are in use:
netstat -a -b

Comment: It said The requested operation requires elevation. What does that mean?
Comment: @CanColsto You need to move the computer a bit higher for it to work. Put some books under it :P. OK, seriously. It means that the command needs to be run as administrator. Start the command prompt as administrator first.
Comment: thaink you. And for the record. I do have books under my pc tower XD
Comment: @CanColsto If my answer fixed the problem, don't forget to accept.
Comment: Ok i went through a few times but i dont see anything that has _**25565**_ on it. What now?

Failed to bind to port


Copper pipe identification using electrical current

Question: My HVAC contractor installed two linesets, one from my basement apartment, one from the main unit, both going to the roof where the air condensers are. The problem is, he did it over several days and I have a suspicion that he messed up which pipe/wire goes where, i.e. that he mixed them.  He claims that he marked it along the way but I am skeptical.  Both linesets (fat and skinny flex copper, power supply, and thermostat) enter the roof through lead cones.  It is not possible to trace the pipes along the way because most of their way is now blocked to sight.  Only the linesets have been installed thus far, so there is no air handler/condensers installed on their end, so the pipes are empty.
Is it possible to use a small amount of current (from a battery?) and send it on one end of the pipe while checking it with a multimeter or some voltage detector on the other end?  If yes, how should I rig up such a contraption?  Can I just wire the battery onto the pipe?
Comment: Have you tried tapping the end of the pipe with something like the blade of a screwdriver? At the other end hold your ear to each pipe. Should be louder on the one being tapped if they don't connect. Since they're not connected yet.. would it be safe to pour some water down into one and see where it comes out? Or would that potentially cause issues with the refrigerant later?
Answer: Put an earbud from your cell phone or iPod in one of the tubes. Crank up some music. Put your ear to the other end. You will absolutely be able to tell the difference between the one with the earbud in it and the other three.
Answer: They are pipes, even though it will be frowned upon by HVAC personel, get an air compressor and hook up to the pipe and see which one produces air at the other end. In my opinion it is better to endure a little air born moisture in the pipe, than have them crossed up. This may be my naivety showing, but the lines are purged before pressurizing with the refrigerant.
The wires are no problem, they will sort that out on their connecting. A multimeter or other specialized testing  tool that they have can determine what goes where. Please pardon my highly advanced technical vocabulary on the name for the equipment.
Comment: A Cat-5 *tone tracer* might work.
Answer: Simply use air blower from one end and check air is coming out in another end. Recently I have used this method for copper pipe checking. If connections are made then use only and only one method that's to check continuity with clamp meter. Hope you get the answer.
Answer: If pipes are touching at any point it won't work. If they aren't touching, I would use an extension cord connected to one end of pipe (tape a piece of wire to the pipe) and a ohm meter in between pipe and extension cord at other end. Test for resistance and you don't have to use any external electrical source.
Comment: If they weren't touching i would use an extension cord connected to one end of pipe(stick piece of wire into socket) and a ohm meter in between pipe and extension cord at other. Test for resistance
Answer: Electricity
I assume you are in the US, where different rules may apply. In the UK, all copper piping would be electrically bonded together (equipotential bonding) for safety. This can occur at multiple places in the pipe run. It's also possible (though unusual) to use plastic push-fit joints on copper pipe. This means you can't reliably use simple electrical means to check copper piping continuity.
Water
If the pipes are intended to carry water (working fluid for an AC unit), maybe you could pour some in at the top and see which carefully positioned bucket at the bottom starts to fill.
Answer: If you can light up a bulb with a battery, you should be able to use this approach (assuming the two runs of pipe never touch).  Attach one side of a low voltage battery (e.g., 1.5, 6, or 9 v) at the bottom and string a long wire up to the top of the two pipes, and use a little light bulb or a VOM to see which pipe is energized.


Not getting any results

Question: I am trying to write code to find the length of a string, and to return "invalid entry" when an integer is entered.
def length_of_string(mystring):
    if type(mystring) == int:
        return "invalid entry"
    else:
        mystring = input("enter the string ")
        return len(mystring)

When I try to execute this function it doesn't give me an error, nor does it produce any solution.
Comment: How do you call that funcion from `main()`?
Comment: First, are you printing the results? Second, why pass one string and then input another one?
Comment: Why would the type of a string ever be an int? A string is a string, not an int.
Answer: You should move out mystring = input("enter the string ") from else and call the function from main or other place.
def length_of_string(mystring):
    if type(mystring) is int:
        return "invalid entry"
    else:
        return len(mystring)

mystring = input("enter the string ")
print(length_of_string(mystring))

Answer: If you want the string to be always requested from the user:
def length_of_string():
    mystring = input("enter the string ")
    try:
        int(mystring)
        return "invalid entry"
    except ValueError:
        return len(mystring)

print(length_of_string())

If you want to use the function with a parameter:
def length_of_string(mystring):
    try:
        int(mystring)
        return "invalid entry"
    except ValueError:
        return len(mystring)

print(length_of_string("a string")) # prints 8
print(length_of_string(1))          # prints invalid entry
print(length_of_string(input("enter the string "))) # prints [input length]

Answer: The problem is that you have not called the function.  Functions (similar to classes) do not run until you execute them.
Calling them is easy.  You just have to call the function name.  You also have to pass the necessary parameters to the function (here it is mystring).
length_of_string('Hello World')

To get what is returned you will need to pass it to a variable or print it/perform some other action.
print(length_of_string('Hello World'))

Also if type(mystring) == int: will not work input() is always a string.  The thing to do is to test it and see if it can be made into an integer:
try:
    int(mystring)
    return "invalid entry"
except ValueError:
    mystring = input("enter the string ")
    return len(mystring)

Entire code:
def length_of_string(mystring):
    try:
        int(mystring)
        return "invalid entry"
    except ValueError:
        mystring = input("enter the string ")
        return len(mystring)
print(length_of_string('Hello World'))

Comment: I tried running that code but that gives me a error message

PS C:\Users\ayudr\Desktop\python> python .\exercise3.py
  File ".\exercise3.py", line 2
    return "invalid entry"
    ^
SyntaxError: 'return' outside function
PS C:\Users\ayudr\Desktop\python> python .\exercise3.py
  File ".\exercise3.py", line 4
    return len(mystring)
Comment: @steffinissac  I added the complete code.  Try it again, there was no error for me.
Answer: If you pass a string by parameter, it does not make sense to overwrite it again.
I think the solution is:
def length_of_string(mystring):
    if (isinstance(mystring, str)):
        print "Length of the string: ", len(mystring)
    else:
        print "Type invalid"

Comment: how do i define a statement where it can check for the interger value and return a invlid entry message

Not getting any results


Python Beautifulsoup decompose removing elemets out of element

Question: I got a DB of files from theguardian.com. I need to reduce these files to only text and remove all Ads and other text. I am able to get the main text but when I try to remove the bottom element ("div", attrs={"class": "submeta"}) it deletes the whole text, but the text is not part of this element.
Input file
# Decomposing
for remove1 in soup.select("figure", attrs={"class": "element-atom"}):
    remove1.decompose()
for remove2 in soup.select("aside", attrs={"data-component": "rich-link"}):
    remove2.decompose()
for remove3 in soup.select("div", attrs={"class": "submeta"}):
    remove3.decompose()

# Extraction of text
textHeadline = soup.find("h1", attrs={"class": "content__headline"})
textUnderline = soup.find("div", attrs={"class": "tonal__standfirst"})
textBody = soup.find("div", attrs={"class": "content__article-body from-content-api js-article__body"})

# Final text
reductionResult = str(textHeadline) + str(textUnderline) + str(textBody)

Thank you for any help.
Answer: Use .find_all() instead of .select() to select elements to decompose. .select() is used only with CSS selectors:
for remove1 in soup.find_all("figure", attrs={"class": "element-atom"}):
    remove1.decompose()
for remove2 in soup.find_all("aside", attrs={"data-component": "rich-link"}):
    remove2.decompose()
for remove3 in soup.find_all("div", attrs={"class": "submeta"}):
    remove3.decompose()

textHeadline = soup.find("h1", attrs={"class": "content__headline"})
textUnderline = soup.find("div", attrs={"class": "tonal__standfirst"})
textBody = soup.find("div", attrs={"class": "content__article-body from-content-api js-article__body"})

# Final text
reductionResult = str(textHeadline) + str(textUnderline) + str(textBody)
print(reductionResult)

Prints:

'Clear discrimination': South Sudanese react to exclusion from migration program

...and so on.