text:
Q: Having trouble importing middleware classes in App Engine / Django Trying to get facebook connect to work on app engine, and so I'm following these instructions:
http://www.slideshare.net/mrtrosen/lab305-django-facebook-connect-integration-example
One of the steps requires me to add to my middleware_classes, and so I've added the following to settings.py (copied from slide 18 in the presentation above):
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'facebook.djangofb.FacebookMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'facebookconnect.middleware.FacebookConnectMiddleware',
    )

However, when I view my app locally (which was working before adding this to settings.py), I get the following error:

ImproperlyConfigured: Error importing
middleware facebook.djangofb: "No
module named facebook.djangofb"

However, when I go to the terminal, I am able to run python and when I type "import facebook.djangofb" I do not get any error.
FYI, the facebook package is in /Library/Python/2.6/site-packages.
Any ideas as to why this might be happening? I've been stuck on this for a while so any help would be greatly appreciated.
Thanks!

A: Google App Engine uses python 2.5 runtime I believe, thus you will have either move the facebook directory into the project as suggested above or move it over to the 2.5 site-packages if you have python 2.5 installed as well.

A: All modules must reside under your app's folder hierarchy. Be sure to also add the required paths to sys.path in your app request handlers.
The sys.path should be updated to something along the lines of:
root = os.path.split(__file__)[0]
sys.path.insert(0, os.path.join(root, 'folder1'))
sys.path.insert(0, os.path.join(root, 'folder2'))

where folderX is contained under the app folder. This "path adjustment" should be done in each "request entry point script" in the application.


text:
Q: Work around for bug in pgf when used with htlatex? EDIT The PGF team reported that this bug was fixed on 2018-12-29
There is a bug in pgf that stops it playing nicely with tikz/pgf. As discovered by michal.h21, the solution is a simple a one line change to pgfsys-tex4ht.def. This bug was reported to the pgf team in 2014, together with a patch, but it remains unfixed as of TeXLive 2017.
Question
Is there a way that I can patch the pgf file pgfsys-tex4ht.def from within LaTeX?
It is possible to fix the problem by editing/replacing the system version of pgfsys-tex4ht.def. What I would like, however, is a way of patching this from inside LaTeX because I want to be able to work around this problem in a package. (In an ideal world, the pgf team would just apply Michael's patch, and so fix the problem once and for all, but they just don't seem to be interested in doing this...)
The actual error that occurs is:
! Undefined control sequence.
\pgfsys@svg@newline ->\Hnewline

l.190   \pgfusepathqfill}

and the fix is to replace the line \def\pgfsys@svg@newline{\Hnewline} in
pgfsys-tex4ht.def with
\def\pgfsys@svg@newline{^^J} %% corrected

I have tried patching this line in many ways, in latex files, my class file, in cfg files and mk4 files. Sadly, nothing that I have tried fixes the problem. For reasons I don't understand, once the pgfsys-tex4ht.def file has been read it is really hard to convince htlatex to use any other definition of \pgfsys@svg@newline or \Hnewline.
To see the bug in action, compile the following really simple MWE with htlatex:
\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
  \draw(0,0)--(10,0);
\end{tikzpicture}

\end{document}

The problem only occurs with htlatex and friends -- the MWE compiles without issue using (pdf)latex.

A: This situation is quite unfortunate. The pgfsys-tex4ht.def driver is selected automatically by TikZ when the document is compiled with tex4ht. You can create alternative driver, like pgfsys-tex4ht-alt.def:
\input pgfsys-tex4ht.def
\def\pgfsys@svg@newline{^^J}

but the problem is that the alternative driver cannot be defined in the .cfg file, because it is interpreted after the document preamble was executed. You must put it either to the TeX file:
\documentclass{article}
\def\pgfsysdriver{pgfsys-tex4ht-alt.def}
\usepackage{tikz}

\begin{document}

 \begin{tikzpicture}
   \draw(0,0)--(10,0);
 \end{tikzpicture}

\end{document}

Or use one trick in the .mk4 file:
settings.packages = settings.packages ..'\\def\\pgfsysdriver{pgfsys-tex4ht-alt.def}'

You can load additional packages or define custom commands in the settings.packages variables in the mk4 build file.
Edit 2017/11/11:
Another possibility is to use dvisvgm to generate the SVG file. We can use the built-in feature of tex4ht to convert any piece of TeX code inside a \Picture* ... \EndPicture environment to picture and the fact that TikZ has support for dvips commands, which are supported by dvisvgm.
The alternative pgfsys-tex4ht.def:
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/systemlayer/pgfsys-tex4ht.def,v 1.25 2013/08/06 17:46:08 tantau Exp $

% Driver commands for tex4ht

%
% Load common pdf commands:
%
  %\input pgfsys-dvisvgm.def
  \input pgfsys-dvips.def

%
% tex4ht-specific stuff:
%

\newcount\pgf@sys@svg@picnum

% configure the output picture format to svg
\AtBeginDocument{
  \Configure{Picture}{.svg}
}

% Make the code inserted by tex4ht configurable

\NewConfigure{tikzpicture}{2}
\Configure{tikzpicture}{%
  % \ifvmode\IgnorePar\fi\EndP%\HtmlParOff
  \Picture*{}
}{\EndPicture}

\let\orig@pgfsys@begin\pgfsys@beginpicture
\let\orig@pgfsys@end\pgfsys@endpicture
\def\pgf@sys@postscript@header#1{{\special{! #1}}}
\def\pgfsys@beginpicture{%
  \bgroup
  \csname a:tikzpicture\endcsname
  \pgf@sys@postscript@header{
    /pgfsc{}bind def% stroke color is empty by default
    /pgffc{}bind def% fill color is empty by default
    /pgfstr{stroke}bind def%
    /pgffill{fill}bind def%
    /pgfeofill{eofill}bind def%
    /pgfe{a dup 0 rlineto exch 0 exch rlineto neg 0 rlineto closepath}bind def% rectangle
    /pgfw{setlinewidth}bind def% setlinewidth
    /pgfs{save pgfpd 72 Resolution div 72 VResolution div neg scale
      magscale{1 DVImag div dup scale}if
      pgfx neg pgfy neg translate pgffoa .setopacityalpha}bind def% save
    /pgfr{pgfsd restore}bind def %restore
    userdict begin%
    /pgfo{pgfsd /pgfx currentpoint /pgfy exch def def @beginspecial}bind def %open
    /pgfc{newpath @endspecial pgfpd}bind def %close
    /pgfsd{globaldict /pgfdelta /delta where {pop delta} {0} ifelse put}bind def% save delta
    /pgfpd{/delta globaldict /pgfdelta get def}bind def % put delta
    /.setopacityalpha where {pop} {/.setopacityalpha{pop}def} ifelse % install .setopacityalpha
    /.pgfsetfillopacityalpha{/pgffoa exch def
      /pgffill{gsave pgffoa .setopacityalpha fill 1 .setopacityalpha newpath fill grestore newpath}bind def
      /pgfeofill{gsave pgffoa .setopacityalpha eofill 1 .setopacityalpha newpath eofill grestore newpath}bind def}bind def
    /.pgfsetstrokeopacityalpha{/pgfsoa exch def /pgfstr{gsave pgfsoa .setopacityalpha stroke grestore newpath}bind def}bind def
    /pgffoa 1 def
    /pgfsoa 1 def
    end
  }%
  \orig@pgfsys@begin%
}%

\def\pgfsys@endpicture{%
  % Save the bounding box
  %\printdim%
  \orig@pgfsys@end%
  \csname b:tikzpicture\endcsname%
  \egroup
  \par% FIXME : was '\Par' but that seems to be undefined!?
}%

\endinput

%%% Local Variables:
%%% mode: latex
%%% End:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel DB::RAW() NOT IN not working Hello I have 5 records on cards table,
and when I use not in on phpmyadmin it's working
SELECT id FROM cards WHERE id NOT IN (1,2)

but when I used not in on Laravel it's not working, and it only bind on 1st
$test = "1,2";

$cards = DB::SELECT(DB::RAW("SELECT id FROM cards WHERE id NOT IN (:exception)"), ['exception'=>$test]);

echo "<pre>";
var_dump($cards);
echo "</pre>";

I'm using this guide to avoid SQL Injection:
http://fideloper.com/laravel-raw-queries

A: DB::table('cards')->whereRaw('id NOT IN(".$test.")')->get();

Please try this code instead.


text:
Q: How do I find the location of the file via inspect element? So I want to edit a small thing in my website and I can change it via Inspect Element without a problem, but I can't find the location of the file in order to change it. That's the website: gesher-jds.org/giving
I tried everything..I searched in all the folders and I couldn't find the small thing that I need to edit. I want to change: give-gateway-offline-2727-1 to give-gateway-offline-2727-2
I tried to find it all day and I couldn't..
<input type="radio" name="payment-mode" class="give-gateway" id="give-gateway-offline-2727-2" value="offline">

A: Id generation logic seems dynamically generating like,
id = "give-gateway-offline-" + id-number
Where id-number may be calculated to 2727-1.
Instead of searching the codebase directly for "give-gateway-offline-2727-1", try to search with sub strings. Eg. give-gateway-offline

A: In your case Id is dynamically generated.
use visual code for searching and instead of searching direct id you can search other related tag like class="give-gateway" and find the where logic is write for dynamic ID build and change it.


text:
Q: Need a handler. Pass the with: keyword argument or provide a block Recently I update my app from Ruby version 2.6.1  to 3.0.1 & I'm using rbenv as a version manager.
but when I try to run the rails server I got an error
=> Booting Puma
=> Rails 6.1.3 application starting in development
=> Run `bin/rails server --help` for more startup options
Exiting
/home/humayun/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activesupport-6.1.3/lib/active_support/rescuable.rb:56:in `rescue_from': Need a handler. Pass the with: keyword argument or provide a block. (ArgumentError)
    from /home/humayun/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/will_paginate-3.1.8/lib/will_paginate/railtie.rb:67:in `rescue_from'
    from /home/humayun/umerfarooq/Alchemy/app/controllers/application_controller.rb:2:in `<class:ApplicationController>'
    from /home/humayun/umerfarooq/Alchemy/app/controllers/application_controller.rb:1:in `<main>'

I just read Here about the function which is causing an error on line 56.
applciation_controller.rb
 rescue_from Exception, with: :handle_exception
 protect_from_forgery prepend: true, with: :exception
 before_action :configure_permitted_parameters, if: :devise_controller?
 before_action :initialize_api

  def not_found
    raise ActionController::RoutingError.new('Not Found')
  end

 def handle_exception(exception = nil)
    return render_404 if [ActionController::RoutingError, ActiveRecord::RecordNotFound].include?(exception.class)
     render_500
 end

I think this is because of depreciation.
can anyone please tell me how to handle these errors?

A: your handle_exception probably will need a block that render a view or returns a status
as mentioned in the error in app/controllers/application_controller.rb:2 you probably have a rescue_from without an error or a handler you need to follow any of below syntax
class ApplicationController < ActionController::Base
  rescue_from User::NotAuthorized, with: :deny_access # self defined exception
  rescue_from ActiveRecord::RecordInvalid, with: :show_errors

  rescue_from 'MyAppError::Base' do |exception|
    render xml: exception, status: 500
  end

  private
    def deny_access
      ...
    end

    def show_errors(exception)
      exception.record.new_record? ? ...
    end
end

