text:
Q: Question about multi-tenant application design/architecture I'm making an app that uses Apartment for multi-tenancy and Devise for user authentication.
Initially, an instance of Tenant would be created, then would redirect to subdomain.lvh.me/users/sign_up so a user can sign up and only be a part of the schema for that particular subdomain. This way users are only authorized to login on the subdomain that they initially signed up on, which is what I want. It was also beneficial because I set every User with id=1 to admin, so every time a new tenant is created, it redirects to the subdomain and the first user to sign up would be the default admin (made sense because user would start on landing page, create company account (tenant), and then create a User account with their name, email, password etc right after and they would be the first user associated with that tenant and therefore be the default admin.
This worked well because the person coming from the landing page (imagine the head of a team - director of marketing or whatever) could sign up for the product and set the company information as well as be the first user with administrator capabilities. Every employee on the team would sign up on the subdomain and wouldn't be authorized to login on another subdomain, or they would have to sign up on the landing page in which case they would be treated like a new company is signing up and not just a user.
Recently I implemented nested attributes so that I could have the initial sign-up process completed in one form/view only instead of two. The problem is because the instance of User is being created in the Tenant controller, it is not a part of the schema for the company subdomain and therefore cannot login on subdomain.lvh.me/users/sign_in.
I'm wondering if anyone has run into this challenge before and what your solution was. Would it be better to change it back to how it was originally, creating Tenant first, redirecting to subdomain/sign_up and then creating the first User?
Sorry if I didn't articulate this as well as I could have.
I've tried redirecting to the sub-domain before calling @tenant.users.build but it didn't work like I thought.
part of tenants_controller.rb
def new
    @tenant = Tenant.new
    @tenant.users.build
    render layout: false
end

def create
    @tenant = Tenant.new(tenant_params)
    @tenant.update_attribute :subdomain, @tenant.company.downcase
    respond_to do |format|
      if @tenant.save
        format.html { redirect_to "http://#{@tenant.subdomain}.lvh.me:3000/users/sign_in", notice: 'Domain was successfully created.' }
        #format.html { redirect_to new_user_registration_path, notice: 'Tenant was successfully created.' }
        format.json { render :show, status: :created, location: @tenant }
      else
        format.html { render :new }
        format.json { render json: @tenant.errors, status: :unprocessable_entity }
      end
   end
end

A: I'm not sure how your app and apartment is configured.
I had it set up that a tenant (in my case workspace) belongs to an owner (its class is User). Here is an excerpt.
controllers/workspace_controller.rb
class WorkspacesController < ApplicationController
  def new
    @workspace = Workspace.new
    @workspace.build_owner
  end

  def create
    @workspace = Workspace.new(workspace_params)
    respond_to do |format|
      if @workspace.valid?
        Apartment::Tenant.create(@workspace.subdomain)
        Apartment::Tenant.switch(@workspace.subdomain) do
          @workspace.save
        end
        format.html { redirect_to new_user_session_url(subdomain: @workspace.subdomain), notice: t("flash.controllers.#{controller_name}.#{action_name}.success") }
      else
        format.html { render :new }
      end
    end
  end
end

models/workspace.rb
class Workspace < ApplicationRecord
  belongs_to :owner, class_name: 'User', required: true
  accepts_nested_attributes_for :owner
end

The form is built with workspace and owner fields. If validation passes a new schema is created with Apartment::Tenant.create(@workspace.subdomain). Then we wrap the actual creation of the tenant in the Apartment switch Apartment::Tenant.switch(@workspace.subdomain) do …
Everything in that block will be saved in the schema subdomain except whatever you have assigned to config.excluded_models in your Apartment config. In my case the user gets saved into 'subdomain'.'users' and the workspace into public.'workspaces'.
Don't hardcode your redirect destination. You can pass the subdomain to the url-helper.


text:
Q: How to lock Windows 7 with second screen displaying actual desktop? I have special PC for testing purposes, it has two screens: one (main) for displaying virtual machines which operate tests, another (2nd) for graphs.
I'd like the second one to be always on (should always display graphs), even when I go away and lock my PC.
Is it even possible?
P.S.: there could be another problem, mozilla browser (which is used to display graphs) stops refreshing when PC is locked.

A: It's not possible to keep one screen unlocked in this way. Windows basically swaps your visable desktop with a different one when the machine is locked.
You may be able to display the graphs using a screensaver, however.

A: I have started to use 3rd party software to lock keyboard & mouse with password.
In my case it is Kid-Key-Lock, I was choosing between several software but this is one that uses password (whatever you want to set) for locking.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does root not have /usr/local in path? I've noticed that the default path for root on my of my vm's and servers do not include /usr/local/bin
sudo -s
echo $PATH
/sbin:/bin:/usr/sbin:/usr/bin

Whereas normal users on the server do have /usr/local/bin
/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/sowen/bin

Why would root not need /usr/local in the path?
Where is the default path for a user defined?

A: Because it isn't set up in the relevant shell startup files for root.
Traditionally, /usr/local has been used for unofficial, locally installed software (often to override buggy/broken/limited "official" versions; a friend quipped that the first step when a new Sun arrived was GNU > /usr/local). As root is all-powerful, any mistake or misdesign in the programs it runs can be fatal. It stands to reason that running e.g. a local, experimental version of make by root should be treated with caution. Better have it go the extra step of giving an explicit path.


text:
Q: Eclipse Link using wrong field mapping in InheritanceType.JOINED inherited classes I have an Animal class which is extended by two classes:
@XmlRootElement
@Entity
@Table(name="class_animal")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING,length=31)
@DiscriminatorValue("animal")
@Cacheable
@Cache(coordinationType=CacheCoordinationType.INVALIDATE_CHANGED_OBJECTS, alwaysRefresh=true, expiry=300)
public class Animal {
    @Id @Column(name="uuid")        private String id;
    @Column(name="owner")           private String owner;
    @Column(name="name")            private String name;
    @Column(name="type")            private String type;
}

The Cat class extending Animal
@Entity
@Table(name="class_animal_cat")
@Cacheable
@Cache(coordinationType=CacheCoordinationType.INVALIDATE_CHANGED_OBJECTS, alwaysRefresh=true, expiry=300)
@DiscriminatorValue("cat")
public class Cat extends Animal {
    // ...
}

The Mouse class, extending the Animal
@Entity
@Table(name="class_animal_mouse")
@Cacheable
@Cache(coordinationType=CacheCoordinationType.INVALIDATE_CHANGED_OBJECTS, alwaysRefresh=true, expiry=300)
@DiscriminatorValue("mouse")
public class Mouse extends Animal {
    // ...
}

I use following (simplified) syntax to receive all Animals:
ExpressionBuilder builder = new ExpressionBuilder(Animal.class);
ReadAllQuery databaseQuery = new ReadAllQuery(type, builder);
Expression exp = builder.getField("owner").equal("Thomas");
databaseQuery.setSelectionCriteria(exp);
Query query = ((JpaEntityManager)em.getDelegate()).createQuery(databaseQuery);
List<Animal> resultsList = query.getResultList();

As long as no items are in the DB, everything is fine and I get back an empty list.
If I add an item of type "Cat" I get following error:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'owner'.
Error Code: 207
Call: SELECT t0.uuid, t0.type, t0.name, t0.owner, t1.uuid FROM class_animal t0, class_animal_cat t1 WHERE ((t1.owner = ?) AND ((t1.uuid = t0.uuid) AND (t0.type = ?)))
    bind => [2 parameters bound]
Query: ReadAllQuery(referenceClass=Animal sql="SELECT DISTINCT type FROM class_animal WHERE (owner = ?)")

The field accessor to t1.owner is wrong - t0.owner would be right. How can I configure/anotate the field to always fall back to Animal.owner instead of i.E. Cat.owner?


text:
Q: A problem on chains of squares — can one find an easy combinatorial proof? Consider the unit square $ S = [0,1] \times [0,1] $. For each $ n \in \mathbb{N} $, we can tessellate $ S $ by the collection
$$
  A
= \left\{
    \left[ \frac{i}{n},\frac{i + 1}{n} \right] \times
    \left[ \frac{j}{n},\frac{j + 1}{n} \right] ~ \Bigg| ~
    i,j \in \{ 0,\ldots,n - 1 \}
  \right\}
$$
of $ n^{2} $ smaller squares whose sides have length $ \dfrac{1}{n} $.
Let $ C_{1} $ be a finite sequence $ (S_{k})_{k = 1}^{M} $ of squares in $ A $ such that

*

*$ S_{1} = \left[ 0,\dfrac{1}{n} \right] \times \left[ 0,\dfrac{1}{n} \right] $;

*$ S_{M} = \left[ \dfrac{n - 1}{n},1 \right] \times \left[ \dfrac{n - 1}{n},1 \right] $;

*$ S_{k} $ and $ S_{k + 1} $ share a common side for each $ k \in \{ 1,\ldots,M - 1 \} $.

Similarly, let $ C_{2} $ be a finite sequence $ (T_{k})_{k = 1}^{N} $ of squares in $ A $ such that

*

*$ T_{1} = \left[ 0,\dfrac{1}{n} \right] \times \left[ \dfrac{n - 1}{n},1 \right] $;

*$ T_{N} = \left[ \dfrac{n - 1}{n},1 \right] \times \left[ 0,\dfrac{1}{n} \right] $;

*$ T_{k} $ and $ T_{k + 1} $ share a common side for each $ k \in \{ 1,\ldots,N - 1 \} $.

Geometrically speaking, $ C_{1} $ is a chain of side-touching squares in $ A $ from the bottom leftmost corner of $ S $ to its upper rightmost corner, and $ C_{2} $ is a chain of side-touching squares from the upper leftmost corner of $ S $ to its bottom rightmost corner.

Combinatorial problem. Find a combinatorial proof that $ C_{1} $ and $ C_{2} $ contain a common square in $ A $. (It is intuitively obvious that the chains contain a common square in $ A $.)

If we let $ n \to \infty $, then we obtain a