as per documentation here https://apidock.com/rails/ActiveSupport/Rescuable/ClassMethods/rescue_from
------- Update:
This is due to the will_paginate gem that you are using that overrides the rescue_from method in your controller alongside the new ruby updates that change the behavior around the keyword attribute
if your base controller include ControllerRescuePatch you might be able to remove it and this will fix it but not sure what will happen to your pagination.
Otherwise, hold off the ruby update until the will_paginate update their code to fix this


text:
Q: How to check if value is valid property in Matlab? Is there a way of checking whether a property value is valid for the given hobject?
I took the 'enable' property below just as an example, my question is for general property, and assuming you don't know all the possible accepted properties values in advance.
% MyBtnObject is a standard push button

% this will be ok
set(MyBtnObject, 'enable', 'on');

% and this will not, but how can I check it?
set(MyBtnObject, 'enable', 'SomeInventedProp');

A: I've found the answer. I can use x = set(MyBtnObject, 'enable') to get the possible values to the enable property, listed as cell array x.
% find buttons
h = findobj('style', 'pushbutton');

% getting all the possible values for 'enable' property for all pushbuttons
% x = set(h, 'enable'), when h is array, will not work
x = arrayfun(@(x)(set(x, 'enable')), h, 'UniformOutput', false);


text:
Q: org.jooq.lambda.tuple - Create Tuples In my project, I need to use org.jooq.lambda.Tuple for mapping fields for simpleflatmapper JdbcMapperFactory:
public static final JdbcMapper<Tuple17<
        Entity1,
        Entity2,
        Entity3,
        Entity4,
        Entity5,
        Entity6,
        Entity7,
        Entity8,
        Entity9,
        Entity10,
        Entity11,
        Entity12,
        Entity13,
        Entity14,
        Entity15,
        Entity16,
        Entity17
        >> MAPPER =
        JdbcMapperFactory
                .newInstance()
                .unorderedJoin()
                .newMapper(
                        new TypeReference<>() {
                        });

But I have only 16 tuples in package org.jooq.lambda.tuple of library org.jooq.jool:0.9.12
My Idea is to avoid writing boilerplate code for my next Tuple17,18,19... etc.
In addition, I have been looking for a long time for a mention of similar, ready-made structures for Jooq, but I could not find it. Also, I can't find any generators of such Tuples.
Can somebody help?

A: If languages cannot abstract over "generic type variable arity," libraries have to work around this by creating types like jOOλ's Tuple[N] types (max(N) = 16) or jOOQ's Record[N] types (max(N) = 22). The upper bound of type safety is arbitrarily chosen. There's no good reason for one or the other number. So, you will inevitably run into the limitation you ran into, eventually.
There are usually tools to nest tuples in order to work around this. I.e. there's no significant difference between the two types below:
Tuple3<A, B, C>
Tuple2<A, Tuple2<B, C>>

If you must use the stack you've started using (jOOλ and SimpleFlatMapper), then I suspect that this is one way to work around the limitation you've encountered. Surely, there are other ways, e.g.

*

*At some point, you can just use an Object[] and waive type safety.

*If you're using jOOQ, you could use nested records already inside of jOOQ / SQL, so you never realistically reach this limit of 16 attributes

The latter suggestion hints at there possibly being a jOOQ-only solution to your underlying problem, which removes the need for the other two libraries. I'm happy to look into that option in a follow-up question.


text:
Q: Why does my browser think that https://1.1.1.1 is secure? When I visit https://1.1.1.1, any web browser I use considers the URL to be secure.
This is what Google Chrome shows:

Normally, when I try to visit an HTTPS site via its IP address, I get a security warning like this:

From my understanding, the site certificate needs to match the domain, but the Google Chrome Certificate Viewer does not show 1.1.1.1:

GoDaddy's knowledgebase article "Can I request a certificate for an intranet name or IP address?" says:

No - we no longer accept certificate requests for either intranet names or IP addresses. This is an industry-wide standard, not one specific to GoDaddy.

(emphasis mine)
And also:

As a result, effective October 1, 2016, Certification Authorities (CAs) must revoke SSL certificates that use intranet names or IP addresses.

(emphasis mine)
And:

Instead of securing IP addresses and intranet names, you should reconfigure servers to use Fully Qualified Domain Names (FQDNs), such as www.coolexample.com.

(emphasis mine)
It's well after the mandatory revocation date 01 October 2016, yet the certificate for 1.1.1.1 was issued on 29 March 2018 (shown in the screenshot above).

How is it possible that all the major browsers think that https://1.1.1.1 is a trusted HTTPS website?

A: English is ambiguous. You were parsing it like this:
(intranet names) or (IP addresses)

i.e. ban the use of numeric IP addresses entirely.  The meaning that matches what you're seeing is:
intranet (names or IP addresses)

i.e. ban certificates for the private IP ranges like 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16, as well as for private names that aren't visible on the public DNS.
Certificates for publicly routable IP addresses are still allowed, just not generally recommended for most people, especially those who don't also own a static IP.

This statement is advice, not a claim that you can't secure a (public) IP address.

Instead of securing IP addresses and intranet names, you should reconfigure servers to use Fully Qualified Domain Names (FQDNs), such as www.coolexample.com

Maybe someone at GoDaddy was misinterpreting the wording, but more likely they wanted to keep their advice simple, and wanted to recommend using public DNS names in certificates.
Most people don't use a stable static IP for their service.  Providing DNS services is the one case where it's truly necessary to have a stable well-known IP instead of just a name.  For anyone else, putting your current IP in your SSL cert would constrain your future options, because you couldn't let someone else start using that IP.  They could impersonate your site.
Cloudflare.com has control of the 1.1.1.1 IP address themselves, and isn't planning to do anything different with it in the foreseeable future, so it makes sense for them to put their IP in their cert.  Especially as a DNS provider, it's more likely that HTTPS clients would visit their URL by number than for any other site.

A: Looks like the Certificate Subject Alt Name includes the IP address:
Not Critical
DNS Name: *.cloudflare-dns.com
IP Address: 1.1.1.1
IP Address: 1.0.0.1
DNS Name: cloudflare-dns.com
IP Address: 2606:4700:4700::1111
IP Address: 2606:4700:4700::1001

Traditionally I guess you would have only put DNS Names in here, but Cloudflare have put their IP Addresses in as well.
https://1.0.0.1/ is also considered secure by browsers.

A: The GoDaddy documentation is mistaken.  It is not true that Certification Authorities (CAs) must revoke certificates for all IP addresses… just reserved IP addresses.
Source: https://cabforum.org/internal-names/
The CA for https://1.1.1.1 was DigiCert, which as of the writing of this answer, does allow buying site certificates for public IP addresses.
DigiCert has an article about this called Internal Server Name SSL Certificate Issuance After 2015:

If you are a server admin using internal names, you need to either reconfigure those servers to use a public name, or switch to a certificate issued by an internal CA before the 2015 cutoff date. All internal connections that require a publicly-trusted certificate must be done through names that are public and verifiable (it does not matter if those services are publicly accessible).

(emphasis mine)
Cloudflare simply got a certificate for their IP address 1.1.1.1 from that trusted CA.
Parsing the certificate for https://1.1.1.1 reveals that the certificate makes use of Subject Alternative Names (SANs) to encompass some IP addresses and ordinary domain names:
deltik@node51 [~]$ openssl s_client -showcerts -connect 1.1.1.1:443 < /dev/null 2>&1 | openssl x509 -noout -text | grep -A1 'Subject Alternative Name:'
            X509v3 Subject Alternative Name:
                DNS:*.cloudflare-dns.com, IP Address:1.1.1.1, IP Address:1.0.0.1, DNS:cloudflare-dns.com, IP Address:2606:4700:4700:0:0:0:0:1111, IP Address:2606:4700:4700:0:0:0:0:1001

This information is also in the Google Chrome Certificate Viewer under the "Details" tab:

This certificate is valid for all of the listed domains (including the wildcard *) and IP addresses.


text:
Q: MYSQL; Update Table A base on join from Table A and Table B Right of the bat, I'm going to say that I believe that this is what I want:
Update multiple rows using select statement. The answer seems to be for what I want to do.
My tables ares as follows. tPatientsIDs contains only two columns: keyid and uid.
tEyeResults contains a column named patientid and a column named puid. The values of patientid match the column uid from tPatientsIDs and puid is empty, having been created by altering the table recently.
All I want to do is set the value puid to the keyid in tPatientIDs that corresponds to the value of the column patientid.
Here is the query I'm using based on the answer on SO:
UPDATE tEyeResults SET puid = tPatientIDs.keyid FROM tPatientIDs WHERE
tPatientIDs.uid = tEyeResults.patientid;

Even though the structure seems Identical to the answer I get the error:
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near 'FROM
tPatientIDs
WHERE tPatientIDs.uid = tEyeResults.patientid' at line 1

A: Use JOIN with your update
UPDATE tEyeResults e
JOIN tPatientIDs p ON p.keyId = e.patientId
SET e.puid = tPatientIDs.keyid

Maybe you need a where clause to only update one patient but I didn't see one in your question


text:
Q: Python Expect Like Behavior to capture /dev/tty (Provide passphrase to ssh / ssh-add) I would like to respond to ssh / ssh-add password prompt when launched using Python subprocess, but since ssh reads password directly from /dev/ttyXX and not stdin, standards PIPEs do not work.
Is there a way to wrap subprocess with a virtual tty that I can control in Python so that I can send a password to the vty programmatically (like Expect seems to be able to do)?  I would rather not use an Expect like module for Python if possible.
    # Does not work, still grabs tty
    my_env = os.environ.copy()
    my_env['SSH_ASKPASS'] = my_env['HOME'] + '/bin/foo'

    keyfile = './id_rsa'
    keypass = b'password\n'

    proc = subprocess.Popen('/usr/bin/ssh-add -t 86400 ' + keyfile,
                            shell=True,
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            env=my_env)

     # Always results in timeout as keypass is sent to stdin NOT /dev/ttyXX
     stdout_data, stderr = result.communicate(input=keypass, timeout=60)
     if stderr:
         print("@LOG ERROR - Could not add password to ssh-agent [" + keyfile + "].")
         sys.exit(1)


text:
Q: (java)set length of an array depending on the number of values from input? I'm trying to set the length of an array depending on the user's input without asking for a key to end the array. for example, when the user types "3 2 4", my array would be {3,2,4}. and if the user types "1", then the array would be {1}. the length of the array would vary only on the user's input. I'm trying to see if the enter key can be the trigger to end taking values but i'd really like some help on this. thanks in advance

A: Well in most programming languages (since no language was given) a string can already be used as an array
 var str = "hellp";
 print str[0];

This would print out "h". If you were to use a function for counting than it would count the amount in the array. Such as PHP = count() or javascript = .length
EDIT JAVA
Im not sure how regexp works in Java, but Try this
String s = "321351";
int charCount = s.replaceAll("\[^0-9]\", "").length();
println(charCount);

This link might be helpful Java: How do I count the number of occurrences of a char in a String?

A: If you are using Java try this (assuming that the numbers are separated by space):
Scanner sc = new Scanner(System.in);
String[] tokens = sc.nextLine().split(" ");
int[] result = new int[tokens.length];
int i = 0;
for (String token : tokens)
    result[i++] = Integer.parseInt(token);
// here you will have de desired array stored in the variable 'result'.

A: Scanner sc = new Scanner(System.in);
        StringTokenizer stringTokenizer = new StringTokenizer(sc.nextLine(), " ");
        int[] result = new int[stringTokenizer.countTokens()];
        int i = 0;
        while (stringTokenizer.hasMoreTokens()){
            result[i] = Integer.parseInt(stringTokenizer.nextToken());
            System.out.println(result[i++]);
}

Use above code to handle extra spaces given by user input.
Like below string :
'       1     2    3    4  5  6    '


text:
Q: MOSFET does not turn off totally UPDATE:
If your MOSFET (or other chip) does not behave well AND you bought from not-really-known seller (even if his/her positive feedback ratio is over 99%) for a very competitive price, MAYBE you got a "factory FAKE" item (means: intentionally produced as FAKE in factory).
This realization took about 3-4 nights to me, because I just started using MOSFETs.... very VERY VERY big eye opening experience.
Original question:
I checked "MOSFET does not turn off", or even "does not turn of totally" related topics.
There the solution was usually or other (parasitic way of power), or MOSFET driving problem.
I thought I understand MOSFET (voltage driven and which voltage counts), however I faced the same problem with 2 different simple circuits, so likely  I missed something regarding MOSFET basics.
What I wanted to achieve: driving a 12V LED strip (draws about 2A).
1st I used P channel MOSFET - as switch.
It was working, BUT very often the LED strip lightly dimmed and vibrated (MOSFET ON was OK, OFF was not perfect).
I read somewhere P channel MOSFET gate needs little higher voltage than source to surely turn off..
In both circuits I created them in simulator (drawings came from there), so V1 (dataIN pin) is coming from a 3.3V microcontroller (which I realized only in 2nd circuit).

So I discarded that circuit and made a simpler one with N channel MOSFET:
(after taking apart, I checked the P channel MOSFET and .... just now I saw a Youtube video regarding real and false MOSFETs: Youtube regarding REAL and FALSE MOSFETs )

BUT
This 2nd circuit does exactly the same.
I moved the pin to a PWM capable pin, so now I can dim the LED strip nicely, I can switch on the LED strip as well, but when I switch it off it "starts" to dim very lightly and "blinks" randomly. Again, I can make steady 5%-100% LED power and works nicely, but with 0-1% (I am interested in 0%) it does not switch off firmly.
In 2nd N channel MOSFET circuit I also checked the voltages:

*

*logic high = 3 V (MOSFET gate), MOSFET DS = 0,2V - works as expected (however MOSFET datasheet states 2-4V is needed to turn on fully).

*Logic low = 0,2V (MOSFET gate), MOSFET DS = 5V (7V drops in LED). I shorted R3 (150 Ohms) to make things even simpler. When LED strip started "very dim blinking", I even shorted gate to source (with multimeter) - blink continued and I measured about 1mA <- THIS when I decided to ask help, because this ruined everything I imagined.
I have to admit, that my power source is far from perfect, 2A drain in 12V made it 11,5V, but obviously does not make few volts spikes etc.
Very rarely I achieved the "total off" state (without modifying everything), but within few mins - few hours I got back the low light & blinking LED strip. I was thinking to make some capacitor to eliminate any ripple (if any).
The dataIN is about 50 cm wire, LED strip is 2-2,5 meters, wire to LED strip is about 1 meter. Again, I shorted (in 2nd circuit during logical low dataIN) gate and source - without reaching the desired TOTAL OFF.

*

*P channel MOSFET is: IRF9540N

*N channel MOSFET is: IRFZ44N

I know both has a diode between source and drain (connected as reverse bias), but as I heard it is a byproduct of the MOSFET production and should not make any trouble here.
If anybody could help me:

*

*Why MOSFETS does not turn totally off in the above 2 circuits.

*How can I modify them (currently I have the lower circuit only, but I can recreate the 1st circuit if the solution is there).

*I added this question finally (after realizing that very likely I inserted a fake MOSFET from China to my circuit) - could be this my problem is? Therefore my 2nd circuit should not able to turn ON a real MOSFET or at least it is very borderline (as stated in datasheet).

A: I bought some N channel MOSFETs (IRLZ44N) - which has logic level gate drive from a reputable local store (for about 0,36EUR / 0,43 USD per piece).
According to datasheet, for 3V gate voltage and 3A drain-source current the resistance goes below 0,1 Ohm...
I changed the N channel MOSFET (and only that) - and VOILA everything works like charm! As I already connected to PWM signal, at even 1% PWM LEDs are nicely (but barely) dim.
Now I am sure that the originally bought IRF MOSFETs from eBay are fake (IRFZ44N were 1 USD/5 pcs; IRF9540N 1,22 USD/5 pcs) - so a price tag difference was (the real in Hungary, including 27% TAX) about 0,23 USD per piece - I start to pull my hair out.... - and always check local sellers next time.
I also bought P channel MOSFETs (IRF9Z34N) and I am quite sure my other circuit would also work with a real MOSFET.

A: Most likely your LED-s are catching some noise, might be from the DC-DC converter or the WIFI router or even from the power source itself.
The drain source diode makes a half bridge rectifier for the noise leading to a small current going through the led strip.
Place a 1Kohm resistor in parallel with the LED strip and the flickering will go away.

A: LED array still not totally off with the FET gate open or short to source. I replaced the FET with transistor with base limiting resistor solved the issue.


text:
Q: How Windows Azure Platform scales instances and balances workload? The Windows Azure Platform allows an application to be deployed to one or more instances. The fabric controller then balances your application's workload across those instances.

*

*Can the number of instances be scaled up/down based on demand or are the number of instances static? If instances can be dynamically started how much control do I have over how this happens?

*How does Azure balance workload amongst my application instances and do I have any control over how this happens?

A: I just want to add that by commercial launch (November), we'll have an API that lets you programmatically modify the number of instances.  (So you can scale based on whatever logic you want.)

A: This question has lots of good information, including a 3rd party tool (AzureWatch) that I use that can scale up/down based on load.
Azure platform: scalling instances up and down

A: The number of instances for Azure roles is specified in an xml configuration file.  Currently, you must manually change the instance count in this config file.  When you do so, the fabric controller will automatically adjust the number of running instances for you.
For web roles, incoming TCP connections are balanced across your instances.  For worker roles, the load is generally distributed across all instances picking up work assignments from a message queue.  The fabric doesn't really get involved for worker roles.

A: I know this is an old question, but I just thought that I'd highlight the free Windows Autoscaling Application Block, which was released since the question was first asked.


text:
Q: How can I access UITextFields from outside the ViewController (from a .m file)? I have a class where I keep utility methods; one of those methods takes the values in some textboxes stored in a ViewController and saves those values to a plist.
The problem is the utility methods class is not a ViewController and therefore I can't "hook up" the outlet properties of the textboxes tothe Utility class.
Is there a way I can pass the ViewController as a parameter to the Utility class method?

A: Just make the utilities class a Singleton inheriting just from NSObject. That way you can easily access the methods wherever you'd like and you'll only have one instance of it.
https://developer.apple.com/library/ios/documentation/general/conceptual/DevPedia-CocoaCore/Singleton.html
Matt Gallagher wrote a great helper file to create Singletons. Check it out here:
http://www.cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html

A: If these utility methodes are class methods use a singleton. Something like this:
+ (__CMMotionManager__ *)__sharedMotionManager__ {
    static __CMMotionManager__ *shared = nil;
    if (!shared) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{ // all threads will block here until the block executes
            shared = [[__CMMotionManager__ alloc] init]; // this line of code can only ever happen once
        });
    }
    return shared;
}