Continuous version of the problem. Let $ \gamma_{1} $ be a continuous path in $ S $ from $ (0,0) $ to $ (1,1) $ and $ \gamma_{2} $ a continuous path in $ S $ from $ (0,1) $ to $ (1,0) $. Then prove that $ \gamma_{1} $ and $ \gamma_{2} $ intersect, i.e., $ {\gamma_{1}}(a) = {\gamma_{2}}(b) $ for some $ a,b $ in the interval $ ]0,1[ $.

The continuous version of the problem has a well-known solution via Brouwer's Fixed Point Theorem, but most proofs of Brouwer's Fixed Point Theorem require algebraic topology. Even Sperner's combinatorial proof requires some effort to understand. If, however, we can solve the combinatorial problem above, then by a limiting argument, we can solve the continuous version rather easily, thus avoiding Brouwer.
There are certain similarities between this problem and the Game of Hex, where elementary properties of the game are a consequence of non-trivial topological arguments, as first demonstrated by John Nash.

A: You could google digital Jordan curve theorem and you could also add some of the following names in your search: Khalimsky, Kiselman, Kopperman, Rosenfeld, Slapal. The papers you get are likely to be along the lines of what you are looking for, I hope.
In particular see several papers in a Special issue on digital topology,
Topology and its Applications
http://www.sciencedirect.com/science/article/pii/016686419290013P
or  a recent paper by J Šlapal, [Jordan Curves in the Digital Plane,
http://www.emis.de/journals/BMMSS/pdf/acceptedpapers/2011-06-033_R1.pdf
or an older survey, T. Yung Kong, Ralph Kopperman, Paul R. Meyer,
A topological approach to digital topology.
Amer. Math. Monthly 98 (1991), no. 10, 901–917.
http://www.jstor.org/discover/10.2307/2324147

A: I used to think that Sperner's proof is simple enough, but if you don't like it, maybe it's because what you're really looking for is an algorithm.
I can show that there is no fast algorithm for your problem, at least not something faster than for Sperner's lemma.
This is because your question, if defined appropriately, becomes PPAD-complete.
This means that if there was a fast algorithm for your problem, then one could convert it into a fast algorithm for finding a solution to a large class of other problems, like finding a Brouwer like fixed point or a a Nash equilibrium (if defined appropriately).
I really don't think that you are interested in the details, the proof is quite straightforward and similar to showing the PPAD-completeness of 2D-SPERNER or 2D-TUCKER.
In case you are, here is a list of papers: http://www.cs.princeton.edu/~kintali/ppad.html
If you don't like complexity theory, then here is the draft of a paper from whose proofs it follows that you can find a common square in O(n) steps, where one step is to ask of any one square whether it belongs to $C_1$ or $C_2$: http://arxiv.org/abs/1211.3000


text:
Q: Playing the MIDI at the iOS from Delphi XE - 5 is there way how to play MIDI from the Delphi at iPhone under Delphi XE-5?
I found different articles showing how to play the MIDI under ObjectC so the iOS from version 5.0 has that support, but there is missing AudioToolbox and CoreMIDI implementation at the Delphi.
Does someone have that?

A: I assume you're using XE-5 because you're attempting to build a cross-platform app.   You're up against a fundamental problem that some of the platforms supported by XE5 don't have MIDI at all.
However you approach this, you will need to build platform specific portions of the app to handle MIDI on iOS. The AudioToolbox API is a C API and CoreMIDI is Objective-C.  Either way, you need to learn how to create Objective-C and C language bindings in Delphi, and consider writing a large part of your app using the platform's native tools and language.
A quick search with google suggests that you should be looking at the OCClass bridge.

A: I found that there isn't any solution so far.
So I wrote my self a tool to convert the iOS .h units into the .PAS.
It's in progress but I have already first units.
http://pjstrnad.com/my-projects/delphi-implementation-missing-ios-frameworks/
I'll appreciate if you can give me feedback. My intention is to convert completely the iOS framework so Delphi developers can use all the features of the iOS.
Thanks.


text:
Q: NPM login to GitHub registry requires lowercase username I'm trying to log in from the command line using this command:
$ npm login --registry=https://npm.pkg.github.com/

But my username on GitHub has an uppercase first letter, which results in the following error:
$ npm login --registry=https://npm.pkg.github.com/
Username: <Username>
npm WARN Name must be lowercase

Anyone know how I can get around this? Do I have to change my GitHub username for this to work?

A: npm started to enforce lower case usernames at some points, leaving the accounts previously created in this awkward situation.
To solve the issue, you might want to email support@npmjs.com, which will link the lowercase variant of your username to your account.
source: this github issue.


text:
Q: MyBatis: how to pass default parameter to every query I'm developing a Spring Boot application and I need to pass a default parameter to every select query from a table.
This in order to get some previously encrypted user data.
Ex:
select
         a.ID,
         CAST(AES_DECRYPT(a.FIRST_NAME, SHA2(#{secretKey}, 512)) AS CHAR) FIRST_NAME,
         CAST(AES_DECRYPT(a.LAST_NAME, SHA2(#{secretKey}, 512)) AS CHAR) LAST_NAME,
         USERNAME,
         PASSWD,
         b.ID ID_ROLE,
         b.NAME ROLE_NAME
       from users a join
       roles b on a.ID_ROLE = b.ID
       where
        USERNAME = #{username,jdbcType=VARCHAR}

I'm using the mybatis-spring library with a SqlSessionFactoryBean configured in this way
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:sqlmaps/*.xml"));
        sessionFactory.setDataSource(ds);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.getVariables().put("secretKey", "my secret key");
        configuration.setCallSettersOnNulls(true);
        sessionFactory.setConfiguration(configuration);
        return sessionFactory;

But the "secretKey" It's not passed to the query.
What's the correct way to achieve this?
Thanks.

A: #{} is for referencing parameter(s) and its properties.
To reference variables, you need to use ${}.
As ${} is string substitution, it must be enclosed in single quotes and it is your responsibility to escape special characters like ' in the string.
SHA2('${secretKey}', 512)

Note that this solution is not recommended when secretKey is user-provided string because it is vulnerable to SQL injection attack.


text:
Q: How can I make width 100% max ? when I'm looking with both PC and iPhone? There is a table in my layout. I'm also using bootstrap's responsive design.
I want to know how to expand its width depending on the devices that I'm looking with.
For example, with my PC, my web site is usually shown with about 1200px width.
With my iPhone, my web site is usually shown with its resolution, which is about 640px.
I want to expand the bubble's width as much as possible(I mean 100% width)
Bubble's width should be flexible.  Shrinking window's width should make it resized automatically.
How can I?
Demo http://jsfiddle.net/8ASj4/
HTML

               Body

01-10 03:29:Person A

            bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
            <form action="/shop/walmart/posts/617" class="button_to" data-remote="true" method="post">
<input name="_method" value="delete" type="hidden"><input data-confirm="Are you sure?" data-disable-with="deleting..." value="destroy" type="submit"><input name="authenticity_token" value="aoLKQnl4M2SWVlOrXGR+qIMLSeY5m1tKiC/PSnYQjmw=" type="hidden">
</form>

01-10 03:25:Person A

            bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
            <form action="/shop/walmart/posts/615" class="button_to" data-remote="true" method="post">
<input name="_method" value="delete" type="hidden"><input data-confirm="Are you sure?" data-disable-with="deleting..." value="destroy" type="submit"><input name="authenticity_token" value="aoLKQnl4M2SWVlOrXGR+qIMLSeY5m1tKiC/PSnYQjmw=" type="hidden">
</form>

CSS
.chat {
    width: 100%;
    min-width: 300px;
}

.bubble{
    background-color: #FFFFFF;
    border-radius: 5px;
    box-shadow: 0 0 6px #B2B2B2;
    display: inline-block;
    padding: 10px 18px;
    position: relative;
    vertical-align: top;
    word-break: break-all;
}

.bubble::before {
    background-color: #FFFFFF;
    content: "\00a0";
    display: block;
    height: 16px;
    position: absolute;
    top: 11px;
    transform:             rotate( 29deg ) skew( -35deg );
        -moz-transform:    rotate( 29deg ) skew( -35deg );
        -ms-transform:     rotate( 29deg ) skew( -35deg );
        -o-transform:      rotate( 29deg ) skew( -35deg );
        -webkit-transform: rotate( 29deg ) skew( -35deg );
    width:  20px;
}

.me {
    float: left;
    margin: 5px 45px 5px 5px;
    min-width: 250px;
    width: 100%;
}

.me::before {
    box-shadow: -2px 2px 2px 0 rgba( 178, 178, 178, .4 );
    left: -9px;
}

.you {
    float: left;
    margin: 5px 10px 5px 5px;
    min-width: 250px;
    width: 100%;
}

.you::before {
    box-shadow: 2px -2px 2px 0 rgba( 178, 178, 178, .4 );
    right: -9px;
}

A: Just remove all of the table related tags (table/td/tr/etc.)

01-10 03:29:Person A

            bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
            <form action="/shop/walmart/posts/617" class="button_to" data-remote="true" method="post">
<input name="_method" value="delete" type="hidden"><input data-confirm="Are you sure?" data-disable-with="deleting..." value="destroy" type="submit"><input name="authenticity_token" value="aoLKQnl4M2SWVlOrXGR+qIMLSeY5m1tKiC/PSnYQjmw=" type="hidden">
</form>

01-10 03:25:Person A

            bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
            <form action="/shop/walmart/posts/615" class="button_to" data-remote="true" method="post">
<input name="_method" value="delete" type="hidden"><input data-confirm="Are you sure?" data-disable-with="deleting..." value="destroy" type="submit"><input name="authenticity_token" value="aoLKQnl4M2SWVlOrXGR+qIMLSeY5m1tKiC/PSnYQjmw=" type="hidden">
</form>

http://jsfiddle.net/8ASj4/2/


text:
Q: yield on a function that returns object which includes a promise In my saga I have a function I need to yield on but it doesnt return a promise directly. The function is this:
export function requestDownload(url): {
    let resolve, reject;
    return {
        type: REQUEST,
        url,
        promise: new Promise(res=>resolve=res, rej=>reject=rej),
        resolve,
        reject
    }
}

I need to yield on the promise field in the return. I tried variations of call but am not able to do this. I cannot modify this requestDownload function to return the promise directly.
Is this possible with any of the redux-saga helpers?
In summary I am trying to do:
I am trying to do:
function* mySaga() {
    yield call(requestDownload, 'blah_url')
}

A: How about:
function* mySaga() {
    let action = yield call(requestDownload, 'blah_url')
    try {
        let data = yield action.promise
    } catch(err) {
        // deal with error
    }
}


text:
Q: How to play sound in C from scratch (Linux) How to play sounds at different tones in C without using any external library? I know there are dozens of sound libraries in C that allows you to play sound but what I want to know is how does that work behind? How do you tell the computer to play a certain note at a certain tone/frequency?
I know it's possible on windows using the sound() function but I can't find any documentation talking about Linux, all that I found is the beep() function (or write(1, "\a", 1)) that outputs the default terminal beep but I can't figure out how to play different sounds.

A: The Linux kernel native audio API is ALSA (Advanced Linux Sound Architecture).
Example of raw audio playback with ALSA:
https://gist.github.com/ghedo/963382/815c98d1ba0eda1b486eb9d80d9a91a81d995283
However, ALSA is a low-level API that is not recommended to be used directly by higher-level applications.
A modern system audio API for GNU/Linux would be either PulseAudio (the current default on Ubuntu), or the newer and arguably better PipeWire (the default on Fedora).
Example of raw audio playback with PipeWire that generates audio "from scratch":
https://docs.pipewire.org/page_tutorial4.html
How do you tell the computer to play a certain note at a certain tone/frequency?
Sound is a mechanical vibration that propagates through the air (or another medium). It can be represented digitally as a sequence of numerical values representing air pressure at a given sampling rate. To play a given tone/frequency, generate a sine wave of that frequency (at the playback sampling rate) and use the sound API of your choice to play it.
See the PipeWire tutorial above for an example generating a 440Hz tone.
About PulseAudio/PipeWire:
These libraries are typically part of the OS and exposed as system APIs (so they are not "external libraries" if that means some library to ship with your program or to ask users to install), and they should be used by applications to play audio.
Behind the scene, these libraries handle audio routing, mixing, echo-canceling, recording, and playback to the kernel through ALSA (or using Bluetooth, etc). Everything that users and developers expect from the system audio layer.
Until recently, PulseAudio was the de-facto universal desktop system audio API, and many apps still use the PulseAudio API to play audio on GNU/Linux.
PipeWire includes compatibility with PulseAudio, so that apps using the PulseAudio API will keep working in the foreseeable future.
Example of raw audio playback with PulseAudio:
https://freedesktop.org/software/pulseaudio/doxygen/pacat-simple_8c-example.html


text:
Q: htmlentities returning blank after upgrading to PHP 5.5 After upgrading to PHP 5.5, html_entities is returning blank for some strings. Specifically, it seems to be strings that contain French characters. I have tried setting it to UTF-8 but still blank:
htmlentities($str,ENT_COMPAT, 'UTF-8');

Anybody know what's going on here?
My code was working without issue on PHP 5.3.3.
Thanks for any help.
EDIT: Example string from comment
"
Obtenez de meilleurs résultats en moins de temps. Garanti.
"

A: Quote from http://php.net/manual/en/function.htmlentities.php

If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set.

so something like
<?php
$str = "
\xe2 title
";
echo htmlentities($str,ENT_COMPAT, 'UTF-8');

see https://3v4l.org/9OuRE
will return an empty string


text:
Q: How to kill the background process in TCL in the windows environment I have started iperf as the background process from within a Tcl program by using Tcl's exec command in the windows environment. However, I'd like to programmatically kill the iperf process from the same Tcl program at some arbitrary time in the future. How can I best accomplish this?
Here's the code I'm using
proc runtest {  REF_WLAN_IPAddr run_time} {
    exec c:\\iperf_new\\iperf -c $REF_WLAN_IPAddr -f m -w 2M -i 1 -t $run_time  >& xx.txt &
    # have some code after this
}

but i see iperf is not killed, and so the control is not transferred back to TCL, how can i do this? The answers are highly appreciated
}

A: exec returns the list of subprocess PIDs if used in the way you describe,
but Tcl does not have a builtin kill command; those are only available in extensions.
So you have two major options:

*

*Get the TWAPI package http://twapi.magicsplat.com/ and use the end_process function from that package (see http://twapi.magicsplat.com/process.html#end_process)

*Use a second exec and run the windows command taskkill with the /PID Option
exec [auto_execok taskkill] /PID $pid

A: Or maybe
exec {*}[auto_execok start] C:\\Windows\\System32\\taskkill.exe $pid

or
exec {*}[auto_execok start] C:\\Windows\\System32\\taskkill.exe /F /IM ProgramName.EXE /T

A: Here is a skeleton script I use:
package require Tclx

puts "main begins"

puts "Launch child script"
set childPid [exec tclsh child.tcl 0 &]
puts "Child PID: $childPid"

puts "Do something now..."
after 1000

puts "Now wait for child to finish"
lassign [wait $childPid] pid howEnded exitCode

puts "Process $pid ended with reason ($howEnded) and exit code ($exitCode)"
puts "main ends"

Discussion

*

*The script (main.tcl) spawn a child script (child.tcl, or ifperf in your case) and record its process ID to childPid

*The main script then does something (in this case, after 1000, which simply sleeps for 1000 miliseconds)

*The main script calls the wait command to wait for the child process to finish. Wait returns a list of 3 things: the process ID, how it ended, and exit code

*Caveat: if the child finishes before for you call wait, the wait command will throw an exception, you need to catch it.

Here is a sample run:
$ tclsh main.tcl
main begins
Launch child script
Child PID: 25837
Do something now...
  child runs for 16889 miliseconds
Now wait for child to finish
  child ends
Process 25837 ended with reason (EXIT) and exit code (0)
main ends


text:
Q: Google Map Directions Service API 'Drag to change route' text change I've successfully implemented google map direction service api : https://developers.google.com/maps/documentation/javascript/directions with 'draggble' option enabled. Is it possible to change the text label of Drag button (screenshot attached) on hovering the route ? At present it says: 'Drag to change route'. I need to modify it. I checked the documentation: https://developers.google.com/maps/documentation/javascript/reference, but couldn't find anything for this.
The current code is similar to: https://developers.google.com/maps/documentation/javascript/examples/directions-draggable
Please help me. Thanks in advance!

Update: I just got a down vote for: "There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.". The code is available in the provided url and I think there can be only one solution available using google map api. If there's any additional information needed, please add a comment.

A: Probably my answer will be downvoted, but maybe it will be useful for you. Let's say it's just an idea. So you may change the tooltip of the route after the direction has been changed.
    directionsDisplay.addListener('directions_changed', function() {
        directionsDisplay.gd.b.setTitle('This is your new tooltip for the route.');
    });

But unfortunately at the time of the directions_changed event there are no markers yet, so somehow you should delay setting their title:
      for (var i = 0; i < directionsDisplay.b.G.length; i++){
        directionsDisplay.b.G[i].setTitle('Marker ' + i + ' tooltip');
      }

UPDATE:
A more general code:
    directionsDisplay.addListener('directions_changed', function() {
        setRouteTitle(directionsDisplay, 'The new tooltip');
    });

    function setRouteTitle(dirsDispl, newTitle){
        var ddObjKeys = Object.keys(dirsDispl);
        for (var i = 0; i < ddObjKeys.length; i++){
            var obj = dirsDispl[Object(ddObjKeys)[i]];
            var ooObjKeys = Object.keys(obj);
            for (var j = 0; j < ooObjKeys.length; j++){
                var ooObj = obj[Object(ooObjKeys)[j]];
                if ((ooObj) && (ooObj.hasOwnProperty('title')) && (ooObj.hasOwnProperty('shape')) && (ooObj.shape.type == 'circle')){
                    ooObj.setTitle(newTitle);
                }
            }
        }
    };

Hope this helps.


text:
Q: Lets Encrypt 403 Error When Installing Certificate I receive a urllib2.HTTPError: HTTP Error 403: Forbidden error when attempting to install a Lets Encrypt certificate using Certbot. I have been installing certificates using the steps listed in this article for over a year and recently starting running into an issue on many of my servers.
The environment of each of the servers with the issue:
GoDaddy Cloud Server (512MB)
Bitnami Wordpress
Ubuntu 14.04.5 LTS
Python 2.7.6
Here are the outputs when attempting to install a certificate:
sudo ./certbot-auto certonly --webroot -w /opt/bitnami/apps/wordpress/htdocs/ -d xxxxxxxxxxxxx.com
Bootstrapping dependencies for Debian-based OSes... (you can skip this with --no-bootstrap)
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty InRelease
Get:1 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates InRelease [65.9 kB]
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports InRelease
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty Release.gpg
Get:2 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/main Sources [399 kB]
28% [2 Sources 63.9 kB/399 kB 16%] [Waiting for headers] [Waiting for headers]
Hit http://security.ubuntu.com trusty-security InRelease
Hit http://ppa.launchpad.net trusty InRelease
Hit http://security.ubuntu.com trusty-security/main Sources
Get:3 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/restricted Sources [6,331 B]
Get:4 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/universe Sources [180 kB]
Hit http://ppa.launchpad.net trusty/main amd64 Packages
Get:5 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/multiverse Sources [7,764 B]
Get:6 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/main amd64 Packages [984 kB]
Hit http://security.ubuntu.com trusty-security/universe Sources
Hit http://ppa.launchpad.net trusty/main i386 Packages
Hit http://ppa.launchpad.net trusty/main Translation-en
Hit http://security.ubuntu.com trusty-security/main amd64 Packages
Hit http://security.ubuntu.com trusty-security/universe amd64 Packages
Hit http://security.ubuntu.com trusty-security/main i386 Packages
Get:7 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/restricted amd64 Packages [17.1 kB]
Hit http://security.ubuntu.com trusty-security/universe i386 Packages
Get:8 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/universe amd64 Packages [408 kB]
Hit http://security.ubuntu.com trusty-security/main Translation-en
Get:9 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/multiverse amd64 Packages [14.3 kB]
Get:10 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/main i386 Packages [941 kB]
Hit http://security.ubuntu.com trusty-security/universe Translation-en
Get:11 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/restricted i386 Packages [16.9 kB]
Get:12 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/universe i386 Packages [408 kB]
Get:13 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/multiverse i386 Packages [14.6 kB]
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/main Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/multiverse Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/restricted Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/universe Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty Release
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/main Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/restricted Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/universe Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/multiverse Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/main amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/restricted amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/universe amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/multiverse amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/main i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/restricted i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/universe i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/multiverse i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/main Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/multiverse Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/restricted Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/universe Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe Translation-en
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main Translation-en_US
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse Translation-en_US
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted Translation-en_US
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe Translation-en_US
Fetched 3,463 kB in 8s (395 kB/s)
Reading package lists... Done
W: Ignoring Provides line with DepCompareOp for package python-cffi-backend-api-max
W: Ignoring Provides line with DepCompareOp for package python-cffi-backend-api-min
W: Ignoring Provides line with DepCompareOp for package python3-cffi-backend-api-max
W: Ignoring Provides line with DepCompareOp for package python3-cffi-backend-api-min
W: Ignoring Provides line with DepCompareOp for package python-cffi-backend-api-max
W: Ignoring Provides line with DepCompareOp for package python-cffi-backend-api-min
W: Ignoring Provides line with DepCompareOp for package python3-cffi-backend-api-max
W: Ignoring Provides line with DepCompareOp for package python3-cffi-backend-api-min
W: You may want to run apt-get update to correct these problems
Reading package lists... Done
Building dependency tree
Reading state information... Done
gcc is already the newest version.
python is already the newest version.
python-dev is already the newest version.
augeas-lenses is already the newest version.
ca-certificates is already the newest version.
libaugeas0 is already the newest version.
libffi-dev is already the newest version.
libssl-dev is already the newest version.
openssl is already the newest version.
python-virtualenv is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 19 not upgraded.
WARNING: unable to check for updates.
Creating virtual environment...
Running virtualenv with interpreter /usr/bin/python2.7
New python executable in /home/xxxxxxxxxxx/.local/share/letsencrypt/bin/python2.7
Also creating executable in /home/xxxxxxxxxxx/.local/share/letsencrypt/bin/python
Installing setuptools, pip...done.
Installing Python packages...
Traceback (most recent call last):
  File "/tmp/tmp.rG5cNt1Qm0/pipstrap.py", line 146, in <module>
    exit(main())
  File "/tmp/tmp.rG5cNt1Qm0/pipstrap.py", line 130, in main
    for url, digest in PACKAGES]
  File "/tmp/tmp.rG5cNt1Qm0/pipstrap.py", line 112, in hashed_download
    response = opener().open(url)
  File "/usr/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

UPDATE
Here is what happens when I try to download the tar files from pypi.python.org
bitnami@atv-demo:/tmp$ sudo wget https://pypi.python.org/packages/source/p/pip/pip-8.0.3.tar.gz
--2017-06-07 06:58:33--  https://pypi.python.org/packages/source/p/pip/pip-8.0.3.tar.gz
Resolving pypi.python.org (pypi.python.org)... 151.101.32.223, 2a04:4e42:8::223
Connecting to pypi.python.org (pypi.python.org)|151.101.32.223|:443... connected.
HTTP request sent, awaiting response... 403 Forbidden
2017-06-07 06:58:33 ERROR 403: Forbidden.

bitnami@atv-demo:/tmp$ sudo wget https://pypi.python.org/packages/source/s/setuptools/setuptools-20.2.2.tar.gz
--2017-06-07 06:58:41--  https://pypi.python.org/packages/source/s/setuptools/setuptools-20.2.2.tar.gz
Resolving pypi.python.org (pypi.python.org)... 151.101.32.223, 2a04:4e42:8::223
Connecting to pypi.python.org (pypi.python.org)|151.101.32.223|:443... connected.
HTTP request sent, awaiting response... 403 Forbidden
2017-06-07 06:58:41 ERROR 403: Forbidden.

bitnami@atv-demo:/tmp$ sudo wget https://pypi.python.org/packages/source/w/wheel/wheel-0.29.0.tar.gz
--2017-06-07 06:58:48--  https://pypi.python.org/packages/source/w/wheel/wheel-0.29.0.tar.gz
Resolving pypi.python.org (pypi.python.org)... 151.101.32.223, 2a04:4e42:8::223
Connecting to pypi.python.org (pypi.python.org)|151.101.32.223|:443... connected.
HTTP request sent, awaiting response... 403 Forbidden
2017-06-07 06:58:48 ERROR 403: Forbidden.

A: Bitnami developer here.
According to the traceback you shared, the error occurred while trying to download a Python package. The list of URLs that the script tries to download is:
https://pypi.python.org/packages/source/p/pip/pip-8.0.3.tar.gz
https://pypi.python.org/packages/source/s/setuptools/setuptools-20.2.2.tar.gz
https://pypi.python.org/packages/source/w/wheel/wheel-0.29.0.tar.gz

And optionally:
https://pypi.python.org/packages/source/a/argparse/argparse-1.4.0.tar.gz

Taking into account the URLs point to pypi.python.org, this was probably a transient error.
Alternatively, you may try to install Certbot from the official PPA instead of using certbot-auto.


text:
Q: Tensor product for binary numbers I'm working on an FPGA project where I need to calculate tensor product between two binary numbers. This is to be used to calculate CRC values. I was referring to this paper from IEEE. "Fast parallel CRC algorithm and implementation on a configurable processor"
According to this paper, I need to calculate the "product" of this expression;
1011 $\otimes$ 1001
Is this tensor product or something else?
Thanks in advance!


text:
Q: Getting a valid makefile from tikz-externalize when using `-output-directory` and input The following mwe does produce an invalid makefile when used with latexmk's -output-directory option. (The example is from the pgfplots manual)
latexmk mwe.tex -output-directory=build
\documentclass{article}

\usepackage{tikz}
\usepackage{pgfplots}
\usepgfplotslibrary{external}
\tikzexternalize[mode=list and make]

\begin{document}

\input{tikz/figure.tikz}

\end{document}

and a file under tikz/figure.tikz
\begin{figure}
\begin{tikzpicture}
\begin{axis}
\addplot {x^2};
\end{axis}
\end{tikzpicture}
\caption{Our first external graphics example}
\end{figure}

with the makefile beeing at build/mwe.makefile
ALL_FIGURE_NAMES=$(shell cat mwe.figlist)
ALL_FIGURES=$(ALL_FIGURE_NAMES:%=%.pdf)

allimages: $(ALL_FIGURES)
    @echo All images exist now. Use make -B to re-generate them.

FORCEREMAKE:

include $(ALL_FIGURE_NAMES:%=%.dep)

%.dep:
    mkdir -p "$(dir $@)"
    touch "$@" # will be filled later.

mwe-figure0.pdf:
    pdflatex -shell-escape -halt-on-error -interaction=batchmode -jobname "mwe-figure0" "\def\tikzexternalrealjob{mwe}\input{mwe}"

mwe-figure0.pdf: mwe-figure0.md5

as the mwe.tex file is not in the build directory, running the make command from the build directory will not work;
also running it from the projcts "root" directory will not work, as there is no mwe.figlist there.

A: This solution is a dirty hack, so I will not accept it, hoping for someone to provide a better answer.
A current workaround I have is modifying the commands used to create the makefile; this idea is from here and modify the commands including moving up a directory cd .. && and setting the output-directory --output-directory=./build as follows:
\documentclass{article}

\usepackage{tikz}
\usepackage{pgfplots}
\usepgfplotslibrary{external}
\tikzexternalize[mode=list and make]

\tikzset{%
    external/system call={cd .. && pdflatex \tikzexternalcheckshellescape --halt-on-error --interaction=batchmode --output-directory=./build --jobname "\image" "\texsource"},
    /pgf/images/include external/.code={%
        \includegraphics{build/#1}%
    },
}
\begin{document}

\input{tikz/figure.tikz}

\end{document}

generating the new makefile

ALL_FIGURE_NAMES=$(shell cat mwe.figlist)
ALL_FIGURES=$(ALL_FIGURE_NAMES:%=%.pdf)

allimages: $(ALL_FIGURES)
        @echo All images exist now. Use make -B to re-generate them.

FORCEREMAKE:

include $(ALL_FIGURE_NAMES:%=%.dep)

%.dep:
        mkdir -p "$(dir $@)"
        touch "$@" # will be filled later.

mwe-figure0.pdf:
        cd .. && pdflatex -shell-escape --halt-on-error --interaction=batchmode --output-directory=./build --jobname "mwe-figure0" "\def\tikzexternalrealjob{mwe}\input{mwe}"

mwe-figure0.pdf: mwe-figure0.md5

which now can be built from the build directory with make -f mwe.makefile.


text:
Q: Specifying execution platform in protractor I'm trying to specify in protractor which platform specific tests should be executed on. In the base selenium implementation you do it like this (depending on the language binding you are using):
desiredCapabilities.setCapability(CapabilityType.PLATFORM, "MAC");

I don't see how to do that in protractor itself. Is there a way to set this parameter in Protractor test code? I haven't seen anything about this in the references or in any google searches I have been doing on the problem.
Edit:
According to the answer of Andersson I have currently updated my conf.js file to the following, which now seems to be working:
exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  'capabilities': {
    browserName: 'chrome',
    platform: 'WINDOWS'
  },
  specs: ['todo-spec.js']
};

A: You can specify platform info in conf.js as:
exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  'capabilities': {
    browserName: 'chrome',
    platform: 'MAC'
  },
  specs: ['todo-spec.js']
};

Let me know if it's not exactly what you want


text:
Q: Error when install 'e1071' in R on Mac Error shown on console
> install.packages('e1071')
trying URL 'https://cran.rstudio.com/src/contrib/e1071_1.6-8.tar.gz'
Content type 'application/x-gzip' length 581513 bytes (567 KB)
==================================================
downloaded 567 KB

* installing *source* package 'e1071' ...
** package 'e1071' successfully unpacked and MD5 sums checked
checking for C++ compiler default output file name... a.out
checking whether the C++ compiler works... configure: error: cannot
run C++ compiled programs.
If you meant to cross compile, use `--host'.
See `config.log' for more details.
ERROR: configuration failed for package 'e1071'
* removing '/anaconda3/lib/R/library/e1071'
Warning in install.packages :
installation of package 'e1071' had non-zero exit status

I've checked on terminal, gcc is installed and updated.
I also tried https://cran.r-project.org/web/packages/e1071/index.html to download both latest and former versions manually and installed them on R console. The error was still there.
How can I fix it?
Thanks!

A: I ran into this error when using RStudio through Anaconda. I just re-downloaded RStudio from the R website, and now the error has gone away, and e1071 installs just fine.


text:
Q: Why is there no play button in android browser on HTML5 video? In iPhone a play button appears on a video automatically, like here:

Why is there no such thing in android? If i use a custom play button for both devices it will appear on top of the iphone plat button
any solutions?

A: Currently Android doesn't display the play button. A workaround this might be to detect if the user is coming to your website through iPhone or Android. Have a look at this to see you to do that. You can then show the button only if the user comes to the website through Android.
You will also have to manually play the video on Android.
var video = document.getElementById('video');
video.addEventListener('click',function(){
  video.play();
},false);


text:
Q: Div table-cell vertical align not working I am trying to simply center text horizontally and vertically using DIV and display type as table-cell but it is not working in either IE8 or Firefox.
Below is the CSS that I am using and that is all that is in the html page.
@charset "utf-8";
/* CSS Document */
html, body
{
    background-color:#FFFFFF;
    font-family:Arial, Helvetica, sans-serif;
    margin: 0;
    padding: 0;
    padding-top: 5px;
}
div.Main
{
    background-color:#FFFFFF;
    border-collapse:collapse;
    width:800px;
    margin-left:auto;
    margin-right:auto;
}
div.MainHeader
{
    color:#C00000;
    font-size:18pt;
    font-weight:bold;
    text-align:center;
    width:800px;
}
div.BlackBox
{
    background-color:#000000;
    color:#FFFF00;
    display:table-cell;
    float:left;
    font-size:18pt;
    font-weight:bold;
    height:191px;
    text-align:center;
    vertical-align:middle;
    width:630px;
}
div.BlackBoxPicture
{
    background-color:#000000;
    float:right;
    height:191px;
    margin-top:auto;
    margin-bottom:auto;
    text-align:right;
    vertical-align:bottom;
    width:170px;
}

What am I doing wrong?

A: An element styled as follows will be aligned vertically to middle:
.content{
     position:relative;
     -webkit-transform: translateY(-50%);
     -ms-transform: translateY(-50%);
     transform: translateY(-50%);
     top:50%;
}

However, the parent element must have a fixed height.
See this fiddle: https://jsfiddle.net/15d0qfdg/12/

A: see this bin:
http://jsbin.com/yacom/2/edit
should set parent element to
display:table-cell;
vertical-align:middle;
text-align:center;

A: In my case, I wanted to center in a parent container with position: absolute.

            My content

I had to add some positioning for top, bottom, left & right.
.absolute-container {
    position:absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
}

.parent-container {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table
}

.centered-content {
    display: table-cell;
    text-align: center;
    vertical-align: middle
}

A: I think table-cell needs to have a parent display:table element.

A: This is how I do it:
CSS:
html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table
}
#content {
    display: table-cell;
    text-align: center;
    vertical-align: middle
}

HTML:

    Content goes here

See
Example of vertical centering
and
CSS: centering things.

A: Because you still using float...
try to remove "float" and wrap it with display:table
example :

       Hai i'm center here Lol

A: Float it with another wrapper without using display: table;, it works:

I am vertically aligned on your right! ^^

A: Sometime floats brake the vertical align, is better to avoid them.

A: You can vertically align a floated element in a way which works on IE 6+. It doesn't need  full table markup either. This method isn't perfectly clean - includes wrappers and there are  a few things to be aware of e.g. if you have too much text outspilling the container - but it's pretty good.

Short answer: You just need to apply display: table-cell to an element inside the floated element (table cells don't float), and use a fallback with position: absolute and top for old IE.

Long answer: Here's a jsfiddle showing the basics. The important stuff summarized (with a conditional comment adding an .old-ie class):
    .wrap {
        float: left;
        height: 100px; /* any fixed amount */
    }
    .wrap2 {
        height: inherit;
    }
    .content {
        display: table-cell;
        height: inherit;
        vertical-align: middle;
    }

    .old-ie .wrap{
        position: relative;
    }
    .old-ie .wrap2 {
        position: absolute;
        top: 50%;
    }
    .old-ie .content {
        position: relative;
        top: -50%;
        display: block;
    }

Here's a jsfiddle that deliberately highlight the minor faults with this method. Note how:

*

*In standards browsers, content that exceeds the height of the wrapper element stops centering and starts going down the page. This isn't a big problem (probably looks better than creeping up the page), and can be avoided by avoiding content that is too big (note that unless I've overlooked something, overflow methods like overflow: auto; don't seem to work)

*In old IE, the content element doesn't stretch to fill the available space - the height is the height of the content, not of the container.

Those are pretty minor limitations, but worth being aware of.
Code and idea adapted from here

A: Set the height for the parent element.

A: Simply remove the float from the element which has table-cell set on it.


text:
Q: Authenticate on a on-premise webservice I am having trouble with authentication in my asp-net web service. This service has an angular gui and some mvc api.
This service will be deployed on multiple servers inside my organisation windows or linux (or even docker). This seems to prevent me from using basic active directory authentication. Important part is I don't know before deployment the target ip:port of deployment.
I am trying to add an azure active directory based authentication.
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
                    .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
}

Everything works fine until I get into the Reply Url part of the authent process. It seems I can't find a way to avoid using a reply url.
In dev environement I have to add localhost as a valid reply url to my app and everything works fine. But what about future deployment? It seems very painfull to maintain a complete and up to date list of all the alive servers.
Is there a way to do the complete auth process client side and then go back to back end only when the final token has been received? I then suppose that the backend would have to validate the token against the authority has it was not implied in the process but that's fine.
What am I missing here?


text:
Q: jQuery FlipCounter count each digit I'm currently using FlipCounter to count up from 0 to 3,000 but, instead of counting each digit (like the example) it's jumping 1,000 at a time.
Any advice/help would be much appreciated!
JS
  function total(){
    var length = defaultArray.length+'000';
    $("#flipcounter").flipCounterInit();
    function updateLoop(){
      $("#flipcounter").flipCounterUpdate(length);
      window.setTimeout(function () {
        updateLoop();
      }, 5000);
    }
    updateLoop();
  }
  total();

HTML

Total word submissions

Project URL: https://cdn.rawgit.com/adamkwadsworth/oup-interactive-content/master/index.html

A: I think you might want to do something like this. Then when the number gets to 3000, don't do setTimeout
$("#flipcounter").flipCounterInit();

var number = 0;
function updateLoop() {
    number++;
    $("#flipcounter").flipCounterUpdate(number);
    if (number <= 3000) {
        window.setTimeout(updateLoop, 5000);
    }
}
updateLoop();


text:
Q: Not able to add to material design elements to boilerplate app I am trying to add material design elements to quickstart angular app
In app.module.ts added the following:
import {MaterialModule} from '@angular/material';

@NgModule({
  imports:      [ BrowserModule, MaterialModule.forRoot()],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})

In app.component.ts added the following:
@Component({
  selector: 'my-app',
  template: '
My First Angular App
<md-slide-toggle>Slide Toggle</md-slide-toggle>',
})

Here is the plunkr
http://plnkr.co/edit/gAIVxRTA0QZNu3uTC66k?p=preview

A: DEMO : http://plnkr.co/edit/IpeusijLdoTb6p27m7d7?p=preview

You are missing required things as mentioned below,

1) you need to add angular2-material package first in order to use it.
systemjs.config.js
'@angular/material':'npm:@angular/material/material.umd.js',  //<<<### added this

2) angular2-material requires hammer.js support. So, you also need to include it in index.html
index.html

A: adding the following to systemjs.config.js solved the problem
packages: {
  '@angular/material': {
    format: 'cjs',
    main: 'material.umd.js'
  }
}

or the following also solves:
'@angular/material':'npm:@angular/material/material.umd.js'


text:
Q: How do I pass a GET variable to my controller in my custom PHP framework? This is the router for the controller. Now I want to be able to pass an ID or any data through the router to the controller, so that I can perform actions based on the data received like in Laravel.
OLD (what I have now)
$router->get('user-account', 'PagesController@account');

NEW (what I am looking for)
$router->get('user-account/{id}','PagesController@account');

This is the Request type router file which direct request to the router either it be POST / GET
<?php
Class Router {

    public $routes = [
        'GET' => [],
        'POST' => []
    ];

    public static function load($file)
    {
        $router = new static;
        require $file;
        return $router;
    }

    public function get($uri,  $controller)
    {
        $this->routes['GET'][$uri] = $controller;
    }

    public function post($uri,  $controller)
    {
        $this->routes['POST'][$uri] = $controller;
    }

    public function direct($uri, $requestType)
    {
        if(array_key_exists($uri, $this->routes[$requestType]))
        {
            return $this->callAction(
            ...explode('@', $this->routes[$requestType][$uri])
            );
        }

        throw new Exception('No routes defined for this URL.');
    }

    protected function callAction($controller, $action)
    {
        $controller = new $controller;

        if(! method_exists($controller, $action))
        {
            throw new Exception(
                "{$controller}  does not respond to the {$action} action."
            );
        }

        return $controller->$action();
    }

}

I want to be able to pass data to the functions in the pages controller through the router, like that of Laravel.


text:
Q: C - Returning an array from a function I'm trying to create a function that returns an array of strings in C. I've looked at some other questions on the site and tried some of the solutions, but nothing seems to work. I've tried (1) simply changing the function to change the array contents rather than returning it, and I've tried (2) explicitly returning the arrayz, but neither seems to work.
Approach #1:
In one file, the function:
 int getArray(int num, char** array)
    {
        int i;
        for (i = 0; i < num; i++)
            array[i] = "whatever";
        return 0;
    }

In another file, I call the function:
char** array = malloc(sizeof(char*) * num));
getArray(num, files);

When I try printing the contents of the array files, nothing shows up.
Approach #2:
In one file, the function:
 char** getArray(int num)
    {
        int i;
        char** array = malloc(sizeof(char*) * num));
        for (i = 0; i < num; i++)
            array[i] = "whatever";
        return array;
    }

In another file, I call the function:
    char** files = getArray(num);

Again, when I try printing the content of files, nothing shows up.
I have checked and the header file where getFiles() is being defined has been included in the file where I make the call. I'm not sure what's happening.

A: You named your array "array", not "files":
char** array = malloc(sizeof(char*) * num));
getArray(num, files);

Try
getArray(num, array);

A: char** array = malloc(sizeof(char*) * num));