(it's my CoreMotionManager snippet)


text:
Q: Segmentation Fault C++ #include <iostream>
#include "Student.h"
#include "SortedList.h"

using namespace std;

#define BOUNDS 100

int main() {

    SortedList *list = new SortedList();  // points to the sorted list object
    Student *create[BOUNDS];  // array to hold 100 student objects
    int num = 100000;   // holds different ID numbers

    // fills an array with 100 students of various ID numbers
    for (int i = 0; i < BOUNDS; i++) {
        create[i] = new Student(num);
        num += 10;
    }

    // insert all students into the sorted list
    for (int i = 0; i < BOUNDS; i++)
    list->insert(create[i]);

    // removes each student from the list
    num = 100000;
    for (int i = 0; i < BOUNDS; i++) {
    list->remove(num);
    num += 10;
    }

    delete list;
    return 0;
}

I am getting a seg fault with the previous code. Any insight as to why this is or how to possibly fix it would be appreciated. The seg fault is definitely caused by the delete list; line
UPDATE 1: Here is my SortedList destructor
/*
 * Destructs this sorted list object
 */
SortedList::~SortedList() {
    freeList(head);
}

/*
 * Traverses throught the linked list and deallocates each node
 */
void SortedList::freeList(Listnode *L) {
    Listnode *tmp = L;  //holds the node to be deleted

    //traverses the list
    while (tmp != NULL) {
        Listnode *next = tmp->next; //holds the value of the next node

    //delete previous node
    delete tmp->student;
    delete tmp->next;
    delete tmp;

    //sets the next node to the node to be deleted
    tmp = next;
    }
    //delete header node
    delete L;
}

A: Well, we can't see SortedList or Student, and I'd guess the problem is in one of those. I note that num never gets reset to its original value after the creation loop, which means that most of the remove calls are going to be passed an id that belongs to no Student; perhaps that case fails. Or perhaps there are simply bugs in the insert or remove methods -- or the constructor or destructor, for that matter. It's totally up in the air.
EDIT: As others have pointed out, that destructor uses a pointer after it's been deleted; that could be the only source of error, or there could easily be more in the code we haven't seen yet.

A: In freelist(), you delete tmp->next, then set tmp = tmp->next. Now tmp has an invalid pointer. You need to restructure your code so that you do not free a pointer before accessing its members.
Although I hate doing people's homework for them, here's my solution:
/*
 * Traverses throught the linked list and deallocates each node
 */
void SortedList::freeList(Listnode *L) {
    if(L == NULL) return;
    freeList(L->next);
    delete L->student;
    delete L;
}

This use O(n) stack space for deletion, but I personally find it much clearer than a loop. Your solution can be tweaked to "just work" by removing the call to delete tmp->next.

A:  // removes each student from the list
    for (int i = 0; i < BOUNDS; i++) {
    list->remove(num);
    num += 10;
    }

Looks interesting... how does this work exactly?  If num is 100000 + BOUNDS*10 at this point in the code (since it is never changed after you add 10 to it for each student you create).  Every remove call you make doesn't remove a student by their ID (since the id called is 100000 + BOUNDS*10 + i*10).  Was the intent to remove them by ID, if so you should consider resetting num to 100000 before doing the remove loop.
To clarify how this could cause the seg-fault:  if your remove function doesn't have proper bounds checking it could go out of the memory looking for the id to remove.
Updated with destructor question:
void SortedList::freeList(Listnode *L) {
    Listnode *tmp = L;  //holds the node to be deleted

    //traverses the list
    while (tmp != NULL) {
        Listnode *next = tmp->next; //holds the value of the next node

    //delete previous node
    delete tmp->student;
    delete tmp->next;
    delete tmp;

    //sets the next node to the node to be deleted
    //**********
    //Check here, you deleted next, but the assigned it to temp.  Tmp isn't null, but
    //it is however, no longer your memory (since you deleted it)
    //**********
    tmp = next;
    }
    //delete header node
    delete L;
}


text:
Q: What represents 'StartupWMClass' entry from a .desktop file in Ubuntu? I am very new in developing application under Linux.
I have a doubt regarding about the use of .desktop file to add an icon into the Ubuntu Unity toolbar.
I have the following .desktop file:
[Desktop Entry]
Type=Application
#Exec=/usr/share/ConnectDataSpace/appl/launcher.sh
Exec=/usr/share/XCloud/appl/launcher.sh
Type=Application
X-GNOME-Autostart-enabled=true
#Name[en_US]=Connect Data Space
Name[en_US]=XCloud
#Name=Connect Data Space
Name=XCloud
Comment[en_US]=
Comment=
StartupNotify=true
OnlyShowIn=GNOME;Unity;
#StartupWMClass=ConnectDataSpace
StartupWMClass=XCloud
#Icon=/usr/share/ConnectDataSpace/img/icoLauncher.png
Icon=/usr/share/XCloud/img/icoLauncher.png

My doubt is: What exactly represents the StartupWMClass=XCloud field of this file?

A:
StartupWMClass - If specified, it is known that the application will
  map at least one window with the given string as its WM class or WM
  name hint (see the Startup Notification Protocol Specification for
  more details).

Source: Recognized desktop entry keys


text:
Q: Calling shortcode from within shortcode in Wordpress I'm using a php plugin in wordpress that allows you to shortcode php and have it post. My PHP script then calls a random line from a text file. In this file, I want there to be another call on some lines that pull from yet another file, or run a shortcode themselves. Issue is, I run the first shortcode, and it posts the 1st lv just fine, but the codes then in that one don't post. Is there a way to have random lines in a file echoed, that also can pull random lines? (or call a shortcode)
The code stored in XYZ PHP SNIPPIT, in shortcode [stage1]
<?php
$file = "scenarios.txt";
$file_arr = file($file);
$num_lines = count($file_arr);
$last_arr_index = $num_lines - 1;
$rand_index = rand(0, $last_arr_index);
$rand_text = $file_arr[$rand_index];
echo $rand_text;
?>

in the scenarios file it has something like, say
"[person1] and [person2] go for a walk" with both of those being shortcodes for other php list calls.
the issue is, it just shows the [person1] and doesn's call the shortcode. So I also tried making the lines more like this:
<?php echo do_shortcode('[person1]'); ?> and <?php echo do_shortcode('[person2]'); ?> go for a walk

Again it calls up the first Scenario short code, but the person1/2 ones end up just showing blank and not being called up. How do I embed layers of shortcode or php shortcode calls in wordpress?

A: You can pass a parameter such as "[person1] and [person2] go for a walk" to do_shortcode and it will automatically identify the shortcodes. So this will do the trick:
echo do_shortcode($rand_text);


text:
Q: Problem counting screen locking patterns with backtracking The problem is counting the number of paths of length n from a given
vertex in a graph like the used to unlock Android devices.I'm trying to use backtracking to solve it but I don't get right, I'm I'm still learning how to use it. So here is some code I've been trying
G = {
    'a': set('bed'),
    'b': set('cfeda'),
    'c': set('feb'),
    'd': set('abehg'),
    'e': set('bcfihgda'),
    'f': set('ciheb'),
    'g': set('deh'),
    'h': set('efigd'),
    'i': set('fhe')
}

result = 0

def count_patterns(node, length):
    if length == 1:
        return len(G[node])
    global result
    for neighbor in G[node]:
        result += count_patterns(neighbor, length - 1) - 1
    return result

I expect the count_patterns('a',2) to return 15 and it does return it; however, for n>2
all the results are wrong by far. I think it must be that I don't actually getting track of the node visited, for example if takes this route for n = 3
a -> b -> c when it backtracks to a -> b it can take a -> b -> a which is wrong so it cannot take the parent of the node as a neighbor, I know the problem but
I don't know how to fix it.

A: First of all, you don't need the last -1. So,

result += count_patterns(neighbor, length - 1) - 1

Should become

result += count_patterns(neighbor, length - 1)

The main problem with your code is that if you go, for example, from a->b and then b->a, you count this as a path of length 2. But it's not. A path shouldn't have repeated vertices. There are two ways you can deal with this: (I will only mention the main idea)

*

*Have a global visited array that has boolean values (true or false). If you have n nodes, this array should have a capacity as much as the number of nodes. Then, you change your code as follows: (pseudocode)

``
def count_patterns(node, length):
    if length == 1:
        return len(G[node])
    global result
    for neighbor in G[node]:
        if neighbor is not visited
             mark neighbor as visited
             result += count_patterns(neighbor, length - 1)
             mark neighbor as unvisited //This is very important
    return result

``
The reason that you need to "mark neighbor as unvisited" is because you don't want to repeat a vertex in a specific branch; but you want to be able to use it on another path after you have returned from your recursive call.

*You can just pass a third argument to your function which is a list of the vertices you've picked so far; then you only pick a new vertex if you it's not in the list. And you update the list as well:

``
def count_patterns(node, length, list):
    if length == 1:
        return len(G[node])
    global result
    for neighbor in G[node]:

        if neighbor is not in list

             result += count_patterns(neighbor, length - 1, list.append(neighbor))
    return result

``
I personally, prefer the first way because it's gonna be faster and simpler.


text:
Q: Method of p value correction for a set of dependent p values I just got a list of 100 p-values, some of which are associated. For details, these 100 p-values could be separated into 7 groups, each group was calculated from a expression dataset. However, these datasets had 10%~60% overlap among each other, that is the pvalues inside a dataset were independent, but were not across the dataset, which bring the whole 100 p-values not independent.
So is there any solutions you know to directly and simply solve this? Some ref. pointed out to use the BH adjustment inside the R package, while choosing a loose criteria, e.g. 0.2, to define the significance level.
tmp$V7 = p.adjust(tmp$V6,method="BY")
tmpV6[1:5]
[1] 0.040461040 0.001250268 0.037407030 0.009361665 0.006866937
tmpV7[1:5]
[1] 0.31423224 0.08659423 0.29570166 0.14456543 0.13611251
tmp$V7 = p.adjust(tmp$V6,method="BH")
tmp$V6[1:5]
[1] 0.040461040 0.001250268 0.037407030 0.009361665 0.006866937
tmp$V7[1:5]
[1] 0.05252837 0.01447545 0.04943072 0.02416616 0.02275313

Please take a look at this, tmp$V6 is the original p-value, while tmp$V7 is after correction.
However, it seems that after BY correction, I get even worse result than BH (or fdr) method.

A: You should definitely correct for multiple comparisons! There are a huge number of strategies for this, many of which are suitable for dependent data. The Benjamini–Hochberg–Yekutieli procedure is computationally simple approach to setting the false discovery rate and works under arbitrary dependence assumptions; your tests don't need to be independent for it to be appropriate.
In brief, perform all $m$ of your individual tests, recording the $p$-values as you go. Sort them from smallest to largest, creating a list $p_1 \ldots p_m.$ Find the largest value of $k$ such that:
$$ p_k \le \alpha \cdot \frac{k}{m \cdot c(m)}$$
where $c(m)=1$ if the tests are independent or positively correlated, or for arbitrary dependence $c(m) = \sum_i^m \frac{1}{i} \approx \ln(m) + \gamma$, where $\gamma$ is the Euler–Mascheroni constant (0.5772...).
Accept as significant all the $p$-values less than or equal to $p_k$, but reject the rest as non-significant.
Note that this is somewhat more liberal (i.e., has better power, but more Type I errors) than something which controls the Familywise Error Rate. However, people typically use the same $\alpha$ value (0.05, 0.01, etc). Setting $\alpha=0.2$ seems like it would be asking for a lot of spurious calls!
Further reading:

*

*Wikipedia Page on FDR

*Benjamini and Yekutieli (2001). "The control of the false discovery rate in multiple testing under dependency" Annals of Statistics 29 (4): 1165–1188.

*"Comparison Shopping" for False Discovery Rate packages in R


text:
Q: read input data gzipped file line by line I am acquainted that some folks have already written about this question; however, this question is not clear to me yet. I need to read gzipped files which contain unformatted data. I have unsuccessfully tried following instructions from zlib and gzstream sites. Could anybody provide me a quick example of how to extract data directly from the compressed gzip file using an ifstream? My procedure using dat files is the following:
#include <iostream>
#include <sstream>
#include <string>

int main () {
    ifstream file;
    string stringtemp;
    stringstream line2convert;
    file.open("directory/file.dat");
    // read each line using a for loop (I know the total number of lines)
    file.getline (line,100);
    // extract information line by line using stringstreams
    line2convert  << line;
    line2convert >> int2convert;
    ...
    ...
    ...
}

Anybody could give me a hint to add a few lines that I need?
Thanks!
 - F

A: if you know how to link in gzstream, you can do that
just replace "ifstream" with "igzstream"
.

A: A disgusting method to do this is to execute gzip -c on your input file and read the standard output from the gzip(1) process using something like popen(3). It'll decompress as little as necessary to fill your process's read requests. But it does require a working installation of gzip(1) on the system, which is not ideal, but might be a suitable tradeoff for your application.
Perhaps your application should bundle its own copy of gzip(1)? Beware that zlib has security flaws like everything else, and users are not impressed when they have a dozen different applications to update when there is one security problem in zlib.
You could also write code to incrementally decrypt portions of the input yourself and fill your C++ streams objects with the decrypted data. This route would be more work but wouldn't rely on copying data between processes, so it might be able to run faster, and would probably be less brittle than relying on system-supplied gzip(1) executables.


text:
Q: Flow to Email Author I would like to plan a button in my Opportunites page which leads to a flow, the flow will give the user three radio boxes, depending on the option selected this should lead to a Email Author page while also passing off the Opportunity ID (variable).
I believe creating the flow with the options would be easy, but I'm not sure how to link to the email author page and also passing the opportunity ID to it.
How can this be done?

A: The EmailAuthor page isn't readily accessible. However, if you want to travel down this path, you'll need to learn about "Salesforce URL Hacking". I do this in my instance of salesforce with an on click javascript button, and I frequently use the page I'm linking as a reference for what all the URL parameters in the EmailAuthor page mean.
All you'd need to do is have your final page of the flow lead to a particular URL, which you'd craft using the following page as a reference guide:
http://salesforcewizard.wordpress.com/2014/01/30/url-hack-revisted-auto-select-email-template-with-custom-button/


text:
Q: ViewPager animation with buttons using PagerTransformer I'm trying to do some animation on my ViewPager. On my main View i have a ViewPager and two buttons. what I want to do is when I click on left button then view in viewPager is move to the left (off-screen) and next view fades in and the same way for right button but to right side. (something like Tinder app effect but simplest). I found a nice interface named ViewPager.PageTransformer but i can't figure out how to move view in way that I want.
Thanks for help :)

A: This repo has a handful of animations. If what you're looking for isn't present, at least you have a decent start.
https://github.com/ToxicBakery/ViewPagerTransforms

A: You may want to see this. It shows a sample having 2 buttons and pages scrolls on click of these.
http://developer.android.com/intl/es/training/animation/screen-slide.html


text:
Q: Recursion not working as expected for target sum problem I wrote two different recursive functions in python to solve the following problem. The second function I wrote works correctly and returns the correct result; but the first function I wrote returns a wrong result. The only difference between the two functions is the base condition. Could you please explain to me why the first function returns a wrong result?
Problem statement:

You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols
'+' and '-' before each integer in nums and then concatenate all the
integers.
For example, if nums = [2, 1], you can add a '+' before 2 and a '-'
before 1 and concatenate them to build the expression "+2-1".
Return the number of different expressions that you can build, which
evaluates to target.

My code:
# first function: returns the wrong result
def targetsum(nums, crnt, target):
  print(nums,crnt)
  if target==crnt:
    return 1
  if len(nums)==0:
    return 0
  result = (
    targetsum(nums[1:], crnt + nums[0], target)
    + targetsum(nums[1:], crnt - nums[0], target)
  )
  return result

# second function: returns the correct result
def dfs(curr, nums, target):
  print(nums,curr)
  if not nums:
    return (1 if curr == target else 0)
  res = (
    dfs(curr + nums[0], nums[1:], target)
    + dfs(curr - nums[0], nums[1:], target)
  )
  return res

nums = [1,1,1,1,1]
target = 3
crnt=0

print(targetsum(nums, crnt, target))   # prints 4

print(dfs(crnt, nums, target))         # prints 5

I expected the output 5, because there are 5 ways to assign symbols to make the sum of nums be target 3:
    -1 + 1 + 1 + 1 + 1 = 3
    +1 - 1 + 1 + 1 + 1 = 3
    +1 + 1 - 1 + 1 + 1 = 3
    +1 + 1 + 1 - 1 + 1 = 3
    +1 + 1 + 1 + 1 - 1 = 3

The second function, dfs, returns 5 as expected. But the first function, targetsum, returns 4 which is wrong. Why?

A: The base-case for the recursion is wrong in your first function targetsum. Function targetsum returns 1 immediately if crnt == target, even if we haven't reached the end of the array. But this is wrong: you should not return a result until you've reached the end of the array.
On your example with nums=[1,1,1,1,1] and target=3, the first recursive calls will go like this:
 1 1 1 1 1   crnt=0
+1 1 1 1 1   crnt=1
+1+1 1 1 1   crnt=2
+1+1+1 1 1   crnt=3
crnt==3==target!! return 1 immediately!!

Can you see the error in logic here? crnt is equal to target, yes, but we forgot to take into account the last two numbers in the array. We shouldn't return 1 immediately; in fact, there are not 1 but 2 possibilities to make target 3 with the beginning +1+1+1: the two possibilities are +1+1+1+1-1 and +1+1+1-1+1. But the only way to figure that out is to go deeper in the recursion. We haven't hit a base-case yet.
Your second function dfs handles the base case correctly: the conditional if not nums: means "if nums is empty:".


text:
Q: Links not lining up with inline-block I'm trying to get the three links - LOGO, About, and FAQ to show up on the same line, but I'm unable to do so. It seems that the margin-left on my nav-link class is screwing things up, but I'm not sure why.

body, html {
    background-color: #EDEDED;
}
.nav {
    position: absolute;
    width: 80%;
    margin: 5%;
}
.nav-link {
    margin-left: 2%;
}
.nav-part {
    display: inline-block;
}
.apply {
    float: right;
    position: relative;
    right: 0;
    top: 0;
}

        LOGO
        About
        FAQ

        <button>Apply</button>

Here's my jsfiddle - https://jsfiddle.net/hcrcba06/1/

A: the div that contains your links does not have much room to put the links on the same line so it brings the last one to the next line just increase the width of your nav-part class and it will work. JSFiddle here

A: You could easily solve that by changing it to CSS table layout.

body, html {
    background: #EDEDED;
}
.nav {
    display: table;
    width: 80%;
    margin: 5% auto;
}
.nav-part {
    display: table-cell;
}
.nav-link {
    margin-left: 2%;
}
.apply {
    text-align: right;
}

        LOGO
        About
        FAQ

        <button>Apply</button>

A: It's because you are using margin in percentages.

Margins in percentages are always
  relative to the width of the containing block.

Remove the margin-left in percentages. If you add a fixed margin it will work.
Use:
.nav-link {
  margin-left: 12px;
}

instead of
.nav-link {
  margin-left: 2%;
}

DEMO: https://jsfiddle.net/hcrcba06/3/


text:
Q: InnoDB row metadata size (minimum row size) I'm trying to decide whether to normalize a thing further, and need to know what the smallest a row in InnoDB can be (I've got MySQL 5.6).
This is not exactly my case, but for simplicity, let's assume I just have a surrogate PK (bigint) and two TINYINT columns, neither of which can be null. How many bytes can I expect each row to need for storage if I'm gonna have 1 billion of these?
I'd imagine each row requires some metadata (I know it does at least for when there are NULLable columns), but can't seem to find the documentation on how to calculate it.
Then, how much can I expect to be eaten by the free space in the page, and the metadata in the page (or is that all together)?
I want to know so that I can better judge when I would have a long table that is narrow enough to avoid proper normalization.

A: Each row in InnoDB (let assume COMPACT format) has these headers:

*

*Offsets - one or two byte per variable length type field.

*NULL flags - one bit per NULL-able field, aligned to a whole number of bytes.

*So called "Extra bytes" - a bunch of flags like is_deleted, pointer to next record ect. Five bytes in COMPACT format, fixed.

Then comes primary key field(s).
Then 6 bytes transaction id and 7 bytes rollback pointer.
Then remaining field values.
For the given row (BIGINT, TINYINT, TINYINT) it's size will be:

*

*0 bytes offsets

*0 bytes NULL flags

*5 bytes "Extra bytes"

*8 bytes BIGINT

*6 bytes trx_id

*7 bytes roll_ptr

*1 byte TINYINT

*1 byte TINYINT

So, 28 bytes per record.
But to calculate how much space the table will take you need to take into account:

*

*PAGE header (38+56 bytes)

*page trailer

*page fill factor

*infinum, supremum records

*space used by non-leaf pages

Check these slides for more details
http://www.slideshare.net/akuzminsky/data-recovery-talk-on-pluk