here you allocate memory for num char pointers, but not to store num strings. you need to allocate memory for the strings too. i.e. "whatever" you are storing.
And you cant assign a string,
 array[i] = "whatever";

you should use,
strcpy(array[i],"whatever");

A: You need to actually allocate space for your strings. You are just allocating memory for pointers to your strings.
In the example you provided you can use strdup to allocate space for your whatever string. Like this:
int getArray(int num, char** array)
{
    int i;
    for (i = 0; i < num; i++)
        array[i] = strdup("whatever");
    return 0;
}

A: I don't know what you are trying to do. But I think you just do like this.
#include <stdio.h>

char** getArray(int num)
{
  int i;
  char** array = malloc(sizeof(char*) * num);
  char* whatever = "whatever";

  for (i = 0; i < num; i++)
  {
    array[i] = whatever;
    //    array[i][0] = '0' + i;//Comment out because "whatever" is now constant that is immutable. So you can't change it.
  }
  return array;
}

main(){
  char** arr;
  int i;
  arr = getArray(10);
  for(i=0; i<10; i++)
  {
    printf("addr=%d, val=%s\n",arr[i], arr[i]);
  }
}

output:
addr=39075716, val=whatever
addr=39075716, val=whatever
addr=39075716, val=whatever
addr=39075716, val=whatever
addr=39075716, val=whatever
addr=39075716, val=whatever
addr=39075716, val=whatever
addr=39075716, val=whatever
addr=39075716, val=whatever
addr=39075716, val=whatever