A: (I'm adding an "answer", not a comment for formatting reasons.)
@akuzminsky covered most things quite thoroughly.
Why a BIGINT?  Won't an INT UNSIGNED (max value 4 billion) suffice?  That would saver 4GB.
The fill factor comes in two flavors --
If the writes are cleanly done, then the blocks are 15/16 full.  Grand total might be 40-45GB
If there is random INSERTs, then the blocks average 69% full.
Now. let's ask why this layout?  The two TINYINTs will be repeated a lot in a billion rows.  (In particular, at least 1B/(256*256) = some will pairs will be repeated at least 4K times.)  Maybe you could have only 65K rows, and have counters in them?  Maybe some other summarization technique would work for your application?  (OK, maybe this table is artificial.)
BTW, MyISAM would take 11GB for the data for that table (assuming no holes).  Plus another 15-20GB for the PRIMARY KEY.


text:
Q: What are the differences between kill process and close process? When I start a process and want to close this process, what are the differences between Process.Close() and Process.Kill()?
I asked because I have an application which starts to capture packet using Wireshark with a command via command line with Windows = hidden.
so when I want to stop the capturing I kill the process .So sometimes the capture opens with an error that the last packet was cut in the middle so I am wondering can using close() before kill() will solve this issue ?
When I start capturing I can close it by pressing Ctrl + C but in my case I open the window in hidden state, Can I do something similar via my code ?

A: Kill and Close are not two options. Kill (or CloseMainWindow) must be called if you want to terminate a process. Calling Close will just free resources, but it won't close the standard streams. Closing the streams yourself may or may not cause the process to end, it depends on the process. The best strategy is to call Kill or CloseMainWindow depending on the type of process and then Dispose the Process object.
Close begins closing the Process object. It's called by Dispose. Close is generally used for managing the Process object's resources.
Kill terminates the process. This is the only way to terminate a process that has no user interface.
CloseMainWindow sends a close message to the main window of the process. This is the graceful way to stop a process that has a user interface.

A:
What are the differences between Process.Close() and process.Kill()?

The manual is pretty clear on that:
Process.Close():

The Close method causes the process to stop waiting for exit if it was waiting, closes the process handle, and clears process-specific properties. Close does not close the standard output, input, and error readers and writers in case they are being referenced externally. [i.e. the process itself keeps running, you just cannot control it anymore using your Process instance]

Process.Kill():

Kill forces a termination of the process, while CloseMainWindow only requests a termination. [...] The request to exit the process by calling CloseMainWindow does not force the application to quit. The application can ask for user verification before quitting, or it can refuse to quit. To force the application to quit, use the Kill method. The behavior of CloseMainWindow is identical to that of a user closing an application's main window using the system menu. Therefore, the request to exit the process by closing the main window does not force the application to quit immediately.

Process.CloseMainWindow:

Closes a process that has a user interface by sending a close message to its main window.

As for your edit:

i asked because i have application who start to capture packet using wireshark with command via command line with Windows = hidden.

Use the WinPcap API or the Pcap.Net library for that, not Wireshark.

A: Let me illustrate what happens visually when you call  Close() and Kill() . The following will open Notepad but does not exit the notepad at the end when myProcess.Close() executes.
Process myProcess;
myProcess = Process.Start("Notepad.exe");
Thread.Sleep(10000);
myProcess.Close();

the following will open Notepad. after 10 seconds the notepad will close at the end when myProcess.Kill() executes.
Process myProcess;
myProcess = Process.Start("Notepad.exe");
Thread.Sleep(10000);
myProcess.Kill();

A: Process.Kill calls TerminateProcess.
Process.Close doesn't do what you think it does! It simply frees resources used by the instance of the class. Please read this: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.close.aspx

A: Kill asks the system to unceremoniously terminate the process (via a call to the Windows TerminateProcess system call). This is akin to End Process in Task Manager.
Close closes the handle to the process in .NET, but does not actually touch the process itself. Close is also called by Dispose. See this answer by Jon Skeet.
A third option is CloseMainWindow, which does gracefully shut down the program by asking the primary window to close. This is akin to right-clicking the program on the task bar and choosing Close.


text:
Q: Create a function to find the Max & Min float inputArray(int &size,float &inputdata,float array1[]);
float findMaxMin(int &size,float &max,float &min,float array1[]);
void displayMenu (float &max, float &min);

using namespace std;

int main() {
    int size;   // Variable designated for the number of elements the user wishes to allocate
    float inputdata; // Designated for temporarily storing the user input for the array
    float max;          // Variable designated for the maximum value within the array
    float min;          // Variable designated for the minimum value within the array
    float array1[size]; // Array consisting of a specified number of elements by user

inputArray(size,inputdata,array1);
findMaxMin(size,max,min,array1);
displayMenu(max,min);

return 0;

}

/******************************Input Array Data*****************************/
float inputArray(int &size,float &inputdata,float array1[]){

  cout << "Type in the number of elements you wish to utilize" << endl;
    cin >> size;        // User specifies number of elements to be allocated

    for (int x = 0; x < size; x++) {
        cout << "Type in value for element " << x << " and Press [ENTER] "
             << endl;
        cin >> inputdata;
        array1[x] = inputdata;

        }

}
/****************************************************************************/

/*************************Determination of Max & Min*************************/

float findMaxMin(int &size,float &max,float &min,float array1[]){

//The min and max variables are given the value of the first element of array1.

    max=min=array1[0];

    for (int x = 0; x < size; x++) {
            if (min > array1[x]) {
                min = array1[x];
            }
            if (max < array1[x]) {
                max = array1[x];
            }
    }

}

/*****************************************************************************/

/*********************************Menu Screen*********************************/
/**The Menu Screen will tell the user that the data collection is complete and
will prompt the user to input an integer to trigger the display of the desired
output**/

void displayMenu (float &max, float &min){

        char menuInput; // Variable designated to store user input for the menu
        bool inputTester;

        do {
            cout << "\n\n\t\tYour Data Has Been Collected"
                    "\n\t\tTo View Maximum of Data Set Enter.......\t 9"
                    "\n\t\tTo View Minimum of Data Set Enter.......\t 0"
                 << endl;
            cin >>menuInput;

                            switch(menuInput){
                            case('9'):
                                    cout<<"Maximum is "<<max<<endl;
                                    inputTester=true;
                                    break;

                            case('0'):
                                    cout<<"Minimum is "<<min<<endl;
                                    inputTester=true;
                                    break;

                            default:
                                cout<<"Please Enter a Valid Input"<<endl;
                                inputTester=false;
                                break;

                                }
        }

        while (inputTester==false);

}

So basically what I'm trying to do is: Prompt user to input float numbers in console; – Create a function to find the max/min number of the array; – Create a function to display the max and min depending on what command ('0' or '9') is being typed by the user in console. But I keep getting an error and I'm stuck.

A:     int size;  // <---- here
    float inputdata;
    float max;
    float min;
    float array1[size];  // <--- and here

Your variable int size is uninitialized and you use it to allocate float array1 of unknown number of elements; Later you are trying to write to this array assuming that the number of available elements is equal to user input (which is not). That's why your stack is corrupted and you might get seg fault when returning from main. You should use dynamic allocation with operator new or just use appropriate C++ container for this job (like std::vector).
Advice: compile your programs with -Wall -Werror flags. Compiler will tell you about uninitialized variables, no return statements in the functions and similar.

A: The simplest way to get a min and max from an array is with the std::minmax_element provided by the <algorithm> header. To write a function to return a minmax std::pair, you could do:
/* returns <min, max> pair from arr of nelem */
std::pair<float*, float*> minmaxfloat (float *arr, size_t nelem)
{
    return std::minmax_element (arr, arr + nelem);
}

A short example could be:
#include <iostream>
#include <algorithm>
#include <utility>

/* returns <min, max> pair from arr of nelem */
std::pair<float*, float*> minmaxfloat (float *arr, size_t nelem)
{
    return std::minmax_element (arr, arr + nelem);
}

int main (void) {

    float arr[] = { 5, 4, 6, 3, 7, 2, 8, 1, 9 };
    float min, max;
    /* create minmax pair from call to minmaxfloat() */
    std::pair<float*, float*> p1 = minmaxfloat (arr, sizeof arr/sizeof *arr);

    min = *p1.first;    /* assign min */
    max = *p1.second;   /* assign max */

    std::cout << "min: " << min << " max: " << max << '\n';
}

(note: the std::pair will consist of two-pointers to the min and max elements within your array)
Example Use/Output
$ ./bin/floatminmax
min: 1 max: 9

It beats coming up with your own. Look things over and let me know if you have further questions.


text:
Q: R: carrying values forward by an ID and only through a given date range I have a data table that looks like the following:
   id  firstd       lastd       treat
   1   2003-03-23   2003-03-25  1
   1   2003-03-24   2003-03-25  NA
   1   2003-03-25   2003-03-25  NA
   1   2003-05-13   2003-05-15  0
   1   2003-05-14   2003-05-15  NA
   1   2003-05-15   2003-05-15  NA
   2   2004-04-28   2004-04-30  0
   2   2004-04-29   2003-04-30  NA
   2   2004-04-30   2003-04-30  NA

I want to carry through the values of the column treat through the date range from firstd to firstd==lastd by id so the NAs are filled in with the given values.
Ideally, it will look like the following:
   id  firstd       lastd       treat
   1   2003-03-23   2003-03-25  1
   1   2003-03-24   2003-03-25  1
   1   2003-03-25   2003-03-25  1
   1   2003-05-13   2003-05-15  0
   1   2003-05-14   2003-05-15  0
   1   2003-05-15   2003-05-15  0
   2   2004-04-28   2004-04-30  0
   2   2004-04-29   2003-04-30  0
   2   2004-04-30   2003-04-30  0

I know how to carry a value through by one column, but have not done it with the added complexity of a given date range. Does anyone know how to do this?
The code I generally use when carrying forward values through given columns is the following-
    one[, treat:= treat[!is.na(treat)][1], by = id]

Does anyone know how to amend this piece of code to also consider the given date ranges? Or would have any further suggestions?

A: We can group by 'id' and fill
library(dplyr)
library(tidyr)
one %>%
   group_by(id) %>%
   fill(treat)
# A tibble: 9 x 4
# Groups:   id [2]
#     id firstd     lastd      treat
#  <int> <chr>      <chr>      <int>
#1     1 2003-03-23 2003-03-25     1
#2     1 2003-03-24 2003-03-25     1
#3     1 2003-03-25 2003-03-25     1
#4     1 2003-05-13 2003-05-15     0
#5     1 2003-05-14 2003-05-15     0
#6     1 2003-05-15 2003-05-15     0
#7     2 2004-04-28 2004-04-30     0
#8     2 2004-04-29 2003-04-30     0
#9     2 2004-04-30 2003-04-30     0

If we are also using dates as grouping variable, then
one %>%
   group_by(id, grp = rleid(lastd)) %>%
   fill(treat)

Or if we also consider the 'firstd', then create a grouping variable based on the equality between the dates
one %>%
    group_by(id, grp = lag(cumsum(firstd == lastd), default = 0)) %>%
    fill(treat)

With data.table we can combine with na.locf0 from zoo
library(zoo)
library(data.table)
setDT(one)[, treat := na.locf0(treat), by = id][]
#   id     firstd      lastd treat
#1:  1 2003-03-23 2003-03-25     1
#2:  1 2003-03-24 2003-03-25     1
#3:  1 2003-03-25 2003-03-25     1
#4:  1 2003-05-13 2003-05-15     0
#5:  1 2003-05-14 2003-05-15     0
#6:  1 2003-05-15 2003-05-15     0
#7:  2 2004-04-28 2004-04-30     0
#8:  2 2004-04-29 2003-04-30     0
#9:  2 2004-04-30 2003-04-30     0

data
one <- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L),
 firstd = c("2003-03-23",
"2003-03-24", "2003-03-25", "2003-05-13", "2003-05-14", "2003-05-15",
"2004-04-28", "2004-04-29", "2004-04-30"), lastd = c("2003-03-25",
"2003-03-25", "2003-03-25", "2003-05-15", "2003-05-15", "2003-05-15",
"2004-04-30", "2003-04-30", "2003-04-30"), treat = c(1L, NA,
NA, 0L, NA, NA, 0L, NA, NA)), class = "data.frame", row.names = c(NA,
-9L))

A: Another data.table option using non-equi join and then update by reference:
DT[is.na(treat), treat :=
    DT[!is.na(treat)][.SD, on=.(id, firstd<=lastd, lastd>=lastd), x.treat]
    ]

output:
   id     firstd      lastd treat
1:  1 2003-03-23 2003-03-25     1
2:  1 2003-03-24 2003-03-25     1
3:  1 2003-03-25 2003-03-25     1
4:  1 2003-05-13 2003-05-15     0
5:  1 2003-05-14 2003-05-15     0
6:  1 2003-05-15 2003-05-15     0
7:  2 2004-04-28 2004-04-30     0
8:  2 2004-04-29 2004-04-30     0
9:  2 2004-04-30 2004-04-30     0

data:
library(data.table)
DT <- fread("id  firstd       lastd       treat
1   2003-03-23   2003-03-25  1
1   2003-03-24   2003-03-25  NA
1   2003-03-25   2003-03-25  NA
1   2003-05-13   2003-05-15  0
1   2003-05-14   2003-05-15  NA
1   2003-05-15   2003-05-15  NA
2   2004-04-28   2004-04-30  0
2   2004-04-29   2004-04-30  NA
2   2004-04-30   2004-04-30  NA")
cols <- c("firstd", "lastd")
DT[, (cols) := lapply(.SD, as.IDate, format="%Y-%m-%d"), .SDcols=cols]


text:
Q: Image distorted on different resolution devices when using scaleType="fitXY" I have a carousel banner and I have the requirement the images to cover all the layout and be displayed the same irrespective of device resolution. Below is the original image, device screenshot of correct use and lastly, device screenshot of wrong use

As you can see in the last image, the circle on the right upper part of the image becomes oval shaped, which is not the case.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#232323">

    <ImageView
        android:id="@+id/advert_carousel_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY" />

</androidx.constraintlayout.widget.ConstraintLayout>

Image is set using Glide
Glide
    .with(mContext)
    .load(img)
    .into(advertCarouselBackground);

Any ideas on how the original image can be displayed without distortion independently of device resolution? I have tried some solutions, like converting the image to bitmap, setting width and height programmatically, calculating aspect ratio, etc, but nothing worked so far.


text:
Q: Advert showing some markup/not rendering correctly
Running the latest version of Chrome, on a recent version of Windows.
Seems to only happen on Stack Overflow, not too sure about that though as the other sites don't seem to show that advert to me.
I'm pretty sure I don't have any Chrome extensions installed eg, ad blocker.
Only seems to happen with that advert.

A: Good catch! This was due to an error in set up. When trying to append a click-macro we had a superfluous quotation mark in the creative tag.
Easy to fix, and a great reminder that our typos are visible by many!


text:
Q: OpenCV SIFT key points extraction isuue I tried to extract SIFT key points. It is working fine for a sample image I downloaded (height 400px width 247px horizontal and vertical resolutions 300dpi). Below image shows the extracted points.

Then I tried to apply the same code to a image that was taken and edited by me (height 443px width 541px horizontal and vertical resolutions 72dpi).

To create the above image I rotated the original image then removed its background and resized it using Photoshop, but my code, for that image doesn't extract features like in the first image.
See the result :

It just extract very few points. I expect a result as in the first case.
For the second case when I'm using the original image without any edit the program gives points as the first case.
Here is the simple code I have used
#include<opencv\cv.h>
#include<opencv\highgui.h>
#include<opencv2\nonfree\nonfree.hpp>

using namespace cv;

int main(){

Mat src, descriptors,dest;
vector<KeyPoint> keypoints;

src = imread(". . .");

cvtColor(src, src, CV_BGR2GRAY);

SIFT sift;
sift(src, src, keypoints, descriptors, false);
drawKeypoints(src, keypoints, dest);
imshow("Sift", dest);
cvWaitKey(0);
return 0;
}

What I'm doing wrong here? what do I need to do to get a result like in the first case to my own image after resizing ?
Thank you!

A: Try set nfeatures parameter (may be other parameters also need adjustment) in SIFT constructor.
Here is constructor definition from reference:
SIFT::SIFT(int nfeatures=0, int nOctaveLayers=3, double contrastThreshold=0.04, double edgeThreshold=10, double sigma=1.6)

Your code will be:
#include<opencv\cv.h>
#include<opencv\highgui.h>
#include<opencv2\nonfree\nonfree.hpp>

using namespace cv;
using namespace std;
int main(){

Mat src, descriptors,dest;
vector<KeyPoint> keypoints;

src = imread("D:\\ImagesForTest\\leaf.jpg");

cvtColor(src, src, CV_BGR2GRAY);

SIFT sift(2000,3,0.004);
sift(src, src, keypoints, descriptors, false);
drawKeypoints(src, keypoints, dest);
imshow("Sift", dest);
cvWaitKey(0);
return 0;
}

The result:

Dense sampling example:
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include "opencv2/nonfree/nonfree.hpp"

int main(int argc, char* argv[])
{
    cv::initModule_nonfree();
    cv::namedWindow("result");
    cv::Mat bgr_img = cv::imread("D:\\ImagesForTest\\lena.jpg");
    if (bgr_img.empty())
    {
        exit(EXIT_FAILURE);
    }
    cv::Mat gray_img;
    cv::cvtColor(bgr_img, gray_img, cv::COLOR_BGR2GRAY);
    cv::normalize(gray_img, gray_img, 0, 255, cv::NORM_MINMAX);
    cv::DenseFeatureDetector detector(12.0f, 1, 0.1f, 10);
    std::vector<cv::KeyPoint> keypoints;
    detector.detect(gray_img, keypoints);
    std::vector<cv::KeyPoint>::iterator itk;
    for (itk = keypoints.begin(); itk != keypoints.end(); ++itk)
    {
        std::cout << itk->pt << std::endl;
        cv::circle(bgr_img, itk->pt, itk->size, cv::Scalar(0,255,255), 1, CV_AA);
        cv::circle(bgr_img, itk->pt, 1, cv::Scalar(0,255,0), -1);
    }
    cv::Ptr<cv::DescriptorExtractor> descriptorExtractor = cv::DescriptorExtractor::create("SURF");
    cv::Mat descriptors;
    descriptorExtractor->compute( gray_img, keypoints, descriptors);
    // SIFT returns large negative values when it goes off the edge of the image.
    descriptors.setTo(0, descriptors<0);
    imshow("result",bgr_img);
    cv::waitKey();
    return 0;
}

The result:


text:
Q: Highcharts, vue component. 3 charts in 1 expected chart
Hi, I need to make this charts, looks like 3 charts in 1(?). I can make the 2 scatered ones, but the column charts its tricky. Thanks to Wojciech Chmiel I was able to make this columns charts with highcharts-vue, but the chart behaviour its a little odd, I cant add a yAxis, nor stop the chart from pushing to the top like a sort of responsive behaviour.

A: @Wojciech Chmiel
Hi, sorry for the delay. A columnrange chart with a bloxplot and 2 scatter

initChart (data) {
      this.chartOptions = merge(this.getBaseChartConfig(ChartTypes.BoxPlot), {
        xAxis: {
          categories: data.periods
        },
        series: [
          {
            type: 'columnrange',
            name: 'Observations',
            data:data.peerGroupStatisticReturns.dataRange,
            showInLegend: false
          },
          {
            type: 'boxplot',
            linkedTo: ':previous',
            data: data.peerGroupStatisticReturns.values
          },
          {
            type: 'scatter',
            name: data.names[1],
            marker: {
              symbol: 'diamond',
              fillColor: '#6598FD',
              radius: 6
            },
            data: data.benchmarkReturnSeries.data
          },
          {
            type: 'scatter',
            name: data.names[2],
            marker: {
              symbol: 'square',
              fillColor: '#FFCC33'
            },
            data: data.productReturnSeries.data
          }
        ]
      })

      // chart settings
const boxPlotConfig = {
  title: {
    text: ''
  },
  plotOptions: {
    boxplot: {
      fillColor: '#0076C0',
      medianColor: '#303030',
      medianWidth: 1,
      stemWidth: 0,
      whiskerWidth: 0,
      color: '#303030',
      showInLegend: false
    },
    columnrange: {
      color: '#66ADD9'
    },
    series: {
      enableMouseTracking: false,
      borderColor: '#303030'
    }
  },

  yAxis: {
    title: ''
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Now I have make the colors interspersed and move the markers so the dont overlap, one to the right inside the column and one to the left


text:
Q: Is there a class or method in Java that will check if a string is a SQL Server keyword? I want something that can check if a string is "SELECT", "INSERT", etc.  I'm just curious if this exists.

A: Easy enough to add :
    HashSet<String>  sqlKeywords    =
     new HashSet<String>(Arrays.asList(
       new String[] { ... cut and paste a list of sql keywords here ..  }));

A: If you're trying to prevent SQL injection, it would be better to leverage the built in features of JDBC, such as prepared statements. In general, using string concatenation to form the SQL statement is dangerous. From Preventing SQL Injection in Java:
Prepared Statements:
String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();

A: why not start with this stored procedure and modify it to suit your needs, possibly even convert it to Java using the hashmap as Steve suggested.
Personally I like the idea of a stored procedure because different databases may have different keywords so it seems elegant to have the database pass judgement

A: DatabaseMetaData.getSQLKeywords will return the databases keywords that are not in SQL-2003 (SQL-2003 keyword can be found in the standard). There are other methods within that interface for getting various types of function names and similar.
As Chase Seibert mentions, don't think this is an effective way to block SQL injection attacks.


text:
Q: Mapping Normalizer to Automorphism I am squeezing my brain trying to understand this problem:

Let H be a subgroup of $G$, and denoted by $\operatorname{Aut}(H)$ the group of all automorphisms of $H. $ Define
$$\alpha : N_G(H) \to \operatorname{Aut}(H),\quad g \mapsto \alpha_g.$$
where $\alpha_g : H \to H, h \mapsto h^g.$ Show that $\alpha$ is a homomorphism and determine $\ker (\alpha).$

I understand that $N_G(H) = \{g \in G : Hg = gH \}$ and that $\operatorname{Aut}(H)$ is a set whose elements are automorphisms $\alpha_g : H \to H,$ But what I could not imagine is the mapping from $g$ (element of group $G$) to $\alpha_g$ (which in the most mundane term is actually a function.)
Additionally, I would love to see the synopsis of the solution. Any patient and friendly explanation befitting a person still in learning curve is very much appreciated. Thank you for your time and help. Happy holidays.

A: $N_G(H)$ is a group — specifically, a subgroup of $G$. $\operatorname{Aut}(H)$ is also a group: it's elements are functions — specifically, automorphisms of $H$ — and its operation is composition of functions. Thus, the function $\alpha$ that assigns to each $g\in N_G(H)$ the automorphism $\alpha_g\in\operatorname{Aut}(H)$ defined by $\alpha_g(h)=h^g$ for each $h\in H$ is simply a function from one group to another; don't let the fact that the elements of $\operatorname{Aut}(H)$ are themselves functions get in your way.
Since $\alpha$ is a function from one group to another, it could conceivably be a homomorphism, and our task is to show that in fact it is one. In other words, we need to show that for any $g_0,g_1\in G$, $$\alpha_{g_0g_1^{-1}}=\alpha_{g_0}\circ\alpha_{g_1}^{-1}\;.\tag{1}$$
The two sides of $(1)$ are functions from $H$ to $H$; to show that they're equal, we must show that
$$h\alpha_{g_0g_1^{-1}}=h\left(\alpha_{g_0}\circ\alpha_{g_1}^{-1}\right)$$
for each $h\in H$. (Here I'm writing the function after its argument.) Let $h\in H$; then
$$\begin{align*}
h\alpha_{g_0g_1^{-1}}&=h^{g_0g_1^{-1}}\\
&=(g_0g_1^{-1})^{-1}h(g_0g_1^{-1})\\
&=g_1g_0^{-1}hg_0g_1^{-1}\\
&=g_1h^{g_0}g_1^{-1}\\
&=(h^{g_0})^{g_1^{-1}}\\
&=(h\alpha_{g_0})\alpha_{g_1^{-1}}\\
&=h(\alpha_{g_0}\circ\alpha_{g_1^{-1}})\;,
\end{align*}$$
and $\alpha$ is indeed a homomorphism.
The identity element of $\operatorname{Aut}(H)$ is the identity map $\operatorname{id}_H$ from $H$ to $H$, so
$$\begin{align*}
\ker\alpha&=\{g\in N_G(H):\alpha_g=\operatorname{id}_H\}\\
&=\{g\in N_G(H):h^g=h\text{ for all }g\in H\}\;.
\end{align*}$$
With just a little more work you should be able to translate that definition into a familiar subgroup of $H$.

A: just assume that $H=G$ for now.  $G$ acts on itself by conjugation, and conjugation by an element is an automorphism of $G$.  if $\alpha_g:G\to G$ is conjugation by $g$, we have
$$
a_{g_1g_2}(h)=(g_1g_2)h(g_1g_2)^{-1}=\alpha_{g_1}(\alpha_{g_2}(h)),
$$
i.e. $\alpha:G\to\text{Aut}(G)$, $g\mapsto\alpha_g$, is a homomorphism (the group operation on automorphisms is composition of functions).  the kernel of $\alpha$ is the set
$$
\{g\in G : \alpha_g\equiv 1_G\},
$$
which is a way of describing $Z(G)$, the center of $G$ (the elements of $G$ that commute with everything).
Now you should be able to generalize this to a subgroup and it's normalizer.

A: You have the right idea:  $\alpha$ is indeed a function.  What that means is that for each element $g \in N_G(H) \le G$, we have a well-defined rule for associating an automorphism of the subgroup $H$, namely conjugation by $g$.
It's important that we only take elements $g$ from the normalizer of $H$, for those are the elements that fix $H$ setwise under conjugation.  (This is weaker than fixing $H$ pointwise; i.e. the centralizer of $H$.  More on this later).  In symbols,
$$
N_G(H) = \bigl\{ g \in G \mid gHg^{-1} = H \bigr\},
$$
so the function $\alpha_g$ maps $h \mapsto ghg^{-1} \in H$.
Now to check that $\alpha$ is a homomorphism, we have to show that $\alpha(g_1g_2) = \alpha(g_1)\alpha(g_2)$.  Note that the operation on the elements $g_1$ and $g_2$ is in the group $G$; whereas, the operation on the automorphisms $\alpha(g_1)$ and $\alpha(g_2)$ is composition of functions.
(Hover over the box to reveal the calculation.)

 $$ \alpha(g_1g_2)(h) = (g_1g_2) h (g_1g_2)^{-1} = g_1g_2 h g_2^{-1}g_1^{-1} = \alpha(g_1)(g_2 h g_2^{-1}) = \alpha(g_1)\bigl(\alpha(g_2)(h)\bigr) $$

What's the kernel?  An element $g \in \ker \alpha$ maps to the trivial automorphism on $H$ (the identity function).  In other words, $\alpha_g = \alpha_e$.  How do we characterize such $g$?

 $$ \alpha_g(h) = \alpha_e(h) \quad\Longrightarrow\quad ghg^{-1} = ehe^{-1} = h \text{ for all } h \in H \quad\Longrightarrow\quad g \in C_G(H)$$


text:
Q: Layout Help Fitting to Any Screen Hi I have an issue with trying to fit my storyboard objects to other iphone device screens using autolayout. I need to adjust the vertical spacing between my the 4% rule and the get started stack views to fit it but it changes the layout on the iphone 11 pro screen. How can I have everything be in the same position for both screens?

A: I changed the priority of the 2 stackviews from 1000 to 750, and it seems to have fixed my issue.


text:
Q: Валидация поля ввода пароля regex'ом Условия:

*

*минимум 8 символов

*минимум одна цифра

*минимум одна буква латиницы или кириллицы прописная

*минимум одна буква латиницы или кириллицы заглавная

Мое решение:
^(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-ZА-Я])(?=.*[a-zа-я]).*$

пропускает

парольFF

без цифр, что я сделал не так?


text:
Q: Algorithm to check whether distance between any two objects is within the Specified grid I have distance value between two objects. Need algorithm to check whether measured distanced is available in distance of any two objects in grid pattern shown in Image
Grid for verification

A: This is grid with squared cells. All distances at such grid (expressed in units of cell size)  should satisfy to condition
d^2 = a^2 + b^2

If  squared distance is integer and you can represent it as sum of two integer squares, then objects can be placed in grid nodes.
There is mathematical criteria - number P is not representable as sum of two squares if it's factorization into primes contains any (4n+3)factor in odd power


text:
Q: Numerical Solution of i-dim heat quation I am solving 1-dim heat equation by discretizing it by replacing the time derivative by a forward difference and the space derivative by the center difference formula at the j-th time step. I get the following recursive formula.
              w_{i,j+1}=0.5(w_{i+1,j}+w_{i-1,j}), i=1,2,3,4,5,  j=1,2,3,4,5

The i.cd is u(x,0)=x^{4}, and b.cd are u(0,t)=0 and u(1,t)=1. The domain is: 0

The problem: The B.pts bounds the domain from 3 sides but it is open from one side. So the points (0.2,0.2), (0.4,0.2), (0.6,0.2), ... are interior points. right? When I take, for instance i=1, j=5, then I get w_{1,6} in the recursive formula. This point is out of the mesh. Are there any suggestion to handle this situation? I shall be grateful for your help!
Shah

A: I'm not sure what's confusing you. When you plug in $i=1,j=5$, because of how you wrote the formula, you are using the iteration to find the value of $w_{1,6}$, which is simply not a value of interest since it isn't in the mesh. The only thing I can think that might be confusing you is that your BC numerically says that $w_{0,j}=0$ for all $j$ and $w_{6,j}=1$ for all $j$. So for example $w_{5,j+1}=0.5(1+w_{4,j})$.
It might be clearer to write the formula in the form
$$w_{i,j} = \frac{w_{i+1,j-1} + w_{i-1,j-1}}{2}$$
instead. Does that clear the issue up?
(As an aside, you are likely to have stability problems with that time stepping scheme. Backward Euler, explicit 4th order Runge Kutta, and implicit 4th order Runge Kutta are all much better choices for these kinds of problems.)


text:
Q: None and logical operations and/or I was trying to fully understand the behavior of None as a boolean for logical and and or operations, so I tried the following code:
for a, b in [(None, False), (None, True), (False, None), (True, None)]:
    print(f"{str(a):<5} & {str(b):<5}", a and b)

for a, b in [(None, False), (None, True), (False, None), (True, None)]:
    print(f"{str(a):<5} | {str(b):<5}", a or b)

That outputs:
None  & False: None
None  & True : None
False & None : False
True  & None : None
None  | False: False
None  | True : True
False | None : None
True  | None : True

The last two cases of and are expected due to short-circuiting. If the first statement is False it returns False without checking the second one, while if the first one is True it directly returns the second one. But the first two cases show that None doesn't have any boolean value.
The last two cases of or are again expected due to short-circuiting. If the first statment is False it directly returns the second one, while if the first one is True it returns True without checking the second one. But the first two cases show that None has a negative boolean value.
I understand that the purpose of this negative value is to be able to do things like default values with a = a or 5, but why is it not consistent with the behavior shown for and? I was expecting both first and cases to return False.

A:
why is it not consistent with the behavior shown for and? I was expecting both first and cases to return False.

It's entirely consistent.
and returns the first operand if it's "falsy", otherwise the second; or returns the first operand if it's "truthy", otherwise the second. Neither converts its operands to booleans.
None is "falsy", since and returns the first operand if falsy None and x returns None, regardless of x.
Also your table is pretty confusing as | and & are actual Python operators (but not boolean operators, or short-circuiting).


text:
Q: CSS позиционирование Как при помощи только css(не редактируя HTML) разместить данные блоки http://jsfiddle.net/runrmtvm/

так что бы они имели вот такой вод вид:

A: попробуйте nth-child редактировать
к примеру
.img:nth-child(1){
width:150px;
margin:auto;//или позиционированием
}
.img:nth-child(2){
margin-left:150px;
float:left;}
.img:nth-child(3){
margin-left:100px;
float:left;}
.img:nth-child(4){
margin-left:100px;
float:left;}

A: Здравствуйте, вот http://jsfiddle.net/vbsLpkup/1/
в margin-left подставе проценты какие вам нужно
.img:first-child, .img:first-child img{
  width:150px;
  margin:20px auto;
}

.img:not(:first-child){
  float:left;
  margin-left:16%;
}


text:
Q: Interpreting regression and $R^2$ with small $n$ I am trying to create a regression comparing resampled data from 2 sampling periods using $n=6$ samples.
I have tried a few different models (e.g., linear, log-transform, and exponential), and have received mixed results.
For example, the linear models look best graphically, but because I have so few data points, each point has a strong effect on the trend and therefore points with greater distance from the mean are resulting in the model having a negative adjusted $R^2$ value.
An exponential model has a much improved, and positive, adjusted $R^2$ value, but graphically doesn't make as much sense as the linear model.
Essentially, the exponential model is reacting to the dispersion of points around the linear regression line and trying to make up for the residual error of more outlier-ish points.
However, these points would almost certainly be within reasonable distance from the mean if more points were added.
So I have 2 questions:

*

*Do I go with what looks more sensible graphically, or just blindly believe the adjusted $R^2$?

*Obviously, more data points would be beneficial, but what are my options if I can't supplement with more data?

Examples:
3 variables demonstrating this issue. Solid color lines are model fits and dashed lines are 95% CI. Black = linear, red = log-trasnformed, green = exponential. x-axis = 1977, y-axis = 2015. Created in R using lm().

Update:
Background info:
I have 21 soil variables I resampled in 1977 & 2015. Each of these variables had 6 sample plots shared b/w each sampling period. However, I have a number of 1977 samples & 2015 samples that were only sampled once (in 1 year & not the other). The soil processing was different b/w years, so the 2 years aren't directly comparable. I'm trying to 'correct' the non-resampled 1977 samples to match 2015 data (not sampled in 1977) by regressing my 6 resampled samples for each variable. I'm assuming soil has not changed in 40 years, so I'm not trying to compare soil change, but rather trying to lump all extant samples (resampled and not) for common analyses.
My example data:
dput(soil.dat)
structure(list(plot.2015 = c(5L, 10L, 24L, 25L, 44L, 51L), Silt.2015 = c(28.88, 21.84, 22.89, 25.34, 16.96, 22.36), Sand.2015 = c(63.92, 73.67, 60.38, 69.03, 81.6, 70.18), BS.2015 = c(70, 60.4, 43.2, 41, 84.4, 54), Silt.1977 = c(44L, 38L, 40L, 42L, 50L, 36L), Sand.1977 = c(37L, 49L, 37L, 36L, 39L, 42L), BS.1977 = c(36.6, 26.48, 44.08, 36.6, 53.32, 44.08)), .Names = c("plot.2015", "Silt.2015", "Sand.2015", "BS.2015", "Silt.1977", "Sand.1977", "BS.1977"), class = "data.frame", row.names = c(1L, 2L, 15L, 16L, 18L, 19L))

A: The problem is that your data is both very small and very noisy. This leads to the very different outcomes you get from your models. In such small samples outliers have very big influence on your outcome. Imagine, for example, that you removed case 44 from the first plot - then we would see "obvious" upward, quadratic trend. Now imagine we removed case 5 - the "trend" would be very different. If we removed case 10 from the second plot we would get very steep positive trend. All this makes the approach you would choose for analyzing this data have great influence on the outcome.
One approach you could possibly apply is to use Bayesian model with informative prior based on your out-of-data knowledge about the phenomenon you observe.
With such a small sample overfitting is a significant risk, so simpler (e.g. linear) models are safer that more complicated ones (e.g. including polynomials).


text:
Q: How to create list inside a list using UITableView I have a requirement. Where I have to get the list of students and then I have to show their subjects in which they are enrolled in.
Example
Now you can see below I have list of students i.e Student1, student2, and so on. and each student have different number of subjects

What I have done So far:
I have created a Custom cell that Contains a Label and Empty vertical stackview.
Then in method tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) I am running the for loop that makes some UiLabel dynamically and adds them into the vertical stackview
Problem:  By doing this I am getting what I want. But when I scroll up and down the for loop repeats data in the cell again and again on each scroll up/down
Please help if there is anyother way of doing that.

A: You can use tableview with section.

*

*Set student name in section

*Set your subjects in cell

This is sample of tableview with section.
https://blog.apoorvmote.com/uitableview-with-multiple-sections-ios-swift/
Here is the sample code it is just for your reference.
class TableViewController: UITableViewController {

let section = ["pizza", "deep dish pizza", "calzone"]

let items = [["Margarita", "BBQ Chicken", "Pepperoni"], ["sausage", "meat lovers", "veggie lovers"], ["sausage", "chicken pesto", "prawns", "mushrooms"]]
// MARK: - Table view data source

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

return self.section\[section\]

}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
 // #warning Incomplete implementation, return the number of sections

return self.section.count

}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
 // #warning Incomplete implementation, return the number of rows

return self.items\[section\].count

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
 let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath)

// Configure the cell...

cell.textLabel?.text = self.items[indexPath.section][indexPath.row]

return cell

}