Is this OK? In above case arr[i] is readonly and points just one memory space. Occasionally this is very memory efficient.
But I think you want to do like this.
#include <stdio.h>

char** getArray(int num)
{
  int i;
  char** array = malloc(sizeof(char*) * num);
  char* whatever;

  for (i = 0; i < num; i++)
  {
    whatever = malloc(sizeof(char) * (strlen("whatever")+1));
    strcpy(whatever, "whatever");//Now you can change "whatever". Because you created new readable-writable memory space by using malloc.
    array[i] = whatever;
    array[i][0] = '0' + i;//Now You can change array[i].
  }
  return array;
}

main(){
  char** arr;
  int i;
  arr = getArray(10);
  for(i=0; i<10; i++)
  {
    printf("addr=%d, val=%s\n",arr[i], arr[i]);
  }
}

output:
addr=-356501104, val=0hatever
addr=-356501088, val=1hatever
addr=-356501072, val=2hatever
addr=-356501056, val=3hatever
addr=-356501040, val=4hatever
addr=-356501024, val=5hatever
addr=-356501008, val=6hatever
addr=-356500992, val=7hatever
addr=-356500976, val=8hatever
addr=-356500960, val=9hatever

Now you can change the arr[i] because you used malloc and create memory space for the new string("xhatever").
I hope it helps. :)


text:
Q: disable mongoEmbeddedServer at test environment I'm using embedmongo-spring only for dev purposes. I have a problem using it on my test server as it is failing downloading the embeddedmongo zip file (not a lot of disk space), but anyways, I don't need it to be downloaded as I'm using a real mongoDB server for testing.
The problem is that spring automatically trying to create the embeddedMongoServer:

11:10:51.998 [main] WARN  o.s.w.c.s.GenericWebApplicationContext -
  Exception encountered during context initialization - cancelling
  refresh attempt:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'embeddedMongoServer' defined in class path
  resource
  [org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [de.flapdoodle.embed.mongo.MongodExecutable]: Factory
  method 'embeddedMongoServer' threw exception; nested exception is
  java.lang.RuntimeException: could not create dir
  /users//.embedmongo/extracted/Linux-B64--3.2.2 11:10:52.009
  [main] INFO  o.s.b.a.l.ConditionEvaluationReportLoggingListener -

The only place I'm using the embedded mongo is at some class named MongoDevConfiguration which annotated with @Profile("dev") (and the output above is for the active profile test)
How can I guide spring not to create the embeddedMongoServer on the test server?

A: I found the solution:
@EnableAutoConfiguration(exclude = EmbeddedMongoAutoConfiguration.class)


text:
Q: Ant SecureInputHandler: prints password in clear text when used with tee We use Ant's secure handler to enter passwords:
<input message="Please enter TFS password: " addproperty="tfs.password">
  <handler type="secure"/>
</input>

That, of course, does work: input is not printed.
When though (to save the build log) we run the build as
ant | tee build.log

the input is printed in clear text. Oops.
I wonder where is the issue (ant? tee?) and how to fix that.
P.S. OS:
Linux devosb1 3.0.0-12-generic #20-Ubuntu
SMP Fri Oct 7 14:56:25 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux

P.P.S. OK, so it is not tee -- a shell script with read/echo instead of tee triggers the same behaviour.

A: Looks like a shell issue. Have you considered using the ANT record task?
<project name="demo" default="build">

    <target name="build">
        <record name="build.log" loglevel="verbose"/>

        <input message="Please enter TFS password: " addproperty="tfs.password">
            <handler type="secure"/>
        </input>
    </target>

</project>


text:
Q: How strict can I be in the definition of "2-group"? Recall that a group is an associative, unital monoid $G$ such that the map $(p_1,m) : G \times G \to G\times G$ is an isomorphism of sets.  Here $p_1$ is the first projection and $m$ is the multiplication, so the map is $(g_1,g_2) \mapsto (g_1,g_1g_2)$.
My question is a basic one concerning the definition of "2-group".
Recall that a monoidal category is a category $\mathcal G$ along with a functors $m : \mathcal G \times \mathcal G \to \mathcal G$ and $e: 1 \to \mathcal G$, where $1$ is the category with one object and only identity morphisms, such that certain diagrams commute up to natural isomorphism and those natural isomorphisms satisfy some axioms of their own (the natural isomorphisms are part of the data of the monoidal category).
Then a 2-group is a monoidal category $\mathcal G$ such that the functor $(p_1,m): \mathcal G \times \mathcal G \to \mathcal G \times \mathcal G$ is an equivalence of categories.  I.e. there exists a functor $b: \mathcal G \times \mathcal G \to \mathcal G \times \mathcal G$ such that $b\circ (p_1,m)$ and $(p_1,m) \circ b$ are naturally isomorphic to the identity.  Note that $b$ is determined only up to natural isomorphism of functors.

Question: Can I necessarily find such a functor $b$ of the form $b = (p_1,d)$, where $d : \mathcal G \times \mathcal G \to \mathcal G $ is some functor (called $d$ for "division")?  If so, can I necessarily find $d = m\circ(i \times \text{id})$, where $i: \mathcal G \to \mathcal G$ is some functor (called $i$ for "inverse")?

In any case, the natural follow-up question is to ask all these at the level of 3-groups, etc.

A: You can always do this. Take any $b$ and define $d = p_2 b$. Then $b' = (p_1, d)$ is equivalent to the original $b$. To see this note that
$$(p_1, m) \circ b = (p_1b, m \circ (p_1 b, d)) \simeq id = (p_1, p_2)  $$
The first component shows $p_1 b \simeq p_1$. We use this transformation $\times id$ to show that
$b \simeq b' = (p_1, d)$.
Now we consider the equivalence $(p_1, m)  \circ b' \simeq id$. Here we have,
$$(p_1, m) \circ (p_1, d) = (p_1, m \circ (p_1, d)) \simeq id = (p_1, p_2) $$
restricting to $G = G \times \{ 1\} \subseteq G \times G$, this gives a natural isomorphism $m(x, d(x, 1)) \simeq 1$. You can take $i(x) = d(x,1)$, and we have $x i(x) \cong 1$.
We also have
$$(p_1, d) \circ (p_1, m) = (p_1, d \circ (p_1, m)) \simeq (p_1, p_2) $$
which gives a natural isomorphism, $ d(x, xy) \simeq y$ (writing $m(x,y) = xy$).
Thus we have,
$$d(x,y) \simeq d(x,1 y) \simeq d(x, x i(x) y) \simeq i(x) y, $$
which is the formula you were after. So we can replace $d(x,y)$ with $m(i(x), y)$ to get a third inverse functor b''. Note that this doesn't mean that we have a strict 2-group, just that we can define the inverse functors and difference functors  you asked about.
Notice also that we didn't really use anything about G being a 1-category as opposed to an n-category (except the associator and unitors) so this argument generalizes to the n-group setting basically verbatim.

A: I think the answer is no, but cannot give a counterexample off hand. What is true is that there will be an equivalent monoidal category such that the corresponding functor $b$, does have the property. Any 2-group is equivalent to a strict 2-group (which can be assumed to come from a crossed module). What would be an interesting subsidiary question would be can the structure be `deformed' to one which is strict.  (Deformed in the sense of a deformation theory.)


text:
Q: connected to database but can't getting data result method throwing nullpointer exception i am using wildfly 10.1.0 my project is running well but when i try to validate username and password by retrieving data from database i get null pointer exception as follow.

Caused by: java.lang.NullPointerException
 at com.revguru.crs.web.user.controller.UserLoginController.authenticate(UserLoginController.java:86)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at com.sun.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:181)
 at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
 at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
 at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
 at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
 at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
 at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
 at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
 at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
 ... 50 more

when i ping my database is shows me it is connected but still my UerLoginController class having securityService.authenticate(username,password) method call throws null pointer exception
UerLoginController class

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.TimeZone;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import com.revguru.crs.core.entity.ht.HotelDataObject;
import com.revguru.crs.core.service.exception.HSDServiceException;
import com.revguru.crs.core.service.sc.SecurityService;
import com.revguru.crs.core.util.HSDServiceConstants;
import com.revguru.crs.security.entity.FeatureDataObject;
import com.revguru.crs.security.entity.HotelUserDataObject;
import com.revguru.crs.security.entity.RoleDataObject;
import com.revguru.crs.security.entity.UserDataObject;
import com.revguru.crs.web.common.vo.CommonGlobalBean;
import com.revguru.crs.web.constants.HSDWebConstants;
import com.revguru.crs.web.hotel.controller.GeneralHotelController;
import com.revguru.crs.web.hotel.delegate.HotelDelegate;
import com.revguru.crs.web.user.delegate.UserDelegate;
import com.revguru.crs.web.user.vo.Menu;
import com.revguru.crs.web.user.vo.MenuItem;
import com.revguru.crs.web.user.vo.UserInformation;
import com.revguru.crs.web.user.vo.UserLogin;
import com.revguru.crs.web.utils.Util;

public class UserLoginController {

 private FacesContext facesContext = FacesContext.getCurrentInstance();
 HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
 private SecurityService securityService = new SecurityService() ;

 public void setSecurityService(SecurityService securityService) {
  this.securityService = securityService;
 }

 public SecurityService getSecurityService() {
  return this.securityService;
 }

 /**
  * Authenticate the User
  * @return
  */
 public String authenticate() {

  if(session.getAttribute("menus") != null) {
   session.removeAttribute("menus");
  }

  if (session.getAttribute("CommonGlobalBean") != null) {
   session.removeAttribute("CommonGlobalBean");
  }

  CommonGlobalBean commonGlobalBean = new CommonGlobalBean();
  commonGlobalBean.setTimeZone(TimeZone.getDefault().getID());

  UserLogin userLogin = new UserLogin();
  userLogin = (UserLogin)session.getAttribute("UserLogin");

  String username = userLogin.getUserName();
  String password = userLogin.getPassword();

  UserInformation userInformation = null;

  if (userLogin != null) {
   if (securityService.authenticate(username,password)) {
    Util.log("Get User Object by Email");
    UserDataObject userDataObject = securityService.getUserObjectByEmail(userLogin.getUserName());
    Util.log("User name : "+userDataObject.getUserFirstName());
    userInformation = (UserInformation)session.getAttribute("UserObject");
    if (userInformation != null) {
     session.removeAttribute("UserObject");
    }
    userInformation = getUserInformation(userDataObject);
    session.setAttribute("UserObject", userInformation);

    if(!checkUserAsHotelRole(userInformation)) {
     Util.log("User does not have hotel role.");
     Util.reportError(facesContext, "login_user_not_valid_password", null);
    }

this is my method definition

public boolean authenticate(String email, String password) {
  log.info("Authenticating : " + email);
  UserDataObject user = new UserDataObject();
   user=getUserObjectByEmail(email);
  if (user == null) {
   log.info("User does not exist for email id :" + email);
   return false;
  }
  return checkPassword(password, user.getPassword());
 }

A: The following lines are problematic:
UserLogin userLogin = new UserLogin();
userLogin = (UserLogin)session.getAttribute("UserLogin");

In the first line, you assign a reference to a new UserLogin object to the variable userLogin.
In the second line, you replace that reference with a reference to the object present in the session under the key "UserLogin".
If the session does not contain an attribute with the key "UserLogin", the result would be null, leading to a NullpointerException in the line right below it: String username = userLogin.getUserName();.
As for the place where you indicated the issue would have been: assuming neither username nor password are null, the issue would be inside authenticate(String, String), of which you have not provided us with the code.


text:
Q: Fancybox 2.0 close button to the top corner of the window How do I move the close button of Fancybox 2.0 from the top corner of the dialog box to the top corner of the screen?  I asked on the FB Google Group and had no response, so thought to ask here, since a lot of FB questions are apparently being asked here, especially for FB 2.0.

A: Change style for close button from:
#fancybox-close {
    position: absolute;
    top: -15px;
    right: -15px;
    ...
}

to something like:
#fancybox-close {
    position: fixed;
    top: 15px;
    right: 15px;
    ...
}

Though, in that case close button won't move even if you scroll the page.
Have a look, for example, at this for more information about CSS positioning.


text:
Q: storing one line of a text file as an array python i have a text file which is set out like:
a 1 1
b 1 1
c 1 1
d 1 1
e 1 1
f 1 1

and i was hoping to out put it like ["a", "1", "1"] etc however it currently outputs as
[a 1 1\n]
[b 1 1\n]
[c 1 1\n]
[d 1 1\n]
[e 1 1\n]
[f 1 1\n]

my code is
import csv
tname = input("player 1 enter your team name ")
x = "./" + tname + ".txt"
with open (x, "r") as r:
    reader = csv.reader(r)
    for row in r:
        spec = [row]
        print (spec)

A: There is some ambiguity what is the desired result. So three possible answers:
with open('somefile.txt', 'r') as f:
    for row in f:
        print(row.strip().split())

# -> ['a', '1', '1']
     ['b', '1', '1']
     ['c', '1', '1']
     ['d', '1', '1']
     ['e', '1', '1']
     ['f', '1', '1']

with open('somefile.txt', 'r') as f:
    print([row.strip().split() for row in f])

# -> [['a', '1', '1'],
      ['b', '1', '1'],
      ['c', '1', '1'],
      ['d', '1', '1'],
      ['e', '1', '1'],
      ['f', '1', '1']]

with open('somefile.txt', 'r') as f:
    print([item for row in f for item in row.strip().split()])

# -> ['a', '1', '1', 'b', '1', '1', 'c', '1', '1', 'd', '1', '1', 'e', '1', '1', 'f', '1', '1']

A: No need to use the csv module, just read all the lines in turn, split them by spaces and append them to your output list:
with open('input.txt', 'r') as f:
    lines = f.readlines()

output = []
for line in lines:
    output = output + line.split()

print(output)

This gives you:
['a', '1', '1', 'b', '1', '1', 'c', '1', '1', 'd', '1', '1', 'e', '1', '1', 'f', '1', '1']


text:
Q: select all X type of elements but not the same type again inside them for example, if there are several DIV elements, one inside another. lets say 3 levels.
how would you go about selecting only the 2nd level of Divs, not knowing how deep they might be,
and not able to give more classes?
// html example of a possible DOM

selectors overview:
div.level1 > div => (BAD) would return nothing because Div is inside a
div.level1 > a > div => (BAD) the 2nd level div's might be deeper, and the exact xpath should not be written
is there some kind of CSS selector combinations that would return 'find the elements but never go find inside them', so then div.level1 div will return only the 2nd-level Divs but not the ones that might be inside them (something of that sort). I find this a very powerful thing to have.

A: Not likely.
But what you can do is set desired property on the level >= 2 (div.level1 div) and negate it on all the divs below level 2 (div.level1 div div).
Of course, there's always an option of using different classes for each level.

A: Your first selector looks absolutely fine. Just check out this example CSS:

Only the second level DIV is matched as it is a direct child of the div.level1.
BTW: Your HTML makes no sense at all. DIVs inside of inline elements are bad. But links inside of links are even worse :)


text:
Q: Operations on timestamp with nanoseconds in Python I have this timestamp with 9 decimal digits:
2019-08-05T00:01:23.486000061Z

I need to subtract to this timestamp a quantity like this (in seconds):
1.069422832374933

I can do this with "normal" timestamps (with 6 decimal digits) with datetime, but how can i do that in this particular case? As you can see, i also need to truncate the quantity because it has extra digits which i don't need.
Edit: i realized i can truncate the quantity using round(float_number, 9)
Edit: i need to obtain a timestamp with the same shape (9 digits for seconds)

A: I am not sure of what you wanted. If it is to present this timestamp with 6 digits for seconds and no further calculation you can treat everything as a regular expression.
import re

givenDate = '2019-08-05T00:01:23.486000061Z'
exp       = '(\d{4})-(\d{2})-(\d{2})?T(\d{2}):(\d{2}):(\d{2}).(\d{6})'

newDate = re.search(exp, givenDate).groups()
print(newDate[0]+'-'+newDate[1]+'-'+newDate[2]+''+newDate[3]+':'+newDate[4]+':'+newDate[5]+'.'+newDate[6])

The output is:
2019-08-0500:01:23.486000
To obtain 9 digits is as easy as doing this:
exp       = '(\d{4})-(\d{2})-(\d{2})?T(\d{2}):(\d{2}):(\d{2}).(\d{9})'


text:
Q: Android studio failed to build tools after updating to 3.0 from 2.3 stable channel I just updated my android studio from 2.3 to 3.0 from stable channel.
But I was getting this error
Failed to find Build Tools revision 26.0.2 Install Build Tools 26.0.2 and sync project

I do tried to install this but still failing to resolve

A: Open SDK manager to check installed buildtool revision version:

for example, I have version 27.0.3 installed.
Then add buildToolsVersion '27.0.3' in build.gradle:

A: You can install any version of build tools manually.
Please go to Preferences > Appearance & Behavior > System Settings > Android SDK. Then select "SDK Tools" pane and be sure to check "Show package details" below the list. Then you can install additional versions of Android SDK Build-Tools. Voila!


text:
Q: Android Google maps overlay balloon/annotation like iPhones I've got overlay icons all over my map activity that each need to pop up a dialog when tapped.
Currently I just display Androids default AlertDialog.
I was hoping to instead be able to display a small balloon like iPhones 'annotation', see picture below.
Is there a simple way of achieving this in Android? Preferably without using some kind of external library?

Thanks heaps

A: Having gone down the "no library" route, you will probably want to use something like Mapview Balloons by Jeff Gilfelt. You can incorporate the source OR use as a library.


text:
Q: Qual a melhor forma de armazenar dados localmente? Eu preciso desenvolver um sistema web para rodar sem um servidor, o sistema em questão apenas irá salvar os dados de clientes e agendamentos. Eu não gostaria de utilizar um servidor de banco de dados, pois se torna chato o cliente ter que iniciar o server sempre que for utilizar o sistema. Por isso desejo salvar sem utilizar um server. Eu considerei utilizar JSON mas não me parece muito viável, e também considerei a API IndexedDB, mas ela parece ser muito complicada. Existe alguma outra forma em que o cliente apenas precise abrir o navegador e utilizar o sistema offline ?

A: Olha, creio que não seja viável, por alguns motivos. Eu conheço 3 formas de armazenar dados localmente:

*

*No localstorage do navegador

*Em um arquivo .csv

*Em um banco de dados

No localstorage é inviável armazenar esse tipo de dado porque existe um limite de armazenamento que é extremamente baixo(No Chrome acho que é 10mb).
No arquivo .csv(tabela do excel) você também teria que ter um servidor rodando a aplicação e também da muito trabalho.
A melhor opção é você criar um banco de dados! e o cliente não vai precisar abrir o banco toda vez que for utilizar! o banco inicia automaticamente junto com o SO como um processo de segundo plano. Você pode utilizar o host local do cliente pra hospedar o servidor em um container Docker que roda sozinho quando ele liga o computador. (Nunca fiz isso, mas tenho quase certeza que funciona, pesquisa um pouco sobre).


text:
Q: Error in VF page as : Unknown property 'QuoteStandardController.Student' ,Apex class as :Error unexpected token: 'public' at line 40 column 0 Can any one help me out of this Error and Suggest me on the Code written .
I have created a vf page on Quote Object ,which should be generated in PDF .I have other objects which are has a relation ship on quote object such as quotelineitems , opportunity , account and few object which does not have a relationship on quote object such as student.Now i would like to get display all the field in a table .So written a wrapper class based on the controller .
ANY HELP IS VERY MUCH APPRECIATED

*

*Error in VF page as : Unknown property 'QuoteStandardController.Student' ,

*Apex class as :Error Error: Compile Error: unexpected token: 'public' at line 40 column 0

*How to get the rows and colums in a table using html.it just displays the field names ,but not in a table format

*How to query the Product2 field on Quotelineitems and RecordType on Account obj.

Here is my VF Code and the class
<apex:page standardController="Quote" extensions="QuoteContentController"
        applyHtmlTag="false" renderAs="PDF" showheader="false">

        <link href="{! $Resource.advancedpdfresource }" rel="stylesheet" type="text/css"/>

RFQ Information {!Quote.Name}

General Inforamtion

            Customer Name
            <apex:outputField value="{!Quote.Name}"/>

            Price
            <apex:outputField value="{!Quote.Totalprice}"/>

            Subtotal
            {!Quote.Subtotal}

            BillingName
            {!Quote.BillingName}

            Opportunity Name
            <apex:outputField value="{!Quote.Opportunityid}"/>

QuotelineItems

                PartNumbers
                Price
                Quantity
                EndcustomerPrice
                TotalPrice

            <apex:repeat value="{!Quote.QuotelineItems}" var="qli">

                <apex:outputText value="{!qli.Product2}"/>
                <apex:outputText value="{!qli.Unitprice}"/>
                <apex:outputField value="{!qli.Quantity}"/>
                <apex:outputField value="{!qli.Description}"/>
                <apex:outputField value="{!qli.TotalPrice}"/>

            </apex:repeat>

Justification and Account

                RFQ Justification
                RecordType
                no_of_opportunities
                Description
                pi_score

            <apex:repeat value="{!Quote.Account}" var="a">

                <apex:outputText value="{!a.name}"/>
                <apex:outputText value="{!a.RecordType}"/>
                <apex:outputField value="{!a.no_of_opportunities__c}"/>
                <apex:outputField value="{!a.Description}"/>
                <apex:outputField value="{!a.pi_score__c}"/>

            </apex:repeat>

Student

                Studentname
                StudentDOB
                StudentSkills
                StudentLocation
                StudentResult

            <apex:repeat value="{!Student}" var="std">

                <apex:outputText value="{!std.name}"/>
                <apex:outputText value="{!std.StudentDOB__c}"/>
                <apex:outputField value="{!std.StudentSkills__c}"/>
                <apex:outputField value="{!std.StudentLocation__c}"/>
                <apex:outputField value="{!std.StudentResult__c}"/>

            </apex:repeat>

</apex:page>

Apex Class :
public with sharing class QuoteContentController {

    public QuoteContentController(ApexPages.StandardController controller) {

    }

//public  QuoteContentcontroller()
//public  QuoteLineItem(get;set;)
// Creating lists for the object Quote ,Quotelineitems ,Account and opportunity & opportunity forecast(wrapper class).
list<Quote> q = new list<Quote>();
list<QuoteLineItem> quoteLineItems = new list<QuoteLineItem>();
list<Account> account = new list<Account>();
list<Opportunity>opportunity = new list<Opportunity>();

// Creating List for Wrapper class

public List<wrapper> Student = new List<wrapper>();

// Get method calling from PageBlockTable and return the list of wrapper to Table

public List<wrapper> Student() {

  q = [select id , name ,BillingName from Quote];
 quoteLineItems = [select id, UnitPrice ,Quantity ,Description ,TotalPrice from QuotelineItem ];
 account =[select id , name ,  description from Account];
 opportunity =[select id , name from Opportunity];

 for(Integer i=0;i<q.size();i++){
Student.add(new wrapper(q[i].name,q[i].id,q[i].BillingName,
                        quoteLineItems[i].id,quoteLineItems[i].Product2,quoteLineItems[i].UnitPrice,quoteLineItems[i].Quantity,quoteLineItems[i].Description,quoteLineItems[i].TotalPrice,
                        account[i].id,account[i].name,account[i].recordtype,account[i].Description,
                        opportunity[i].id,opportunity[i].name));

}

return Student;

// Wrapper Class Construction

public  class wrapper{

public String Qname{get;set;}

public String QBillingName{get;set;}

public String QLIProduct2{get;set;}

public String QLIUnitprice{get;set;}

public String QLIQuantity{get;set;}

public String QLIDescription{get;set;}

public String QLITotalprice{get;set;}

public String AName{get;set;}

public String Arecordtype{get;set;}

public String ADescription{get;set;}

public String OppName{get;set;}
// Wrapper class constructor

public wrapper(String Qname,String QBillingName,String QLIProduct2,String QLIUnitprice,String QLIQuantity,String QLIDescription,String QLITotalprice,String AName,String Arecordtype,String ADescription,String OppName){

this.Qname=Qname;

this.QBillingName=QBillingName;

this.QLIProduct2=QLIProduct2;

this.QLIUnitprice=QLIUnitprice;

this.QLIQuantity=QLIQuantity;

this.QLIDescription=QLIDescription;

this.QLITotalprice=QLITotalprice;

this.AName=AName;

this.Arecordtype=Arecordtype;

this.ADescription=ADescription;

this.OppName=OppName
}

}


text:
Q: How to get check box value of a attribute i want to get value of attribute value of checkboxes.
my code is giving me undefined
$('#mytable').find('tr').each(function () {
            var row = $(this);

            if ( row.find('input[type="checkbox"]').is(':checked') ) {
                alert( $(this).attr("b_partner_id") );
            }
        });

A: this is referring to the tr element in the if block, since your b_partner_id attribute is not present in the tr element you are getting undefined.
Instead you need to get the attribute value using the checkbox reference
$('#mytable').find('tr').each(function () {
    var row = $(this),
        $check = row.find('input[type="checkbox"]');

    if ($check.is(':checked')) {
        alert($check.attr("b_partner_id"));
    }
});


text:
Q: Transformar getElementsByClassName em elementRef Fiz um codigo e gostaria de transformar meu getElementsByClassName e elementRef, abaixo mostro como fiz e como tentei ajustar
tabContent = this.tabContent.nativeElement.innerHTML;
    for (i = 0; i < tabContent.length; i++) {
      tabContent[i].style.display = 'none';
    }
    tablinks = document.getElementsByClassName('tablinks');
    for (i = 0; i < tablinks.length; i++) {
      tablinks[i].className = tablinks[i].className.replace(' active', '');
    }

A: Para você pegar qualquer elemento Html na sintaxe nativa do JavaScript e transformar para Angular você pode utilizar o decorator @ViewChild() e a tipagem da variável como sendo do tipo ElementRef o que lhe possibilita ter acesso a todas as propriedades daquele elemento através do atributo nativeElement:
No seu caso aí a variável tabContent já é um @ViewChild() então tablinks seguiria a mesma lógica:
// Faz os imports
import { Component, ElementRef, ViewChild } from '@angular/core';

// decalara a variável e o tipo como ElementRef
@ViewChild('tablinks', {static, false}) tablinks: ElementRef;

tabContent = this.tabContent.nativeElement.innerHTML;
for (i = 0; i < tabContent.length; i++) {
  tabContent[i].style.display = 'none';
}
for (i = 0; i < tablinks.length; i++) {
  tablinks[i].className = tablinks[i].className.replace(' active', '');
}

Dependendo da versão do Angular que estiver utilizando (acho que do 7 para cima) é necessário declarar um objeto declarando se a instância da variável é estática ou não: {static, true}


text:
Q: Migrate SharePoint 2010 rbs to SharePoint 2013 sql We have a SharePoint 2010 Farm using rbs and would like to migrate it to a SharePoint 2013 Farm using sql. Can this be done by using the detach method on the WSS_Content database or is there another approach?

A: You cannot migrate directly a DB with RBS enabled, You have to move all the files inside the DB then you can use backup & restore method.
The steps you need to follow are:

*

*Stop Content Db to use RBS and Move in all the Files inside the DB
from Blob Folder.

*Verity that files are inside Sql DB by running query.

*Test by uploading file to Site and verify it stores in sql DB.

*backup and restore the DB to your new SharePoint 2013 environment.

*Test it.

*Configure the RBS on SharePoint 2013 Farm after upgrade. link to the
planning for RBS :
https://technet.microsoft.com/en-us/library/ee748638.aspx
http://sharepoint-community.net/forum/topics/sharepoint-2010-to-2013-upgrade-migration-with-rbs
http://www.quercussolutions.com/blog/index.php/troubleshooting-sharepoint-2013-upgrade-issue-content-database-cannot-be-upgraded-due-to-use-of-the-obsoleted-external-binary-storage-feature/

A: I know this is old, but I wanted to post my solution.
We were able to migrate the databases with the RBS still attached. I was able to go Microsoft RBS Library to download the library on each 2013 WFE server. NOTE:  Do not run the configuration wizard it installs features that are not compatible with SharePoint 2013. Instead Save the file to the location C:\RBSClient (I created the location)
Run the Command Prompt as an Administrator and paste the following code
cd c:\RBSClient
First
msiexec /qn /lvx* rbs_install_log.txt /i RBS_amd64.msi TRUSTSERVERCERTIFICATE=true FILEGROUP=PRIMARY DBNAME="<database>" DBINSTANCE="<DBSERVER>" FILESTREAMFILEGROUP=RBSFilestreamProvider FILESTREAMSTORENAME=<FileStreamName>

Second
msiexec /qn /lvx* rbs_install_log.txt /i RBS_amd64.msi DBNAME="<database>" DBINSTANCE="<DBServer>" ADDLOCAL=Client,Docs,Maintainer,ServerScript,FilestreamClient,FilestreamServer

msiexec /qn /lvx* rbs_install_log.txt /i RBS_amd64.msi DBNAME="<Database>" DBINSTANCE="<DBserver>" ADDLOCAL=Client,Docs,Maintainer,ServerScript,FilestreamClient,FilestreamServer

NOTE:  The first code is the initial install of the RBS Client and should only be ran once. The second code is for each other content database. This is done on each server.
After the library is installed on each Web Server Enable RBS for each content database on just one server by running the SharePoint 2013 Management Shell application as an administrator and pasting the following code.
$cdb = Get-SPContentDatabase <database>
$rbss = $cdb.RemoteBlobStorageSettings
$rbss.Installed()
$rbss.Enable()
$rbss.SetActiveProviderName($rbss.GetProviderNames()[0])
$rbss

Make sure the app pool account has dbOwner, at this point documents should be able to open using the filestream provider. To migrate them to SQL database use the following code.
$rbs=(Get-SPContentDatabase <database>).RemoteBlobStorageSettings
$rbs.GetProviderNames()
$rbs.SetActiveProviderName("")
$rbs.Migrate()


text:
Q: MySQL Заполнение datagridview Подскажите пожалуйста как заполнить датагрид только со своими колонками.
На данном этапе такая реализация
private void BindMySqlData()
{
    Task.Factory.StartNew(() =>
    {
        try
        {
            const string @select = "SELECT * FROM customers;";
            _mySqlConnection = new MySqlConnection(Settings.Default.MySQLConnectionString);
            _mySqlConnection.Open();

            var mySqlDataAdapter = new MySqlDataAdapter();
            var mySqlDataTable = new DataTable();

            mySqlDataAdapter.SelectCommand = new MySqlCommand(select, _mySqlConnection);
            mySqlDataAdapter.Fill(mySqlDataTable);

            var mySqlBindingSource = new BindingSource { DataSource = mySqlDataTable };

            LoggerHelper.Debug("Update user UI - DataGrid Bind running in thred!");

            return mySqlBindingSource;

        }
        catch (MySqlException mysql)
        {
            LoggerHelper.Error("Error connection to DB!", mysql);
            return null;
        }
        finally
        {
            _mySqlConnection?.Close();
        }
    }).ContinueWith(x =>
    {
        //dataGridView1.DataSource = x.Result;
        BeginInvoke((Action)(() =>
        {
            dataGridView1.DataSource = x.Result;
            LoggerHelper.Debug("Update user UI - DataGrid Bind!");
        }));
    }, TaskScheduler.FromCurrentSynchronizationContext());
}

Заполняет все нормально, но суть в том, что у меня есть свои колонки и не всю инфу я хочу показывать юзеру.

A: Так и сделай в запросе нужные поля, плюс сразу и название выведи.
например так:
SELECT `id` as "Номер записи",`name` as "Имя чего-то там",`date` as "Дата",`pasport` as "Данные паспорта" from customers

Плюс колонки сами назовутся как укажешь в запросе.

A: Можно прятать ненужные колонки, например: dataGridView1.Columns[0].Visible = false;


text:
Q: Unable to AutoLoad Class using Composer I have a project structure that looks like:
app/
app/models/
app/controllers/
app/views/
public/
vendor/
composer.json

Inside of app/controllers/IndexController.php, I have:
require '../vendor/autoload.php';

use MyApp\Models\Test;

class IndexController {

    public function __construct() {
       $t = new Test(); // can't be found
    }
}

Here's my composer.json:
{
  "require": {
    "aws/aws-sdk-php": "*",
  },
  "autoload": {
    "psr-0": {
        "MyApp": "app/"
    }
  }
}

After updating composer.json, I run composer.phar update to update the generated autoload files.
FYI - I'm not using any type of MVC framework. This is just a custom lightweight structure I like to use for small projects.
How do I fix my project so that I can autoloaded classes from my models folder and use them properly in my controllers?

A: If you use psr-0 autoloading, then you need to follow the psr-0 spec. That means, if you specify "MyApp": "app/", the class MyApp\Models\Test must be in app/MyApp/Models/Test.php.