Update
Customised section view
Create your custom view and show your view as section
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let view = UIView(frame: CGRect(x:0, y:0, width:tableView.frame.size.width, height:18))
    let label = UILabel(frame: CGRect(x:10, y:5, width:tableView.frame.size.width, height:18))
    label.font = UIFont.systemFont(ofSize: 14)
    label.text = "This is a test";
    view.addSubview(label);
    view.backgroundColor = UIColor.gray;
    return view

}

Sample code for Customised section
Update 2
Custom header with reference of cell
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let  headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! CustomHeaderCell
    headerCell.backgroundColor = UIColor.cyanColor()

    switch (section) {
    case 0:
      headerCell.headerLabel.text = "Student Name 1";
      //return sectionHeaderView
    case 1:
      headerCell.headerLabel.text = "Student Name 2";
      //return sectionHeaderView
    case 2:
      headerCell.headerLabel.text = "Student Name 3";
      //return sectionHeaderView
    default:
      headerCell.headerLabel.text = "Other";
    }

    return headerCell
  }

A: You can try a different approach. Make a list with number of sections = number of students. Each section should have number of rows equal to the subjects for that student. This can be achieved easily by making a student model with subjects array as it's property.
class Student: NSObject {
    var subjectsArray : [String] = []
}

A: First add this extension to your source code.
extension UIStackView{
    func removeAllArrangedSubviews() {
        let removedSubviews = arrangedSubviews.reduce([]) { (allSubviews, subview) -> [UIView] in
            removeArrangedSubview(subview)
            return allSubviews + [subview]
        }
        removedSubviews.forEach({ $0.removeFromSuperview() })
    }
}

Now override this method in your Custom cell class. it will remove all child views from stackview before reuse.
override func prepareForReuse() {
    super.prepareForReuse()
    self.stackView.removeAllArrangedSubviews()
}