text:
Q: Keyboard not resigning when i tap the return key (xcode) I am trying to get the keyboard to go away, when I press the return key on my application heres my code from the .m:
- (BOOL)textFieldShouldReturn:(UITextField *)textField{

[textField resignFirstResponder];
return YES;

}

and the code in the .h:
- (BOOL)textFieldShouldReturn:(UITextField* )textField;

But when I run the application and hit the return key nothing happens. What am I doing wrong?
my .h:
#import <UIKit/UIKit.h>
@interface ChemicalInfoViewController: UIViewController{
IBOutlet UIScrollView *ChemicalInforScroller;

}
@property (strong, nonatomic) IBOutlet UITextField *PPMForChlTextField;
@property (strong, nonatomic) IBOutlet UITextField *GallonsForChlTextField;
@property (strong, nonatomic) IBOutlet UITextField *PPMForAlkTextField;
@property (strong, nonatomic) IBOutlet UITextField *GallonsForAlkTextField;
@property (strong, nonatomic) IBOutlet UITextField *PPMForPHTextField;
@property (strong, nonatomic) IBOutlet UITextField *GallonsForPHTextField;
- (IBAction)SumbitCDI:(UIButton *)sender;
@property (strong, nonatomic) IBOutlet UILabel *PPMLabelForChl;
@property (strong, nonatomic) IBOutlet UILabel *GallonsLabelForChl;
@property (strong, nonatomic) IBOutlet UILabel *PPMLabelForAlk;
@property (strong, nonatomic) IBOutlet UILabel *GallonsLabelForAlk;
@property (strong, nonatomic) IBOutlet UILabel *PPMLabelForPH;
@property (strong, nonatomic) IBOutlet UILabel *GallonsLabelForPH;
@property (strong, nonatomic) IBOutlet UITextField *ChlorinePoundsTextField;
@property (strong, nonatomic) IBOutlet UITextField *GallonsForAlkDecreaser;
@property (strong, nonatomic) IBOutlet UITextField *PhPoundsTextField;
@property (strong, nonatomic) IBOutlet UITextField *AlkPoundsTextField;
@property (strong, nonatomic) IBOutlet UITextField *LbsForAlkDecreaser;
@property (strong, nonatomic) IBOutlet UITextField *PPMForAlkDecreaser;
@property (strong, nonatomic) IBOutlet UITextField *LbsForPhDecreaser;
@property (strong, nonatomic) IBOutlet UITextField *PPMForPhDecreaser;
@property (strong, nonatomic) IBOutlet UITextField *GallonsForPhDecreaser;
- (IBAction) clickedBackground;
@interface ChemicalInfoViewController : UIView <UITextField>
@end

and my .m:
#import "ChemicalInfoViewController.h"

@interface ChemicalInfoViewController ()

@end

@implementation ChemicalInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {

}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
[ChemicalInforScroller setScrollEnabled:YES];
[ChemicalInforScroller setContentSize:CGSizeMake(320, 1000)];
self.textField.delegate = self;

}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];

}

- (IBAction) clickedBackground {

[self.view endEditing:YES];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

[textField resignFirstResponder];
return YES;

}

A: In your .h, remove:
- (BOOL)textFieldShouldReturn:(UITextField* )textField;

And it will work as it should, given that in your .h, you conform to the protocol:
@interface yourViewController : UIView <UITextFieldDelegate>

And set up the delegate like so:
yourTextField.delegate = self;

Edit regarding to the @end:
In your .m, add a @end to the bottom; so , it becomes (scroll to the very bottom):
@implementation ChemicalInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {

}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
[ChemicalInforScroller setScrollEnabled:YES];
[ChemicalInforScroller setContentSize:CGSizeMake(320, 1000)];
self.textField.delegate = self;

}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];

}

- (IBAction) clickedBackground {

[self.view endEditing:YES];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

[textField resignFirstResponder];
return YES;

}

@end //Here :-)

A: You didn't set the delegates for your textfields.
In "viewDidLoad" add

_ChlorinePoundsTextField.delegate = self;
_GallonsForAlkDecreaser.delegate = self;
_PhPoundsTextField.delegate = self;
_AlkPoundsTextField.delegate = self;
_LbsForAlkDecreaser.delegate = self;
_PPMForAlkDecreaser.delegate = self;
_LbsForPhDecreaser.delegate = self;
_PPMForPhDecreaser.delegate = self;
_GallonsForPhDecreaser.delegate = self;

A: none of these methods seemed to be working for some reason but what i did end up doing was creating a DidEndOnExit action and resigned the keyboard under that action for each textfield


text:
Q: Add ordinal column to stored procedure I'd like to add a column to a stored procedure that simply counts up from 1, irrespective of how the data is sorted or which page I'm fetching (using offset.)
The stored procedure itself looks like this:
SELECT
   e.EntityId, e.HierarchyId, e.ParentNode, e.NgageId, e.NgageParentId,
   e.Type, e.IsDeleted, e.LastIndexedDate, e.CurrentVersion, e.Level,
   v.EntityVersionID, v.VerisonNotes, v.Title, v.[Description], v.FormID,
   v.IsPublic, v.CreatedDate, v.LastModifiedDate, v.ExpirationDate,
   d.DocumentID, d.OwnerId AS OwnerId,
   o.ADUsername AS OwnerAccount, o.Name AS Author,
   d.[Status], d.DocumentType, d.CheckoutUserId AS CheckoutUserId,
   c.ADUsername AS CheckoutUserAccount, c.Name AS CheckoutUserName,
   d.CheckoutDate,
   dbo.GetCommaSeperatedTags(e.EntityID) AS Tags
   --INTO #documentsTemp
FROM
   dbo.Entities AS e
INNER JOIN
   dbo.EntityVersions AS v ON v.EntityID = e.EntityID AND e.CurrentVersion = v.VersionNumber
INNER JOIN
   dbo.Documents AS d ON d.EntityVersionID = v.EntityVersionID
INNER JOIN
   dbo.Users AS o ON o.UserID = d.OwnerId
LEFT JOIN
   dbo.Users AS c ON c.UserID = d.CheckoutUserId
WHERE
   [Type] = 5
   AND NgageID = @ngageId
   AND IsDeleted = 0
   AND dbo.CheckPermissions(e.EntityId, @userId, 'LIST') = 1
ORDER BY
    CASE WHEN @orderBy = 'Title' THEN v.Title END,
    CASE WHEN @orderBy = 'Title' AND @desc = 1 THEN v.Title END DESC,
    CASE WHEN @orderBy = 'Author' THEN o.Name END,
    CASE WHEN @orderBy = 'Author' AND @desc = 1 THEN o.Name END DESC,
    CASE WHEN @orderBy = 'DateModified' THEN v.LastModifiedDate END,
    CASE WHEN @orderBy = 'DateModified' AND @desc = 1 THEN v.LastModifiedDate END DESC
OFFSET ((@pageNumber - 1) * @pageSize) ROWS
FETCH NEXT @pageSize ROWS ONLY;

What is the best way to do this?
Thanks,
Joe

A: I see three options (two of them are already mentioned by Gordon and the third one is not recommended):

*

*do this at the application level

*repeat the ORDER BY clause and do some arithmetic

*rely on undocumented behaviour, with potentially incorrect results

Here are options 2 and 3 in AdventureWorks (to shorten the queries):
DECLARE @pageSize int=5, @pagenumber int=2, @OrderBy varchar(20)='Name'

SELECT (ROW_NUMBER() OVER (
    ORDER BY
    CASE WHEN @OrderBy='Name' THEN Name END,
    CASE WHEN @OrderBy='ProductNumber' THEN ProductNumber END
    )-1)%@pageSize+1 as N, *
FROM Production.Product
ORDER BY
    CASE WHEN @OrderBy='Name' THEN Name END,
    CASE WHEN @OrderBy='ProductNumber' THEN ProductNumber END
OFFSET ((@pageNumber - 1) * @pageSize) ROWS
FETCH NEXT @pageSize ROWS ONLY

SELECT ROW_NUMBER() OVER (ORDER BY @pageSize) AS RN, *
FROM (
    SELECT * FROM Production.Product
    ORDER BY
        CASE WHEN @OrderBy='Name' THEN Name END,
        CASE WHEN @OrderBy='ProductNumber' THEN ProductNumber END
    OFFSET ((@pageNumber - 1) * @pageSize) ROWS
    FETCH NEXT @pageSize ROWS ONLY
) X

Razvan

redpajama_set_name: RedPajamaStackExchange


text:
Q: Curved arrow in math mode I'm fairly new to LaTeX and am trying to see if I can get away doing something without using a library like tikzcd. I have the following code:
\begin{document}
\begin{center}
$\dashrightarrow
\overbrace{Tr1_{P9} \mapsto \underbrace{enum(Tr2_{P9}
\mapsto Tr3_{P9})}_{\alpha} \mapsto
\begin{pmatrix} Tr4_{P9} \\ Tr4_{I0} \end{pmatrix}}^{\beta}$
\end{center}
\end{document}

\
Is there a way that I can have a long curved arrow (preferably a dotted \mapsto arrow) connect from the first letters, Tr1_{P9} to the vector at the end––over or under the rest of the text–– without creating a diagram in tikzcd? The overbrace (with the \beta text) can be changed to an underbrace if needed. Thanks!

A: Without creating a diagram, you can do that with pstricks: make two nodes in the equation and connect them with ncarc and the suitable parameters:
\documentclass{article}

\usepackage{amsmath, amssymb}
\DeclareMathOperator{\enum}{enum}

\usepackage{pst-node}

\begin{document}

 \[ \dashrightarrow
\overbrace{\rnode{T}{Tr1}_{P9} \mapsto \underbrace{\enum(Tr2_{P9}
\mapsto Tr3_{P9})}_{\alpha} \mapsto
\begin{pmatrix} Tr4_{P9} \\Tr\rnode{M}{4_{I0}}\end{pmatrix}}^{\beta}
\ncarc[linestyle=dotted, dotsep=2pt, arrows=->, arrowinset=0.15, arcangle=-30, nodesep=6pt]{T}{ M}
\]

\end{document}


text:
Q: New remote repository eclipse git I have a java project that used to deal with a remote repository that now doesn't exist any more. It has a history I'd like to keep and I need to create another remote bare repository where push to and pull from, for the future commits. How can I do this, just starting from the only copy I have now, the local one (which is already some commits ahead)?

A: Eclipse has a Git Perspective that helps you achieve this.
Head over to Window -> Open Perspective -> Other and choose Git from the dialog
You would be presented with the Git Repository view.
Expand the Remotes section, and Click on Create Remote... Fill in the details of your new repository.
You can then choose to remove the previous remote and rename the newly created one as origin.


text:
Q: ReSharper Integrate with VS build I have VS2008 professional and i installed ReSharper. The R# does work well and analyzes the code but what i need is to integrate the R# analysis with VS Build so that when i make a build (in Debug/Release), i should be able to see those suggestions/warnings by R# in the VS Error List Window. Also getting a report of the same is appreciated.
Can anyone help me in this regard?

A: TeamCity, also from JetBrains, is a build system that has the ability to provide the ReSharper errors and warnings as part of your build.
I'm aware that this isn't MS Build, though.


text:
Q: Retrieving Jenkins node variables from master So my google-fu has failed me and the Jenkins O'Reilly book isn't helping either.
I have a Jenkins setup with a master and 20-odd nodes.  I make heavy use of custom environment variables on the nodes, as many of them perform similar tasks, only slightly different platforms.
I'm now in a position that I have a job that runs on the master (by necessity), which needs to know certain node properties for any given node, including some of the environment variables that I've set up.
Is there any way to reference these?  My alternative seems to be to have hundreds of environment variables in the master in the form node1_var1, node2_var1, node1_var2, node2_var2 etc., which just seems messy.  The master clearly has knowledge of the variables, as that's where the configuration for them is done, but I just can't find a way to specify them in a job.
Any help (or ridicule and pointing out of obvious answers) much appreciated...

A: Here's a simple Groovy script that prints the list of environment variables for each slave:
for (slave in jenkins.model.Jenkins.instance.slaves) {
  println(slave.name + ": ")
  def props = slave.nodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)
  for (prop in props) {
    for (envvar in prop.envVars) {
      println envvar.key + " -> " + envvar.value
    }
  }
}

Warning: I am not an experienced Groovy programmer, so I may not be using the appropriate idioms of Groovy.
You can run this from the Jenkins script console in order to experiment. You can also run a "System Groovy Script" as a build step. Both of the above require the Groovy plugin. If you don't use Groovy in your job, you could use this script to write a properties file that you load in the part of your build that does the real work.


text:
Q: Regex/Notepad++ to extract text from file I have multiple files with text in parenthesis that I need to extract from the file (or delete everything else in that file).  I have a method that works, but it only works for one file.  Here is an example of the kind of files I'm dealing with.
(is it on?)
[3.87595  3.87595 0 ]xsh
grestore
NDTMRY+Helvetica[8.5 0 0 -8.5 0 0 ]msf
 mo
(NO)

The method I have used is as follows:

*

*in notepad++ under the mark tab in find replace; Find: ^(.*?$ (with bookmark line checked)

*Search>bookmarks>remove unbookmarked lines

Is there a way/better way to do this for multiple files at a time?  In this or another language such as python.
Thanks!

A: Yes, it is possible to remove in multiple files lines that do not start with (.
Here is the screenshot with settings:

So, here are the instructions:

*

*Press Ctrl+H and click Find in Files

*In Find What, type ^(?!\().*\R*, keep Replace With empty

*Add file masks in Filters

*Select the initial directory in Directory.

*Make sure Regular expression radio button is selected.

Adjust other options and hit Replace in Files button.


text:
Q: Custom Permalink Structure with Custom Post Types Using Custom Taxonomies After a pretty exhaustive search, I'm stumped.
I have a Wordpress custom post type named: listings. Listings have taxonomies called Services and Areas.
The default structure is
/listing/%post-name%
I'm trying to achieve a structure that looks like:
/%services%/%areas%/%post-name%
I was able to achieve something close using the plugin Custom Post Type Permalinks which gives me this working URL:
/listings/%services%/%areas%/%post-name%
And then used the code
function gp_remove_cpt_slug( $post_link, $post, $leavename ) {

    if ( 'listing' != $post->post_type || 'publish' != $post->post_status ) {
        return $post_link;
    }

    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );

    return $post_link;
}
add_filter( 'post_type_link', 'gp_remove_cpt_slug', 10, 3 );

That shows a permalink of what I want when I edit the listing but there's a 404 error when I go to that URL. I'm not sure where to go from here. Please help.

A: A simple solution would be using the rewrite and 'with_front arguments while registering the post type. Try this..
'with_front' => false,
'rewrite' => array( 'slug' => '%services%/%areas%'),

Then add a filter to post_type_link to replace the tags with terms.
function wpse277778_rewrite_urls( $url, $post ) {

   if ( 'listings' == get_post_type( $post ) ) {
        $services = wp_get_post_terms( $post->ID, 'services' );
        $areas = wp_get_post_terms( $post->ID, 'areas' );

        $url = str_replace( '%services%', $services[0]->slug, $url );
        $url = str_replace( '%areas%', $areas[0]->slug, $url );

    }
    return $url;
}
add_filter( 'post_type_link', 'wpse277778_rewrite_urls', 10, 2 );

Please note, this is a barebone code and you need to do some checking with conditional tags to output error free $url. Also, you should set a default services and area in case no terms are associated.


text:
Q: Access object from lambda passed in object's constructor I have a Java class MyClass with this constructor:
public MyClass(Consumer<?> someMethod)

And I would like to do that:
final MyClass myObject = new MyClass(obj -> {
    doSomethingOutsideTheContextOfMyObject();
    myObject.doSmomething(obj);
    });

But I get an compiler error that variable myObject might not be initialized.
According to my research I cannot switch of the compiler showing the error and I cannot fake-initialize the variable as it has to be final. What shall I do?

A: Here:
final MyClass myObject

declares a new object myObject. And then you go on:
  = new MyClass(obj -> {
  doSomethingOutsideTheContextOfMyObject();
  myObject.doSmomething(obj);

using the very same myObject within its own declaration!
That isn't possible like that! You are creating a "self-reference" in circular ways!

A: I think that the lambda you are passing to your Constructor should not be a Consumer ; it should be a BiConsumer...
Something like that :
import java.util.function.BiConsumer;

public class MyClass<T> {

    private BiConsumer<MyClass<T>, T> lambda;

    public MyClass(BiConsumer<MyClass<T>, T> lambda) {
        this.lambda = lambda;
    }

    private static void doSomethingOutside() {
        // TODO Auto-generated method stub

    }

    private void doSomething(T obj) {
        // TODO Auto-generated method stub

    }

    public void go(T o) {
        lambda.accept(this, o);
    }

    public static void main(String[] args) {
        MyClass<String> myObj = new MyClass<>((me, obj) -> {
            doSomethingOutside();
            me.doSomething(obj);
        });

        myObj.go("Hello World!");
    }
}

HTH! :)


text:
Q: Jcrop OnSelect in Directive Not Firing I'm creating a directive for Jcrop in a project I'm working on. For some reason, the function I have specified in Jcrop's OnSelect isn't firing. I'm wondering if it's because I've defined it within the link function in my directive, or if it's another scope issue...but I'm not really sure.
I'm defining the following directive for Jcrop:
module MyProject.Directives {

    export interface IEfJcropScope extends ng.IScope {
        image: MyProject.Image;
        aspectRatioGroups: _.Dictionary<MyClass[]>;
        selectCrop(group: MyClass[]);
        storeCoords(coords);
    }

    export class EfJcrop implements ng.IDirective {
        restrict = "E";
        templateUrl = 'ef-jcrop.html';
        replace = true;
        transclude = true;
        scope = {
            image: "="
        }
        link = (scope: IEfJcropScope, elem, attrs) => {
            window.setTimeout(() => {
                this.imageElement = $('#img-' + scope.image.ImageID)
                this.imageElement.Jcrop({
                    onChange: scope.storeCoords, //this is not firing
                    onSelect: scope.storeCoords, //this is not firing
                    allowResize: false,
                    allowSelect: false,
                }, () => {

                    });
            });
            //passing in an entire group, represents all active products for one particular aspect ratio
            scope.selectCrop = (group: MyClass[]) => {
                var jcropObj = this.imageElement.data('Jcrop');
                jcropObj.setOptions({
                    aspectRatio: 1.5 //for example
                });
                scope.storeCoords = (coords) => {
                    //store coords.x, coords.y, code is here
                }
            }
        };
        controller = ($scope: IEfJcropScope) => {
        }
    }
}

Here's the template:

{{ipd.ProductDimension.Name}}

With a breakpoint in scope.storeCoords, the function is never reached. I get no errors in the browser. Why wouldn't it be called?

A: This was an issue that resulted from a tired brain. The storeCoords is within the selectCrop function. It shouldn't be. Oops.


text:
Q: maven can't find path specified I have some problems building my project with maven on my windows machine and I discovered that even "mvn version"  not completes correctly. It ends with "the system cannot find the path specified"
D:\my_project\nl.esi.poosl.maven>mvn -v
Apache Maven 3.2.3 (33f8c3e1027c3ddde99d3cdebad2656a31e8fdf4; 2014-08-11T22:58:10+02:00)
Maven home: C:\apache-maven-3.2.3
Java version: 1.8.0_20, vendor: Oracle Corporation
Java home: C:\Java\jdk1.8.0_20\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "dos"
The system cannot find the path specified.
D:\my_project\nl.esi.poosl.maven>

environment variables:
PATH:                   %JAVA_HOME%\bin;%M2%;C:\Windows\Microsoft.NET\Framework\v4.0.30319;D:\sytemapps\Python27;%M2%;%JAVA_HOME%/bin;C:\Developer\Android\sdk\platform-tools\;%GRADLE_HOME%\bin;%DEVKIT_HOME%\bin;%DEVKIT_HOME%\mingw\bin
JAVA_HOME:
C:\Java\jdk1.8.0_20
M2:
%M2_HOME%\bin
M2_HOME:
C:\apache-maven-3.2.3
I can't find the reason why "The system cannot find the path specified." is printed out because it probably is the reason why my project won't build.

A: Your %JAVA_HOME% is pointing to a JRE. A JRE usually doesn't have javac. Could this be the source of the issue?
Other than that, my environment is the same as yours and it runs fine.
What does your pom.xml look like?

A: %JAVA_HOME%\bin;%M2%;C:\Windows\Microsoft.NET\Framework\v4.0.30319;D:\sytemapps\Python27;%M2%;%JAVA_HOME%/bin;C:\Developer\Android\sdk\platform-tools\;%GRADLE_HOME%\bin;%DEVKIT_HOME%\bin;%DEVKIT_HOME%\mingw\bin
change to
%JAVA_HOME%\bin;%M2_HOME%;C:\Windows\Microsoft.NET\Framework\v4.0.30319;D:\sytemapps\Python27;%M2_HOME%;%JAVA_HOME%/bin;C:\Developer\Android\sdk\platform-tools\;%GRADLE_HOME%\bin;%DEVKIT_HOME%\bin;%DEVKIT_HOME%\mingw\bin
Issue might be becuase of environment variable path name. For maven environment varibale name should be M2_HOME or MAVEN_HOME(for older version)

A: Details for the bounty:
Here is the output to mvn -v:

A: In my case,the problem was not with maven nor java.
I fixed it by editing values in regex by following this answer: https://superuser.com/a/727323
Quoted from the answer: "

*

*Open the Registry Editor (press +R, type regedit and hit Enter) .

*Navigate to HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun and clear the values.

*Also check HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun.

"

A: There is a pre and post script mechanism in the mvn.bat.
The %HOME%\mavenrc_pre.bat and the %HOME%\mavenrc_post.bat files. They are executed before and after the maven executable.
It is possible that the mavenrc_post.bat file is exists in your path and it contains something what can not be found during the mvn -v.
This usually happens on corporate machines when the administrators sets something up there.
You can validate it by two ways:

*

*Set the MAVEN_BATCH_ECHO as it was commented by Robert Scholte (set MAVEN_BATCH_ECHO=on). This will echo the batch commands so you can figure out which command causes the error message.

*You can disable the pre and post rc execution by setting the MAVEN_SKIP_RC to anything (set MAVEN_SKIP_RC=true).

Note: The mvn.bat is tricky about the location of the %HOME% as it allows overrides but by default that is the %HOMEDRIVE%%HOMEPATH% value.

A: As a workaround (and step forward) try with Maven Wrapper:
https://github.com/takari/maven-wrapper
mvnw.cmd clean install

A: If you are developing an JavaFX application using Maven, you don't have to download the JavaFX SDK. You can just specify the modules and the versions you want in the pom.xml.
<plugins>
    <plugin>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-maven-plugin</artifactId>
        <version>0.0.5</version>
        <configuration>
            <mainClass>HelloFX</mainClass>
        </configuration>
    </plugin>
</plugins>

add above plugin and the dependency into the pom file
<dependencies>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>15.0.1</version>
    </dependency>
</dependencies>

No SDK, No path setting. It works for me.
You may find further help in this open jfx documentation


text:
Q: Setting zmin/zmax in groupplot confuses colorbar creation (colorbar is 3d) When using groupplots and setting zmin and/or zmax in the groupplot environment manually, pgfplots generates a (broken) 3d legend:

I assume the issue is that groupplot passes the zmin/zmax settings to the colorbar axis environment as well, resulting in the existential crisis making the colorbar 3d.
Omitting the settings from the global groupplot environment and passing them manually to each \nextgroupplot works. But I thought this was still worth posting in case there's a better solution or in case this is a bug that needs to be resolved.
MWE:
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\usepgfplotslibrary{groupplots}

\begin{document}
\begin{tikzpicture}

  \begin{groupplot}[%
    group style={
      group size=2 by 1,
      horizontal sep=2cm,
    },
    zmin=-10,
    zmax=10,
    colorbar horizontal,
  ]

    \nextgroupplot
    % \nextgroupplot[zmin=-10,zmax=10] % Works if global zmin/zmax are commented out.
      \addplot3[surf] {x+y};

    \nextgroupplot
    % \nextgroupplot[zmin=-10,zmax=10] % Works if global zmin/zmax are commented out.
      \addplot3[surf] {x+y};

  \end{groupplot}
\end{tikzpicture}
\end{document}

A: You are right, the options are not reset for colorbar.
I have fixed this in pgfplots. You can activate the fix in your tex files by means of
\pgfplotsset{
    every colorbar global/.append style={
        zmin=,zmax=,
    }
}

Adding this to your preamble leads to


text:
Q: Reversible 4-switch buck-boost? Can a 4-switch buck-boost be reversible?

The base scheme seems symmetrical but I did not find any reversible design.
Do you have an exemple of such a design?

A:
Can a 4-switch buck-boost be reversible?

Yes, it is inherently bidirectional, but for it to work, the circuit in charge of driving the FETs must support it. If that's the case, it can control current or voltage on one side, or the other.
Many such cases, here's an example from TI.


text:
Q: Conversion Function with decltype(auto) in C++14 class A {
    public:
        int num;
        A ( int param ) : num( param ) {}
        operator decltype( auto )( ){ return num; }
};

class B {
    public:
        int num;
        A objA;
        B ( int param ) : num( param ), objA( param ) {}
      //operator A( )       { return objA; }         // Works               // #1
      //operator int( )     { return objA; }         // Works               // #2
      //operator char( )    { return objA; }         // Actually Not Needed // #3
      //operator double( )  { return objA; }         // Actually Not Needed // #4
        operator decltype( auto )( ){ return objA; } // Does NOT Work       // #5
};

int main(){

    A objA( 1 );
    int    x1 =   int( objA );
    char   y1 = (char) objA;
    double z1 =        objA;

    B objB( 2 );
    A objA2     = objB;
    int      x2 = objB;
    char     y2 = objB;
    double   z2 = objB;

    return 0;
}

This code does not compile neither with clang nor with gcc, so I assume it is not correct. However, if I comment line #5 and uncomment lines #1 and #2 the program works correctly in both compilers (lines #3 and #4 are not really required).
As far as I know, the necessary conversion sequences are defined in both scenarios. Does anyone know why this program is not correct? What am I missing?

A: decltype(auto)  will get the exact type (including references and pointers) of the type you're returning. For class A your conversion operator will return an int, and for class B you will get it to return a class A. I think your belief is that operator decltype(auto) (){/*...*/} will try to return the class for which the conversion is needed, when in fact you would need a template to do so:
class A {
    public:
        int num;
        A ( int param ) : num( param ) {}

        template<class T>
        operator T(){ return static_cast<T>(num); }
};

class B {
    public:
        int num;
        A objA;
        B ( int param ) : num( param ), objA( param ) {}

      template<class T>
      operator T ( ){ return static_cast<T>(objA); }
};

Live Demo

A: Note that implicit conversion sequence could contain only one user-defined conversion. Then the code won't work for int x2 = objB;; B converts to A and A converts to int are both user-defined conversion.
If you provide the operator int() in B, it works fine because B could be converted to int directly. (And also works with char and double, to which int could be converted to by standard conversion.)


text:
Q: Flutter - show how many items scrolled in gridview i am trying to implement like the below image.

I have a grid view which has 2 columns in which i am displaying my list.

As you can see in the above image it is showing 175/67 products.
my logic is i am giving my grid view a scroll controller.
I am adding a listener to that controller but i think my logic or calculation is wrong.
below is my code :
ScrollController _scrollController = new ScrollController();

in initstate i am giving adding a listener to scroll controller
_scrollController.addListener(_scrollListener);

void _scrollListener() {
    setState(() {
      debugPrint(_scrollController.offset.toString());
      debugPrint(count.toString());
      debugPrint(((_scrollController.offset / count).round()).toString());
      index = (_scrollController.offset / count).round();
      print(index);
    });
  }

the count is the total items in my list i.e 67.
as i scroll down it is giving wrong output.
please tell me where i am going wrong.
where my logic has gone wrong?
below is my grid view code:
DragSelectGridView(
                      shrinkWrap: true,
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        childAspectRatio: (itemWidth / itemHeight),
                        crossAxisCount: 2,
                      ),
                      physics: ClampingScrollPhysics(),
                      gridController: gridController,
                      scrollController: _scrollController,
                      itemCount: items.length,
                      itemBuilder: (context, index, selected) {

                        return ProductCard(
                          data: items[index],
                          isSelected: selected,
                        );
                      },
                    ),

Thanks in Advance!!!

A: You can use the ScrollablePositionedList to get the index of current visible items. Check my example app here:
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

const numberOfItems = 500;
const randomMax = 1 << 32;

void main() {
  runApp(ScrollablePositionedListExample());
}

class ScrollablePositionedListExample extends StatelessWidget {
  const ScrollablePositionedListExample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Example App',
      home: const SampleApp(),
    );
  }
}

class SampleApp extends StatefulWidget {
  const SampleApp({Key? key}) : super(key: key);

  @override
  _SampleAppState createState() => _SampleAppState();
}

class _SampleAppState extends State<SampleApp> {
  final ItemScrollController itemScrollController = ItemScrollController();
  final ItemPositionsListener itemPositionsListener =
      ItemPositionsListener.create();
  late List<Color> itemColors;

  @override
  void initState() {
    super.initState();
    final colorGenerator = Random(42490823);
    itemColors = List<Color>.generate(numberOfItems,
        (int _) => Color(colorGenerator.nextInt(randomMax)).withOpacity(1));
  }

  @override
  Widget build(BuildContext context) => Material(
        child: OrientationBuilder(
          builder: (context, orientation) => Column(
            children: <Widget>[
              Expanded(
                child: ScrollablePositionedList.builder(
                  itemCount: numberOfItems,
                  itemBuilder: (context, index) => item(
                    index,
                  ),
                  itemScrollController: itemScrollController,
                  itemPositionsListener: itemPositionsListener,
                  scrollDirection: Axis.vertical,
                ),
              ),
              positionsView,
            ],
          ),
        ),
      );

  Widget get positionsView => ValueListenableBuilder<Iterable<ItemPosition>>(
        valueListenable: itemPositionsListener.itemPositions,
        builder: (context, positions, child) {
          int? currentPosition;
          if (positions.isNotEmpty) {
            currentPosition = positions
                .where((ItemPosition position) => position.itemLeadingEdge < 1)
                .reduce((ItemPosition max, ItemPosition position) =>
                    position.itemLeadingEdge > max.itemLeadingEdge
                        ? position
                        : max)
                .index;
          }
          return Container(
              color: Colors.grey,
              padding: EdgeInsets.all(10),
              child: Text('${currentPosition ?? ''}/$numberOfItems}'));
        },
      );

  Widget item(int i) {
    return InkWell(
      // You can still click on the item here, for example put it in to the cart, etc
      onTap: () => Navigator.of(context).push(MaterialPageRoute(
          builder: (context) => Scaffold(
                appBar: AppBar(),
              ))),
      child: SizedBox(
        height: 150,
        child: Container(
          color: itemColors[i],
          child: Center(
            child: Text('Item $i'),
          ),
        ),
      ),
    );
  }
}

A: look at this code and see dose it useful or not
 NotificationListener<ScrollNotification>(
                                onNotification: (notification) {
                                  //get height of each item
                                  var height=notification.metrics.maxScrollExtent/items.length;
                                  //get position of item
                                  var position=((notification.metrics.maxScrollExtent-notification.metrics.extentAfter)/height).round();
                                  print('postion is $position and the lenght is ${_catcontroller.products.length}');
                                  return true;
                                },

A: GridView.builder(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
  itemBuilder: (_, index) => FlutterLogo(),
  itemCount: 4,)


text:
Q: Laravel's Storage::makeDirectory returns mkdir: invalid argument So I'm trying to create a new directory in C:/..../public/videos folder when somebody uploads a video, using the following code:
if ($request->hasFile('video')) {
    $newDir = public_path('videos\\' . $story->story_id);
    Storage::makeDirectory( $newDir, 0755, true);
    $request->file('video')->move($newDir);
 }

But I get this error:

ErrorException in Local.php line 350: mkdir(): Invalid argument in
  Local.php line 350 at HandleExceptions->handleError('2', 'mkdir():
  Invalid argument',
  'C:\xampp\htdocs\qanda2\vendor\league\flysystem\src\Adapter\Local.php',
  '350', array('dirname' => 'C:\xampp\htdocs\qanda2\public\videos\31',
  'config' => object(Config), 'location' =>
  'C:\xampp\htdocs\qanda2\storage\app\C:\xampp\htdocs\qanda2\public\videos\31',
  'umask' => '0', 'visibility' => 'public')) at
  mkdir('C:\xampp\htdocs\qanda2\storage\app\C:\xampp\htdocs\qanda2\public\videos\31',
  '493', true) in Local.php line 350 at
  Local->createDir('C:\xampp\htdocs\qanda2\public\videos\31',
  object(Config)) in Filesystem.php line 259 at
  Filesystem->createDir('C:\xampp\htdocs\qanda2\public\videos\31') in
  FilesystemAdapter.php line 276

It seems like makeDirectory automatically adds C:\xampp\htdocs\qanda2\storage\app\ in front of my path.
Is there any workaround for this? I've been struggling with this for a while now and I can't find anything about this issue.

A: To create a directory, you should use File, like this:
if ($request->hasFile('video')) {
   $newDir = public_path('videos\\' . $story->story_id);
   File::makeDirectory( $newDir, 0755, true);
   $request->file('video')->move($newDir);
}


text:
Q: Is there an analytical function in mysql to solve this issue? I have a mysql table like below
id   trader price
111   abc    5
222   xyz    5.20
333   abc    5.70
444   xyz    5
555   abc    5.20

I want to have a result to find the number of times each trader increased or decreased price
as below
id   trader price  lagged_price   flag
111   abc    5
222   xyz    5.20   5
333   abc    5.70   5.20        increased
444   xyz    5      5.70        increased
555   abc    5.20   5           reduced
                    5.20        increased

lagged_price is the column which lags the original column price. I need to have a flag saying that at a particular time the trader increased or decreased price
in the above case the final result is
trader  abc increased price twice
 trader xyz increased price ones and decreased price ones

A: I see you have asked this question differently at post: Compare rows in same table in mysql
Nevertheless, here is a solution for the above: (assuming your table is called 'tab', and the IDs actually decrease, and so 'lag' means 'before' as it looks like in your example data)
SELECT a.id, a.trader, a.price, b.price as lagged_price
     , case when a.price > b.price then 'increased'
            when a.price < b.price then 'decreased'
            else 'same'
       end as flag
  FROM tab a
  JOIN tab b
    ON a.trader = b.trader AND a.id > b.id
  LEFT OUTER JOIN tab c
    ON a.trader = c.trader AND a.id > c.id AND b.id < c.id
 WHERE c.id IS NULL

You can see the details of why this works in my answer at your other question.
Hope this helps!
john...


text:
Q: Android Progress Custom Colors I'm trying to create a progress bar like in the picture below:

I don't need to create thise separations, my main goal is to find out how to to create the green colour for the current progress, and the grey colour for the background.
Thanks

A: I'm mostly pulling my answer from here. Your question has a lot of similarities, but I'm unsure if they are close enough to be closed. In the linked question, they use the ProgressBar View by defining it in the layout.xml:
<ProgressBar
android:id="@+id/ProgressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:maxHeight="10dip"
android:minHeight="10dip"
android:progress="50"
android:progressDrawable="@drawable/greenprogress" />

It should be noted that the last attribute is a drawable. This can be any drawable resource, but I think your best best is going to be to follow suit with their solution and create a similar xml file. In this case, greenprogess.xml (note that the file name matches "@drawable/greenprogress" above:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
    <shape>
        <corners android:radius="5dip" />
        <gradient
            android:startColor="#ff9d9e9d"
            android:centerColor="#ff5a5d5a"
            android:centerY="0.75"
            android:endColor="#ff747674"
            android:angle="270"
        />
    </shape>
</item>

<item android:id="@android:id/secondaryProgress">
<clip>
    <shape>
        <corners android:radius="5dip" />
        <gradient
                android:startColor="#80ffd300"
                android:centerColor="#80ffb600"
                android:centerY="0.75"
                android:endColor="#a0ffcb00"
                android:angle="270"
        />
    </shape>
</clip>
</item>
<item
    android:id="@android:id/progress"
>
<clip>
    <shape>
        <corners
            android:radius="5dip" />
        <gradient
            android:startColor="#33FF33"
            android:endColor="#008000"
            android:angle="270" />
     </shape>
 </clip>
 </item>
 </layer-list>

Also note that the linked Question has a simpler Answer as well. However,I think this will give you more flexibility that you may be searching for.


text:
Q: How to get hidden value from Form when i try to get value on controller value zero always @Html.HiddenFor(x =>x.StreamId, Model.StreamId)

@Html.LabelFor(m => m.StreamId)
<select id="streamlist" name="list" onchange="DDLStream();">
    @for (int i = 0; i < @Model.dtforStream.Rows.Count; i++)
    {
        <option value="@Model.dtforStream.Rows[i][0]">@Model.dtforStream.Rows[i][1].ToString()</option>
    }
</select>

<input type="submit" value="Create" />

function DDLStream() {
    var k = $("#streamlist").val();
    $("#sid").val(k);
    alert(k);
}

A: Could you try this?
$("#StreamId").val(int.parse($("#streamlist option:selected").val()));


text:
Q: Web Page Wont Stop Loading Ive recently added this bit of jQuery to my web page and now the website wont finish loading and the circle that spins is super annoying.
Can anyone help? The code is below:
    (function() {

    var quotes = $(".quotes");
    var quoteIndex = 1;

    function showNextQuote() {
        ++quoteIndex;
        quotes.eq(quoteIndex % quotes.length)
            .fadeIn(1000)
            .delay(2000)
            .fadeOut(1000, showNextQuote);
    }

    showNextQuote();

})();


text:
Q: Insert responsive GMaps in bootstrap's jumbotron I'm using bootstrap jumbotron, and I want insert a google map inside, but I'm having a problem. I'm able to insert the map, but in this jumbtron I have also an alert that isn't shown anymore after I put the map.

            Warning! Best check yo self, you're not looking too good.

Alert that should be shown:

How it is shown after map is inserted:

EDIT:
The alert div is shown below the map, despite the fact the absolute position of the same alert

New code:

            Warning! Best check yo self, you're not looking too good.


text:
Q: Pumping lemma on regular languages I'm fairly new to Formal Languages and I am still learning the pumping lemma.
Is it possible to know if a language is regular without knowing it's grammar?
Consider the language L over alphabet Σ={3,5} of all words for which the arithmetic sum of the constituent symbols is divisible by 5.
Now I don't know if this language is regular or not.
I assumed it to be not regular and tried to prove that it is not regular using Pumping lemma for regular languages.
I took n=6 and 'w' as 335333  here 3+3+5+3+3+3=20 which is divisible by 5, so this word belongs to L.
Sub-strings : x=33, y=53, z=33
So conditions |y|>=1 is true and |xy|<=n i.e. 6 is also true.
(w)^i=x(y)^iz
w^i=33(53)^i33
now for i=2 we get string as 33535333 where sum is 3+3+5+3+5+3+3+3=28, not divisble by 5.
Hence, this language is not a regular language.
But then after some thought I was able to make a DFA, which means that this Language L should be regular.By making a pentagon with edges having 3 and self loops of 5 on each corner.(Can't post the image). Start state as it's final state.
Now I don't know what's wrong in my Pumping lemma proof.
I'd appreciate any hints or comments that may help me.
Many thanks in advance.

A: Your pumping lemma proof goes wrong right away; you say "I took $n=6$". But you don't get to pick $n$.  The pumping lemma only tells you that if $L$ is irregular then there exists some such $n$, not what it will be.
And then you make a similar mistake later, when you pick $u,v,$ and $w$.  You don't get to choose these; your proof must go through for any choice of $u,v,$ and $w$.
Think of the pumping lemma as a game:

*

*Mr. Pumping Lemma gives you a constant $n$.

*You choose a word $w$ in the language of length at least $n$.

*Mr. Pumping Lemma gives you $x$, $y$, and $z$ with $xyz=w$, $|xy|≤n$, and $y$ not empty.

*Now you pick $r$.

*Mr. Pumping Lemma asserts that $xy^rz$ is also in the language.

*If he's wrong, you win.

You don't get to make Mr. Pumping Lemma's moves; he makes them, and your proof must present a strategy that wins even though Mr. Pumping Lemma is trying to beat you.

A: Your proof of irregularity is spelled out a bit confused as you start "I assumed it to be not regular and tried to prove that it is not regular".
Actually, there is a pumping length for this language: If $z$ is a word of length $\ge5$ the it either contains a "5" in the first five letters and can be written as $z=uvw$ with $|u|\le 4$, $v=5$ and clearly also all $uv^kw\in L$; or it contains no $5$ in the first five letters, hence the first five letters are all "3" so that $z=uvw$ with $u=\epsilon$, $v=33333$ and clearly $uv^kw\in L$.


text:
Q: Prove that the property of being isolated is a topological property Let $f:X \to Y$ be a homeomorphism and $A \subset X$ such that $A \cap A'= \emptyset$ prove that $f[A] \cap (f[A])'= \emptyset$ where $A'$ is the derived set  of $A$ and $(f[A])'$ is the derived set of $f[A]$
Can someone help me please? Thanks


text:
Q: Help with Sudo installation commands? How do I use these commands?

For the Trusty version
Type the following commands:
wget -q "http://deb.playonlinux.com/public.gpg" -O- | sudo  apt-key add -
sudo wget http://deb.playonlinux.com/playonlinux_trusty.list -O /etc/apt/sources.list.d/playonlinux.list
sudo apt-get update
sudo apt-get install playonlinux

A: *

*Open a terminal by either searching it on Dash
Super and type terminal; or open it with the shortcut: Ctrl+Alt+t.

*Type the commands, one by one (each line is a single command), manually on the terminal or copy them using Ctrl+c and paste them using Ctrl+Shift+v.

*Press Enter after every command.

*When asked for your sudo password, type it and press Enter, note that your password wont appear on screen, thats for obvious security measures.


text:
Q: Partition into open sets and their boundary Let $\tau$ be a topology on $X$.
Let $\omega \subseteq \tau$ be a set of pairwise disjoint, open subsets of $X$.
Let $Y := \bigcup\limits_{Z \in \omega} Z$.
Question: If $X = Y \cup \partial Y$, does $\omega$ have a name? I.e., which terms are typically used for such $\omega$?

A: As Brian said: $\omega$ is a maximal family of (non-empty) pairwise disjoint open sets in $X$. Maximal is meant in the sense of inclusion.
For suppose $O$ is an non-empty open set in $X$, and suppose $O$ is disjoint from all members of $\omega$ (so that $\omega \cup \{O\}$ is a strictly larger pairwise disjoint family). Then $O \cap Y = \emptyset$, but this means that any $x \in O$ is neither in $Y$ nor in $\partial Y$ which cannot be. So $\omega$ is maximal.
The reverse is also clear: if $\omega$ is maximal, and $x \notin Y$, then let $O$ be any open set that contains $x$. Then $O$ must intersect $Y$, as otherwise $O$ is disjoint from any $Z \in \omega$ so that $\omega \cup \{O\}$ is a larger pairwise disjoint family of non-empty sets, which cannot be. And $O$ intersects $X \setminus Y$ in $x$ already, so $x \in \partial Y$ and so $Y \cup \partial Y = X$.


text:
Q: Bootstrap collapse table row I'm trying to build a table where only some rows collapse (only the first row in this example).
When I click on "Recevability", the collapsing and expanding effect worked great, but the problem I got the same behavior when I click on one of the row...
I would like to see the collapsing and expanding effect only when I click on
"Recevability".
Here is the code :

        Recevability

              item1.1

              item1.2

              item2.1

              item2.2

You can try yourself on jsfiddle :
collapsing rows table on jsfiddle
Can some of you take a look ?

A: If you move the table to another li and place the strong tag in first one you get the results you are looking for. Here's my take on it:

        Recevability

              item1.1

              item1.2

              item2.1

              item2.2

https://jsfiddle.net/f030he9x/


text:
Q: Como identificar o botão que foi clicado? Tenho vários botões e eu gostaria de comparar o texto do botão clicado com uma variável do tipo String.
Isso sem usar isso:
if (evento.getSource() == botaoXl) {
    // Fazer isto...
} else if (evento.getSource() == botaoY) {
    // Fazer aquilo...
}

A: Que tal usar ((JButton) evento.getSource()).getText()?


text:
Q: Issues | How to transfer big file ccv2 blob storage to blob fileshare using azCopy using nodejs cloud function I am trying to transfer big files (of size 50MB, 100MB or more than that).
I wrote a nodejs cloud function - using/implementing azCopy command.
Issue: while transferring its giving error:
Exception: TypeError: Cannot read property 'fromTo' of undefined
How to give this option in code, is there any way to transfer big files from storage to fileshare.
Code snippet:
#copy function
context.log('start copy -------------');
var destination = 'https://<>.file.core.windows.net/testsftpshare/MyTest/test?sv=<>&ss=f&srt=sco&sp=rwlc&se=<>&st=<>&spr=https&sig=<>';
context.log('start copy dst defined-------------');
var jobId = await client.copy(fileFullName, dst);
context.log('jobid -------------',jobId);

var status;
// You use this job ID to check on the progress of your job, and know if it has finished.
context.log('start while loop------------');
while (!status || status.StatusType !== "EndOfJob") {
     var jobInfo = await copyClient.getJobInfo(jobId)
     status = jobInfo.latestStatus;
     await new Promise((resolve, reject) => setTimeout(resolve, 1000));
}
context.log('Create file ${fileName} successfully');

Error at line: var jobId = await client.copy(fileFullName, dst);
Error: Exception: TypeError: Cannot read property 'fromTo' of undefined

A: If AzCopy is not necessary for you, I think this post could also resolve this issue as a workaround.


text:
Q: append columns of data I have tab delimited data that I am exporting a select few columns into another file.  I have:
a b c d
1 2 3 4
5 6 7 8
9 10 11 12

and I get:
b, d
b, d
2, 4
b, d
2, 4
6, 8
b, d
2, 4
6, 8
10, 12
......

I want:
b, d
2, 4
6, 8
10, 12

My code is
f=open('data.txt', 'r')
f1=open('newdata.txt','w')
t=[]
for line in f.readlines():
    line =line.split('\t')
    t.append('%s,%s\n' %(line[0], line[3]))
    f1.writelines(t)

What am I doing wrong???  Why is it repeating?
PLease help
Thanks!!

A: The indentation is wrong so you are writing the entire array t on every iteration instead of only at the end. Change it to this:
t=[]
for line in f.readlines():
    line = line.split('\t')
    t.append('%s,%s\n' % (line[0], line[3]))
f1.writelines(t)

Alternatively you could write the lines one at a time instead of waiting until the end, then you don't need the array t at all.
for line in f.readlines():
    line = line.split('\t')
    s = '%s,%s\n' % (line[0], line[3])
    f1.write(s)

A: As already mentioned, the last line is incorrectly indented. On top of that, you are making things hard and error prone. You don't need the t list, and you don't need to use f.readlines().
Another problem with your code is that your line[3] will end with a newline (because readlines() and friends leave the newline at the end of the line), and you are adding another newline in the format '%s,%s\n' ... this would have produced double spacing on your output file, but you haven't mentioned that.
Also you say that you want b, d in the first output line, and you say that you get b, d -- however your code says '%s,%s\n' %(line[0], line[3]) which would produce a,d. Note TWO differences: (1) space missing (2) a instead of b.
Overall: you say that you get b, d\n but the code that you show would produce a,d\n\n. In future, please show code and output that correspond with each other. Use copy/paste; don't type from memory.
Try this:
f = open('data.txt', 'r')
f1 = open('newdata.txt','w')
for line in f: # reading one line at a time
    fields = line.rstrip('\n').split('\t')
    # ... using rstrip to remove the newline.
    # Re-using the name `line` as you did makes your script less clear.
    f1.write('%s,%s\n' % (fields[0], fields[3]))
    # Change the above line as needed to make it agree with your desired output.
f.close()
f1.close()
# Always close files when you have finished with them,
# especially files that you have written to.


text:
Q: Conf files and static files in a deb package I'm using dh_help to build a package template and trying to follow the ubuntu and debian packaging guides for creating a binary package.
How do I tell debuild which file is a conf file and should go for example to /etc/mypkg.conf ?
I've tried to put it under mypkg-0.1/etc/mypkg/fname.conf but debuild ignores it.
The debian guide says all files under etc/ are treated automatically as conf files but it doesn't work for me (http://www.debian.org/doc/maint-guid...ml#s-conffiles).
I've tried putting the conf file under mypkg-1.0/etc/mypkg.conf and under mypkg-1.0/debain/etc/mypkg.conf but it is not included. I also tried to list the file in conffiles but I'm getting an error that it can't be found when building the package.
I also don't understand how to include static files in the package.
Do I have to use the install file to list all the files and folders?
I thought that putting everything with the full path under the mypkgs-0.1 folder should work like it does when using dpkg manually.
Thanks

A: As viraptor said you can put an install command for each file into your debian/rules to install the files into the debian/pkgname directory.
Or you can use a debian/install file to simply list all the files (or just directories) and have a dh_install command in your debian/rules to do it for you.
It seems you are a little confused about how packages are built and which files are included. This is extremely generalized, but when the debian/rules script compiles a program using standard ./configure && make && make install method, it instructs the make install to install the files to debian/pkgname instead of /. Then it knows that everything under debian/pkgname is what should be in the final .deb. If the make install step doesn't put everything in the correct location, then the debian/rules script needs to do that. Previously it seems calling install ... from debian/rules to copy the files to the debian/pkgname directory was common but now using a debian/install file seems to be the preferred method.

A: You don't have to include the package version if you install files via the standard debhelper / debian/rules file. Instead, in the install step do:
install -cm 644 fname.conf $(CURDIR)/debian/mypkg/etc/mypkg/fname.conf

And it should be included properly.


text:
Q: Making a ML model scikit-learn compatible I want to make this ML model scikit-learn compatible:
https://github.com/manifoldai/merf
To do that, I followed the instructions here: https://danielhnyk.cz/creating-your-own-estimator-scikit-learn/ and imported
from sklearn.base import BaseEstimator, RegressorMixin and inherited from them like so:
class MERF(BaseEstimator, RegressorMixin):
However, when I check for scikit-learn compatibility:
from sklearn.utils.estimator_checks import check_estimator

import merf
check_estimator(merf)

I get this error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\hap\anaconda3\envs\a1\lib\site-packages\sklearn\utils\estimator_checks.py", line 500, in check_estimator
    for estimator, check in checks_generator:
  File "C:\Users\hap\anaconda3\envs\a1\lib\site-packages\sklearn\utils\estimator_checks.py", line 340, in _generate_instance_checks
    yield from ((estimator, partial(check, name))
  File "C:\Users\hap\anaconda3\envs\a1\lib\site-packages\sklearn\utils\estimator_checks.py", line 340, in <genexpr>
    yield from ((estimator, partial(check, name))
  File "C:\Users\hap\anaconda3\envs\a1\lib\site-packages\sklearn\utils\estimator_checks.py", line 232, in _yield_all_checks
    tags = estimator._get_tags()
AttributeError: module 'merf' has no attribute '_get_tags'

How do I make this model scikit-learn compatible?

A: From the docs, check_estimator is used to "Check if estimator adheres to scikit-learn conventions."

This estimator will run an extensive test-suite for input validation, shapes, etc, making sure that the estimator complies with scikit-learn conventions as detailed in Rolling your own estimator. Additional tests for classifiers, regressors, clustering or transformers will be run if the Estimator class inherits from the corresponding mixin from sklearn.base.

So check_estimator is more than just a compatibility check, it also checks if you follow all the conventions etc.
You can read up on rolling your own estimator to make sure you follow the convention.
And then you need to pass an instance of your estimator class to check esimator like check_estimator(MERF()). To actually make it follow all the conventions you have to solve every error it throws and fix them one by one.
For example one such check is that the __init__ method only set those attributes that it accepts as parameters.
MERF class violates that:
    def __init__(
        self,
        fixed_effects_model=RandomForestRegressor(n_estimators=300, n_jobs=-1),
        gll_early_stop_threshold=None,
        max_iterations=20,
    ):
        self.gll_early_stop_threshold = gll_early_stop_threshold
        self.max_iterations = max_iterations

        self.cluster_counts = None
        # Note fixed_effects_model must already be instantiated when passed in.
        self.fe_model = fixed_effects_model
        self.trained_fe_model = None
        self.trained_b = None

        self.b_hat_history = []
        self.sigma2_hat_history = []
        self.D_hat_history = []
        self.gll_history = []
        self.val_loss_history = []

It is setting attributes such as self.b_hat_history even though they are not parameters.
There are lots of other checks like this.
My personal advice is to not check all these conditions unless necessary, just inherit the Mixins and the Base classes, implement the needed methods and use the model.


text:
Q: how to return two variables from controller to view in mvc3 Hi Im a new to MVC3 and i am having problem in returning two variables here is my controller code
public ActionResult Create()
    {
        using (var context = new material_managementEntities())
        {
            var blogs = (from cs in context.GROUP_MASTER
                         where cs.GROUP_NAME == "MIC"
                         select cs.ID).FirstOrDefault();

            var droplist = new TRANSACTION();
            droplist.GROUP_MASTER_ID = blogs;
            droplist.GROUP_NAME = "MIC";
            var directory_master = db.DIRECTORY_MASTER.Include(d => d.CATEGORY_MASTER).Include(d => d.REPRESENTATIVE_MASTER);
            droplist.dir_data = directory_master.ToList();
            return View(droplist);
        }

    }

here Transaction is one table and DIRECTORY_MASTER is another and GROUP_MASTER_ID is a foreign key to Transaction table, what i want is the toList data will be displayed in a modalpopup box so i need to pass data available from both tables
here is model
 namespace Material.Models
{
using System;
using System.Collections.Generic;
using System.Web.Mvc;
public partial class TRANSACTION
{
    public int ID { get; set; }
    public int GROUP_MASTER_ID { get; set; }
    public string GROUP_NAME { get; set; }
    public string dir_data { get; set; }
    public string NAME { get; set; }
    public string ADDRESS_DETAILS { get; set; }
    public string CONTACT_PERSON { get; set; }
    public Nullable<int> TEL_NO { get; set; }
    public Nullable<int> CELL { get; set; }
    public Nullable<int> FAX { get; set; }
    public string EMAIL_ID { get; set; }
    public Nullable<int> OPENING_BALANCE { get; set; }
    public Nullable<System.DateTime> OPENING_BALANCE_DATE { get; set; }
    public string VERIFIED { get; set; }

    public virtual GROUP_MASTER GROUP_MASTER { get; set; }
}

}

A: Either you can use a
viewbag.directory_master = (db.DIRECTORY_MASTER.Include(d => d.CATEGORY_MASTER).Include(d => d.REPRESENTATIVE_MASTER)).ToList();

and then iterate your  viewbag.directory_master from your model and display the required ones.
or you can create a custom view model  containing directory_master  and  TRANSACTION like
public class DashboardModel
{
 public TRANSACTION transation{get;set;}
 public List<directory_master>directoryMaster{get;set;}
}

so your action will be like this
public ActionResult Create()
    {
        using (var context = new material_managementEntities())
        {
            var blogId = (from cs in context.GROUP_MASTER
                         where cs.GROUP_NAME == "MIC"
                         select cs.ID).FirstOrDefault();

            DashboardModel dashboardModel= new DashboardModel();
            dashboardModel.transation.GROUP_MASTER_ID = blogId;
            dashboardModel.transation.GROUP_NAME = "MIC";
            dashboardModel.directoryMaster = (db.DIRECTORY_MASTER.Include(d => d.CATEGORY_MASTER).Include(d => d.REPRESENTATIVE_MASTER)).ToList();
            return View(dashboardModel);
        }

    }

A: I would recommend strongly typing your MVC view to take a model of the type you require, and pass that model to the view via an argument in the return function of your controller's action method.


text:
Q: Error While invoking java code from javascript adapter I am using IBM MobileFirst 7.1 and I am calling java code from Javascript adapter. But, I am getting error while calling adapter. Error is:
 {
   "errors": [
      "Ecma Error: TypeError: Cannot call property main1 in object [JavaPackage com.sample.customcode.SendMail]. It is not a function, it is \"object\". (2016-10-
05T10:46:40.941Z\/74c15a587d1ce37bbfce9925722acab7b6321aad\/UsingJavaInAdapter-impl.js#19)"
   ],
   "info": [
   ],
   "isSuccessful": false,
   "warnings": [
    ]
}

I have changed Java compiler level to 1.6 as well as default JRE to 1.6 from 1.7.
But still I am facing same error. This code is working in one project in same eclipse workspace. But in another project this not working.

A: Make sure to also change the Java compiler level for the specific project. Right-click the project and select Properties -> Java Build Path -> Java Compiler.


text:
Q: Unknown sources settings android The issue is that I need to install an apk(non market app) and for this, the user need to activate the unknown source setting, so i send him (if he didn't have it activated) to the settings so he can turn on the option, the issue is that i tested it in different phones and in samsung that option is on applications while in htcs phones is on security. i want send the user to that option  but i don't know how to do it
I read about this and no one knows exactly how to do it
this is my code
    int canInstallFromOtherSources = Settings.Secure.getInt(ctx2,Settings.Secure.INSTALL_NON_MARKET_APPS);
    if(canInstallFromOtherSources == 0)
    {
        Intent intentSettings = new Intent();
        intentSettings.setAction(android.provider.Settings.ACTION_APPLICATION_SETTINGS);
        startActivity(intentSettings);
    }

A: You can do it with the following line (changing to the corresponding action):
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), REQUEST_CODE_ENABLE_LOCATION_PROVIDERS);

Check Android Settings documentation.
I think you should use ACTION_SECURITY_SETTINGS and one of ACTION_APPLICATION_SETTINGS or ACTION_APPLICATION_DEVELOPMENT_SETTINGS.
And here (line 304), you've got a working example of one of my apps: Tureame


text:
Q: Ubuntu 17.10 GDM Auto-Login not working I have selected the setting 'Automatic Login' from within the default Gnome 3 Ubuntu 17.10 control panel app, but it keeps resetting to 'off' after every restart and does not allow me to automatically login.
Any ideas?

A: I think i've found the problem, try to edit /etc/gdm3/custom.conf
and write AutomaticLoginEnable=true
instead of AutomaticLoginEnable=True in my case
(full lowercase for the word "true")
or uncomment this line if it is...

A: For those who are desperate because it continues failing and failing despite using x11 and writing the proper configuration, are you using a docking station?
I figured that under X11, the docking station forces a login: it doesn't load the gdm automatic login settings. Surely a bug.
A workaround is to use the following config instead at /etc/gdm/custom.conf below the [daemon] section:
TimedLoginEnable=true
TimedLogin=<your_username>
TimedLoginDelay=0

It's not as handy as using Automatic Login but at least it works.
You can indeed keep the AutomaticLogin configs if that's already there, those will be loaded and used whenever the docking station is not plugged.
It's interesting to notice that Wayland behaves differently: AutomaticLogin does work with Wayland + docking station, but not with X11.
If you choose Wayland, beware that Wayland does not support the "share screen" button in many common video-call softwares.
EDIT: add some precisions following commentary.

A: Same issue. I've originally changed the "/etc/gdm3/custom.conf" and simply enabled the "AutomaticLoginEnable=True". This was the whole issue: I didn't notice that "True" has to be lowercase.
EDIT:
I was wrong. My autologin works because I'm NOT using the gnome-xorg (the default option for ubuntu) but the gnome classic session.
I can't manage to get the gnome-xorg session to work properly unless I setup a timedlogin which is a little unpleasant.
EDIT 2:
Ok, I finally got enough of this issue, since it's getting ignored. To solve my issue, since I don't care the least about gdm but I still want to use chrome, I've installed lightdm and changed the autologin in the user settings.
In other words:
sudo apt install lightdm

followed by the usual change in the user settings for the autologin.

A: I had to force the loging screen to use xorg and not wayland (not yet supported by nvidia drivers).
Edit as root the file /etc/gdm3/custom.conf.
sudo nano /etc/gdm3/custom.conf

Change the line
#WaylandEnable=false

to
WaylandEnable=false

A: I can confirm that it's a bug in Settings app. When changing the 'Automatic Login' flag under Details->Users it writes True/False values for AutomaticLoginEnable in "/etc/gdm3/custom.conf".
After manually writing the value AutomaticLoginEnable=true the auto-login works.

A: I had to set two variables, to make it work:
$sudo gedit /etc/gdm3/custom.conf

And insert the lines:
AutomaticLoginEnable = true
AutomaticLogin = <my user name>

The settings app is buggy, to an extend where it's getting useless as of 11.2017. Hopefuly that will change :)

A: I just had problems with GDM 3.28.3 auto login with 18.04 minimal and gnome-core only. GUI froze completely on boot with the error A start job is running for Hold until boot process finishes up and after long research I accidentally found a solution by disabling the boot splash screen:
# disable splash screen on boot
sudo sed -i 's/splash quiet//g' /etc/default/grub
sudo update-grub

Note: To enable the splash again: sudo gedit /etc/default/grub and make sure splash quiet is again within the quotation marks of GRUB_CMDLINE_LINUX_DEFAULT e.g. GRUB_CMDLINE_LINUX_DEFAULT="splash quiet". Apply the new settings with sudo update-grub.
I hope this saves other people's time. If anyone has an idea why this worked for me please let me know.


text:
Q: Outlook to PDF language character conversion errors I have Adobe Acrobat dc trial and Windows 8.1.
When I try to Convert to Adobe PDF an email with Greek characters from Outlook 2010, some of the Greek characters get changed to Latin.

RIGHT TEXT BEFORE CONVERSION ->  Καλημέρα παιδιά τι κάνετε
WRONG TEXT AFTER CONVERSION   ->  Κaληµέρa paιdιά tι κάνete

In the conversion there are present Greek and Latin characters together.

A: Unicode, charset and font mix problems.
It seems that you have some problem with a mix of unicode/charset/font in the original document.
The Greek characters are not in the first 127 position of the ascii table.
Following the Unicode standard [1] you should find them in the range 0370-03FF [2]. For example the letter alpha is the unicode U+03B1 [3].  As references it follows the ISO/IEC_8859-7 standard[4] called Windows-28597 from the Microsoft.
The problem is that it exists even a font (or more than one) that writes the a as an α, keeping inside the same internal code (the 97). For example Symbol is one of the four standard fonts available on all PostScript-based printers (and so in the latex documents and in the pdf ones), created by adobe and has an internal representation different from the unicode one [5]:
Symbol    α     β   γ   δ   ε   ζ   η   θ   ι   κ   λ   μ
Symbol*   a     b   g   d   e   z   h   q   i   k   l   m
Symbol    ν     ξ   ο   π   ρ   ς   σ   τ   υ   φ   χ   ψ   ω
Symbol*   n     x   o   p   r   V   s   t   u   f   c   y   w
*encoded as ASCII for older versions of the font

See the rendering with different fonts on the this wiki page.
This font however, contains only the complete unaccented Greek alphabet. So it can happens when in a document there is a mix of different fonts and charsets that in the translation something goes lost and you end up with an hybrid representation.
Further references

*

*The amazing zoo of the Character encoding [6].

*Unicode [1] page on wiki.

*A table [2] of rendered unicode ranges.

*The ISO/IEC_8859-7 standard [4]

*Just in case you didn't feel it enough complicated there were different codepages too:
codepage 737 or the less common codepage 869.


text:
Q: How to solve $\int \frac{2x^2-4x+3}{(x-1)^2}\, dx$? My book says the answer to $\int \frac{2x^2-4x+3}{(x-1)^2} \, dx$ is $2x-\frac{1}{x-1}+C$ but symbolab says it is $2x-\frac{2}{x-1}+\frac{4}{x-1}-\frac{3}{x-1}-2+C$. Who is correct and how would I get to the answer? I tried to use u-substitution but that doesn't work because the derivative of $2x^2-4x+3$ is not a multiple of $(x-1)^{-2}$ and the derivative of $x-1$ is not a multiple of $2x^2-4x+3$.

A: Note that
$$2x  \color{red}{-\frac{2}{x-1}+\frac{4}{x-1}-\frac{3}{x-1}} \color{green}{-2+K} = 2x \color{red}{-\frac{1}{x-1}} \color{green}{+C}.$$

A: Note that $ \int \frac{2x^2-4x+3}{(x-1)^2}\, dx = \int \frac{2\left(x-1\right)^2+1}{\left(x-1\right)^2}\, dx = \int 2+\frac{1}{\left(x-1\right)^2}\, dx = 2x -  \frac{1}{\left(x-1\right)} + C$

A: Well both the answers are correct. The thing is what is asked in the question. The answers are exactly same.


text:
Q: cursor control for "python -i" in cygwin When using python in cygwin, you need to use "python -i" to get into interactive mode. This mode however removes my ability to use my arrow keys to go through my history.
When I push the Up-Key, the cursor goes up. When I press DELETE, the character gets deleted. I want my cursor to act like a normal Windows CLI; where it stays on ONE line.


text:
Q: Strategy for game with probability Two people: person $A$ and person $B$ are playing a game.
Person $A$ picks two different natural numbers $x$ and $y$.  He places each number inside an envelope.
Then person $B$ has to pick one envelope and open it.
After he looks at the number inside the envelope, he has a choice, either stay with the same envelope or switch, while he doesn't know what is the second number.
The goal is for person $B$ to find a strategy in which he will find the bigger number with a probability bigger than $\large\frac{1}{2}$.
This is a riddle friend of mine gave me. I am not even sure it is possible. With a probability of $\large \frac{1}{2}$ is easy, you just choose randomly.
Do you have any idea how to do it or a hint you could give me?

A: Suppose you open an envelope and see a number $n$. You need to decide whether to switch or stay. If you always decide the same way for any given value of $n$ then your opponent can, if they know your strategy, always reduce your winning chance to 50%: they just choose two numbers for which you will do the same thing.
So when you see $n$ you must use a random strategy: switch with some probability $p_n$, and stay with probability $1-p_n$. Now exactly the same argument means that all the values of $p_n$ for the different $n$ must be different, since otherwise your opponent can choose numbers $m$ and $n$ with $p_m=p_n$, holding you to 50%.
One you've got this far, it makes sense that if $m<n$ then $p_m>p_n$, and in fact any sequence of probabilities that satisfy this will work. If your opponent picks $m$ and $n$ then you will end up with $n$ with probability $\frac12p_m+\frac12(1-p_n)>\frac12$. (For example, you might use $p_n=1/n$.)


text:
Q: Java - Possible to Package some external jars, keep others separate? I'm using eclipse to package a program into a runnable jar (Export...>Java>Runnable JAR File). I select the option Package required libraries into generated jar, but one external jar can't be packaged.  Is it possible to package the rest of my external jar dependencies while keeping this one outside the main jar?  I'm not looking to use maven or ant or anything like that.

A: You can, just add the library to the /lib/ext directory of your JRE.
But this basically means you have to have control of the JRE on the target environment.


text:
Q: PC mic+audio to iPhone'ish plug I have a good headset with a mic which has a plug like that which is on the standard iPhone ear buds. In other words, one plug for both mic and audio.
I'd like to use this headset with my computer. Is there anything like a USB adapter or a 'iPhone plug to mic plug and audio plug'-splitter or something?
I've tried searching, but not really sure what this is even called.

A: The Apple-jack :) is actually a TRRS (Tip-ring-ring-sleeve) 1/8th inch plug.

There are numerous adapters that will split out the two functions, here for example.
Apple has been known, however, to wire up their 1/8th inch jacks non-standard, making 3rd party adapters not work correctly.  Not sure if your headset in particular falls into this category, but just be aware.
From the Wikipedia article on TRS:

Several mobile phones, particularly smartphones, feature 3.5 mm TRRS
  connectors to facilitate attaching headphones/hands-free kits. 2
  different forms are frequently found, both of which place left audio
  on the tip and right audio on the first ring (mirroring the
  configuration found on stereo connectors). Where they differ is in the
  placement of the microphone and return contacts. The first, which
  places the return signal on the second ring and the microphone on the
  sleeve, is used by Apple's iPhone line, Samsung's Galaxy Nexus and
  Nokia phones, among others. The second, which reverses these contacts,
  is used by other Samsung smartphones and some Sony/Sony Ericsson
  phones.

A: I think you are looking for an adapter similar to this (3.5mm female to male usb): http://www.amazon.com/GTMax-Female-Microphone-Adapter-Lanyard/dp/B0032AEF42 .

A: Here ya go
http://www.showmecables.com/product/iPhone-Head-Set-Breakout-Cable-3-5mm-TRRS-Jack-to-Dual-3-5mm-Stereo-Plug-6-IN.aspx


text:
Q: Add BitLocker password to existing encrypted system drive (without a TPM) My laptop is not equipeed with a TPM. I have enabled bypass group policy to use BitLocker with a USB thumb drive.
Under certain circumstances I would like to upgrade my authentication by adding a PIN to an exsting encrypted system drive. Or later to remove the USB thumbdrive authentication in favour of PIN/password only.
I have already set up the group policy to allow these settings but I can find no option in the BitLocker settings screen to upgrade security for my system drive. It is instead available to my secondary drive (which is auto-decrypted when the system boots up).
I imagine that I could decrypt the entire drive and perform re-encryption with new settings.
I want to ask if there is any shorter way to accomplish this

A: Well, after thinking a bit about it I concluded an answer made of good sense.
If it was ever possible to add a PIN to an existing Bitlocker-encrypted system drive that is unlocked with a USB key in absence of a TPM the added security would be exactly equal to zero. Only secure procedure is to fully decrypt the disk and re-encrypt using stronger security
Why can't be this done on a USB-powered encryption (and vice versa)?
BitLocker uses symmetric cryptography. I haven't gone into the details but using a PIN or a thumb drive with a secret that can reveal the encryption key equals (from the security point of view) to assuming that the drive or the PIN is the key.
So you have your friendly setup where you already exported the key to a USB drive or memorized under the form of a PIN/password. That key exists, and that key can decrypt the disk.
Suppose that the key gets compromised. The system asks for an additional password. But since the key is contained in the thumb drive, an attacker with physical disk access may still use the key to decrypt the drive because the symmetric key is all the information needed to decrypt information. The attacker can use any software under his control that does not require silly additional authentication
Why CAN this be done on a TPM setup?
The TPM is a different device. The key, or the secret information that is used to derive the decryption key, exists within the bounds of an active computer system, acting as a vault. If you change your vault's lock, the vault will refuse to open without new authentication.
The OS, who controls (owns) the TPM may kindly request the TPM not to release the key anymore unless additional authentication is provided. With a TPM and with the exception of the escrow keys that BitLocker generates, the key can never be exposed. One can change the PIN/password at will, still no one possesses a medium with the byte array of the secret key available.


text: Q: Synonym for un-scientific book by researcher I am looking for a synonym for a kind of book/genre, that contains interesting information, but is not aimed at the scientific community, being polemical / political and not stringent enough to be academic. For instance "Weapons of Math Destruction" by Cathy O'Neil.


text:
Q: Searching a vector inside another vector I am trying to see if vector v1 is inside vector v2.
For example, if v1= (b, a) and v2 = (g, e, f, a, b). I need to check both b and a present in v2.
The following code will help me only if order is same.
std::search(v2.begin(), v2.end(), v1.begin(), v1.end());

i.e., if v2 = (g, e, f, b, a)
Currently I am achieving through following way
for (std::vector<std::string>::iterator it = v1.begin(); it != v1.end(); ++it)
{
    if (std::find(v2.begin(), v2.end(), *it) != v2.end())
        std::cout << "found\n";
    else
        std::cout << "not found\n";
}

Is there a way to achieve using the above using std::search?

A: You could use std::set_intersection:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
    std::vector<char> v1{'a','b','e','f','g'};
    std::vector<char> v2{'a','b'};
    std::sort(v1.begin(), v1.end());
    std::sort(v2.begin(), v2.end());

    std::vector<char> v_intersection;

    std::set_intersection(v1.begin(), v1.end(),
                          v2.begin(), v2.end(),
                          std::back_inserter(v_intersection));
    for(int n : v_intersection)
        std::cout << n << ' ';
}

See the reference
Please note that it is required that the two vectors are sorted using the same sort function prior to using std::set_intersection because it relies on comparing elements using operator<
Additionally you could use std::includes
#include <iostream>
#include <algorithm>
#include <cctype>
#include <vector>

int main()
{
  std::vector<char> v1 {'a', 'b', 'c', 'f', 'h', 'x'};
  std::vector<char> v2 {'a', 'b', 'c'};
  std::vector<char> v3 {'a', 'c'};
  std::vector<char> v4 {'g'};
  std::vector<char> v5 {'a', 'c', 'g'};

  for (auto i : v1) std::cout << i << ' ';
  std::cout << "\nincludes:\n" << std::boolalpha;

  for (auto i : v2) std::cout << i << ' ';
  std::cout << ": " << std::includes(v1.begin(), v1.end(), v2.begin(), v2.end()) << '\n';
  for (auto i : v3) std::cout << i << ' ';
  std::cout << ": " << std::includes(v1.begin(), v1.end(), v3.begin(), v3.end()) << '\n';
  for (auto i : v4) std::cout << i << ' ';
  std::cout << ": " << std::includes(v1.begin(), v1.end(), v4.begin(), v4.end()) << '\n';
  for (auto i : v5) std::cout << i << ' ';
  std::cout << ": " << std::includes(v1.begin(), v1.end(), v5.begin(), v5.end()) << '\n';

  auto cmp_nocase = [](char a, char b) {
    return std::tolower(a) < std::tolower(b);
  };

  std::vector<char> v6 {'A', 'B', 'C'};
  for (auto i : v6) std::cout << i << ' ';
  std::cout << ": (case-insensitive) "
            << std::includes(v1.begin(), v1.end(), v6.begin(), v6.end(), cmp_nocase)
            << '\n';
}

OUTPUT:
a b c f h x
includes:
a b c : true
a c : true
g : false
a c g : false
A B C : (case-insensitive) true

Here is the reference page
(the example above is direct from the reference)
Either one could do the job depending on what you are trying to do.


text:
Q: Material UI- My Card Component is getting added to my Appbar. I want the cards to show up once a button the Appbar is clicked The naming conventions are off. Please ignore those.
Part of the code for the Appbar:
const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1
  },
  title: {
    flexGrow: 1
  }
}));

export default function Appp() {
  const classes = useStyles();
  const history = useHistory();

  return (

      <Router>
        <AppBar position="static" display="flex">
          <Toolbar>
            <Typography variant="h6" className={classes.title}>
              Employee Management
            </Typography>
            <Button
              variant="contained"
              color="secondary"
              className={classes.button}
            >
              <Link to="/emp">Fetch Employees</Link>
            </Button>
            <Switch>
              <Route exact path="/emp" render={(props) => <App {...props} />} />
            </Switch>
          </Toolbar>
        </AppBar>

      </Router>

  );
}

The App component ("user" is JSON data received from an API call):
 return (

      {user &&
        user.map((singleUser) => {
          return (
            <SimpleCard
              nam={singleUser.name}
              uname={singleUser.username}
              ph={singleUser.phone}
              wb={singleUser.website}
            ></SimpleCard>
          );
        })}

  );
}

The SimpleCard Component:
export default function SimpleCard(props) {
  const classes = useStyles();

  return (
    <Card padding={6} style={{ backgroundColor: "red", display: "inline-block" }}>
      <CardContent>
        <Typography
          className={classes.title}
          color="textSecondary"
          gutterBottom
        >

{props.nam}

        </Typography>
        <Typography variant="h5" component="h5">
          #{props.uname}
        </Typography>
        <Typography className={classes.pos} color="textPrimary">
          adjective
        </Typography>
        <Typography variant="body2" component="p">
          well meaning and kindly.

        </Typography>
      </CardContent>
    </Card>
  );
}

So when the Fetch Employees button is clicked, I want the cards with the information to show up. However they are just getting added in the Appbar and the UI is a mess.

A: return (

      <Router>
<AppBar position="static" display="flex">
          <Toolbar>
            <Typography variant="h6" className={classes.title}>
              Employee Management
            </Typography>
            <Button
              variant="contained"
              color="secondary"
              className={classes.button}
            >
              <Link to="/emp">Fetch Employees</Link>
            </Button>
          </Toolbar>
        </AppBar>

        <Switch>
              <Route exact path="/emp" render={(props) => <App {...props} />} />
            </Switch>
      </Router>

  );

You just need to remove your navigator out of the bar


text:
Q: Knockout CSS data binding does not work with Razor syntax Not sure why the following Razor syntax won't work:
@Html.LabelFor(model => model.Description, new { @data_bind = "css: LabelCSS" })

If I use regular HTML syntax with attribute to bind to knockout, it works:
Description

My knockout ViewModel:
function ViewModel(dataFromServer) {

        var self = this;
        self.EnableDesc = ko.observable(dataFromServer.EnableDesc);

        self.LabelCSS = ko.computed(function () {
            return self.EnableDesc() ? "control-label" : "control-label-gray";
        }, self);
}

A: Thanks to mxmissile for answering my question:
The syntax to be used is:
@Html.LabelFor(model => model.Description, new { data_bind = "attr: { 'class': LabelCSS }" })


text:
Q: Unsupported operand types for 'NoneType' and 'datetime.datetime' I am tasked with getting this to work, but the initial port scan code wasn't working on outdated Python versions. I am extremely new to Python coding and hopefully someone can point out what is causing the above error.
#!/usr/bin/env python
import sys
from socket import *
from datetime import datetime

START_PORT = 1
END_PORT = 1025

target = input(">>> Enter target's IP address: ")

start_time = datetime.now().replace(microsecond=0)
print("\nScan started at %s \n") % (start_time)

def scan_target(target, port):
    try:
       return_code = 1

       s = socket(AF_INET, SOCK STREAM)

       err_code = s.connect_ex((target,port))

       if err_code == 0:
           return_code == err_code

       s.close()

    except:
        print("Error: Could not establish connection!")
        sys.exit(0)

    return return_code

for port in range(START_PORT, END_PORT)
    return_code = scan_target(target, port)

    if return code == 0:
        print( "*** Port %d: OPEN") % (port)

end_time = datetime.now().replace(microsecond=0)
duration = end_time - start_time


text:
Q: convolutional neural network vs Genetic algorithms which one has a better object recognition ratio I have read good things about genetic algorithms and convolutional neural networks when it comes to object recognition. I would like to train a software to recognize any computer that has ever been on my  computer network without looking at the mac address because it can change.Typical object recognition.
What would be the best algorithm to use in this case. CNN or GA.

A: You task is to recognize devices connected to a network and recognize these. I'm guessing the output needs to be one of a few hundred computers connected to your network, and this could increase as your network expands (or with time if you have many guests using it temporarily).
As Gung has already mentioned in the comments, CNNs are neural networks which use an optimization method to train the network; while Genetic Algorithms are a class of optimization methods which can't "learn" anything. The paper you've referred to uses a CNN like series of transformations on the character image before it passes on the final vector to evaluate and optimize by the GA. The author could have used another optimizer just as well.
A CNN with large no of layers might not be required for your objective unless you're already tried other methods such as Random Forests, Gradient Boosted Trees, SVMs, or simpler Neural Networks. I would suggest trying to train a simpler neural network for this purpose.
Your first step would be to identify which features are you going to use to identify a computer uniquely - OS fingerprint, open ports, TCP/IP parameters, etc.
Regarding your statement about a user being able to easily change a mac address: if users are so skilled (or intent in hiding their identity) that they are able to change an interface's MAC address, then they could easily spoof all the other parameters you may need to track them too - this makes choosing the right features much more difficult.


text:
Q: JQuery Player - Doesn't work on Chrome I am using a music player written in Jquery which I converted it into a radio player.
The problem is It doesn't work on google chrome
In my index.php file, (written in html5 also) I have created the object with these features
$(document).ready(function(){
  var myCirclePlayer = new CirclePlayer("#jquery_jplayer_1",
  {
    //m4a: "http://46.20.4.50:8030/",   //Safari & Fenomen
    m4a: "http://stream-uk1.radioparadise.com:8034",
    oga: "http://stream-sd.radioparadise.com:9000/rp_192m.ogg" //Firefox
    //m4a :"muzikler/0.m4a",
    //oga :"muzikler/0.ogg"
  }, {
    cssSelectorAncestor: "#cp_container_1",
    canplay: function() {
      $("#jquery_jplayer_1").jPlayer("play");
    }
  });
});

I was wondering if chrome doesn't support .ogg or .m4a but I don't think so since I ve tried it on another player.
In the .js file I ve also adapted jquery 1.4.4 since 1.3.2 doesnt detect Chrome as webkit.
$.jPlayer.uaBrowser = function( userAgent ) {
  var ua = userAgent.toLowerCase();

  // Useragent RegExp
  var rwebkit = /(webkit)[ \/]([\w.]+)/;
  var ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/;
  var rmsie = /(msie) ([\w.]+)/;
  var rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/;
  var match = rwebkit.exec( ua ) ||
              ropera.exec( ua ) ||
              rmsie.exec( ua ) ||
              ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
              [];
  return { browser: match[1] || "", version: match[2] || "0" };
};

What part am I actually missing to fix this issue?
You can take a look at the full js file : http://pastebin.com/HVKGXkCy


text:
Q: Is it possible to make a list of classes without instantiating them as actual objects? I have a set of classes in my program which can be instantiated. Each class has a static method associated with it which updates a particular aspect of that class.
At run time the program chooses to use a number of the classes from the set.
Multiple versions of these classes are then instantiated as objects as the program runs.
Throughout the program there are key points where I need to call the static methods associated with the various classes but only the ones in use that the program picked at run time.
Is it possible for me to make a list/array containing the classes in use without instantiating them? So that I can then just go through that list and call the static method on each class?
The only other way I have found of doing it is instantiating one object for each class in use and storing them in an array and calling the methods from there. This seems a bit inefficient and not very elegant.
Any help is greatly appreciated.

A: You could use reflection to do something like this:
List <Class<?>> classes = new ArrayList<Class<?>>();

// alternatively, classes.add(com.foo.MyClass1.class);
classes.add(Class.forName("com.foo.MyClass1"));
classes.add(Class.forName("com.foo.MyClass2"));
// ...etc

Method m = classes.get(0).getDeclaredMethod("staticFunction");
m.invoke(null); // pass in an instance of the class if this is an instance method

Check out the javadoc for Class and Method.

A: I'm not sure why you want to avoid instantiation, but if the only thing you are doing is calling static methods, there is not reason to create objects. As for your question, you can create an Array of Classes without any problem. Remember that MyClass.class is actually an object of class Class, so this would work :
Class[] classes = new Class[] {MyClass1.class, MyClass2.class};

You can then use your logic to select some of them. When done, you can instantiate them using reflection :
classes[0].newInstance();

Hope it helps, if not, please precise your question. Note that the class objects themselves will be created (not sure you can prevent the class loader to load them).

A: You can have a list of Class objects such as
List<Class> myClasses = new ArrayList<Class>();
To add an item to the list you code something like myClasses.add(Class1.class);
That's one way to store a list of classes, without needing to create an instance of each one.


text:
Q: Unset a single item form a php array embedded in a html site with JS button My question is. I want to press that remove button at the end and remove my item form the session.
how can i do this?
js:
$('.remove button') .click (function() {
removeItem(This);
});

PHP and HTML:
   <?php
  foreach($_SESSION["cart"] as $item) {
  $data = getProducts($pdo, $item);
  if ($data["ColorName"] == NULL) {
      $color = "";
  } else {
      $color = "Color: ".$data["ColorName"]."
";
  }
  if ($data["Size"] == "") {
      $size = "";
  } else {
      $size = "Size: ".$data["Size"]."
";
  }
  print("

1 x ".$data["StockItemName"]."

".$color." ".$size."

Product Code - ".$data["StockItemID"]."

".$data["RecommendedRetailPrice"]."

      <input type=\"number\" value=\"1\" min=\"1\" class=\"quantity-field\">

". $data["RecommendedRetailPrice"] * 1 ."

      <button>Remove</button>

");
  }

I tried using Unset in allot of places, but that doesn't seem to get working :')

A: :)
The solution is rather easy, but requires some explanation in order to be understood.
What you need here is to:

*

*Create a new php file, which would fetch the post data (in this case ID of an element) and then simply unset the key (sub-array), which contains the cart item you want to remove.
You can use $key_to_remove = array_search($_POST['stock_item_id'], array_column($_SESSION["cart"], 'StockItemID')); and then simply unset it unset($_SESSION["cart"][$key_to_remove]);

*Assign id="remove_<?php echo $data["StockItemID"]; ?>" to the
 and data-product-id="<?php echo $data["StockItemID"]; ?>" to the button, so you can identify it for item removal via javascript/jquery and you need that value extracted later for the item you want to remove from the corresponding session array (which is, in this case, $_SESSION["cart"]).

*Create a callback function for removal on('click', function(){});

*Inside that function extract that value data-product-id from the button you just clicked var stock_item_id=$(this).attr('data-product-id');

*Inside the same function, after step 4, create an ajax call to the file from step 1 with the post data from step 4

*On successful execution of an ajax call, delete the corresponding product row you have marked with id="remove_<?php echo $data["StockItemID"]; ?>" in step 2 with the following code $("#remove_"+stock_item_id).remove();
In the end, your code would look like this
YOUR INITIAL PHP AND HTML (With small corrections)
<?php
 foreach($_SESSION["cart"] as $item) {
     $data = getProducts($pdo, $item);
     if ($data["ColorName"] == NULL) {
        $color = "";
     } else {
        $color = "Color: ".$data["ColorName"]."
";
     }
    if ($data["Size"] == "") {
        $size = "";
    } else {
        $size = "Size: ".$data["Size"]."
";
    }
 ?>

                        1

                    x <?php echo $data["StockItemName"]; ?>

                    <?php echo $color." ".$size; ?>

                Product Code - <?php echo $data["StockItemID"]; ?>

        <?php echo $data["RecommendedRetailPrice"]; ?>

        <input type="number" value="1" min="1" class="quantity-field">

        <?php echo $data["RecommendedRetailPrice"]; ?> * 1

        <button data-product-id="<?php echo $data["StockItemID"]; ?>">
            Remove
        </button>

<?php
}
?>

JS
$(document).ready(function(){
    $('.remove button').on('click', function() {
        var stock_item_id=$(this).attr('data-product-id');

        $.ajax({
            url: "new_php_file_created_to_remove_item_from_session_via_ajax.php",
            data:
                {stock_item_id : stock_item_id}
        }).done(function() {
            $("#remove_"+stock_item_id).remove();
        });
    });
});

NEW PHP FILE (new_php_file_created_to_remove_item_from_session_via_ajax.php)
<?php
    $stock_item_id = $_POST['stock_item_id'];
    $key_to_remove = array_search($_POST['stock_item_id'], array_column($_SESSION["cart"], 'StockItemID'));
    unset($_SESSION["cart"][$key_to_remove]);

    if(isset($_SESSION["cart"][$key_to_remove])) {
        return false;
    }
    return true;

For the sake of readability and further maintenance and possible additions, I would strongly recommend you to separate php, html and js code into separate files, but that's only a suggestion. :)


text:
Q: What's the big-O complexity of this recursive algorithm? I am following a course of Algorithms and Data Structures.
Today, my professor said the complexity of the following algorithm is 2^n.
I waited till the lesson was over, approached him and told him I actually believed it was an O(n) algorithm, and I did the computation to prove it, and wanted to show them to it, but he continued to say it was not, without giving me any convincing explanation.
The algorithm is recursive, and its recurrence relation is:
       { 1         if n=1
T(n) = {
       { 2T(n/2)   otherwise

I computed it down to be a O(n), this way:
Let's expand T(n)
T(n) = 2 [2 * T(n/(2^2))]
     = 2^2 * T(n/(2^2))
     = 2^2 * [2 * T(n/(2^3))]
     = 2^3 * T(n/(2^3))
     = ...
     = 2^i * T(n/(2^i)).

We stop when the term inside the T is 1, that is:
n/(2^i) = 1  ==>  n = 2^i  ==>  i = log n
After the substitution, we obtain
T(n) = 2^log n * T(1)
     = n * 1
     = O(n).

Since this algorithm jumped out of a lesson on Merge Sort, I noted how Merge Sort, which notoriously is O(n log n) has a complexity of 2T(n/2) + theta(n) (obviously major then 2T(n/2)), and I asked him why is it, that an algorithm with a lower complexity, gets a higher big-O. Because, at this point, it's counter intuitive for me. He replied, words for words, "If you think that is counter-intuitive, you have serious problem in your math."
My questions are:

*

*Is there any fallacy in my demonstration?

*Wouldn't the last situation be counter-intuitive?

A: First of all, to analyze the complexity of a simple, recursive algorithm, the first stop would be the Master Theorem, where we match your expression T(n) = 2·T(n/2) against the schema T(n) = a·T(n/b) + f(n). By comparing coefficients, we can see that a = 2, b = 2, f(n) = x for some constant x. The Master Theorem then gives us the complexity depending on whether certain relations between the coefficients hold.
Here, the case applies where there exists a c such that f(n) = O(n^c) and c < log_b a, with c = 0 (f(n) = O(1) = O(n^0) and 0 < log_2 2 <=> 0 < 1). Therefore, the Master Theorem tells us that T(n) = Theta(n^(log_b a)) = Theta(n), so that also T(n) = O(n) holds. In other words, you are right.
Your proof checks out, but to be really convincing you should use the proof by induction technique. You've essentially used induction but have not clearly labeled each step, which makes it a bit hard to follow (and, you did it backwards – you should start with the base case T(1), then show that the property holds for T(n+1) for any n rather than starting with the general case and working towards the base case).

A:
"The algorithm is recursive, and it has this complexity: ..."

From the formulation of your question it seems that the function T(n) is not the algorithm to be analyzed but its complexity. In your proof you show that, indeed, the function T behaves asymptotically as an exponential function.
Then the fallacy could be that you are trying to prove the wrong thing. In other words:

*

*You are right that computing T takes linear time (maybe even less, logarithmic time I guess).

*Your professor is right in saying that the complexity of the original algorithm, whose complexity is expressed by T, is exponential.

A: The algorithm will have execution time of O ((log n)^2), because there will be log n steps doubling a number of n bits. The result is O (n). It is easily shown by complete induction that T (n) ≤ n, assuming that n/2 means floor (n/2).
As far as intuition goes, if T (n) = O (2^n) then T (1000) should be around 2^1000. But then T (1000) = 2 * T (500) which should be around 2^501... Slight difference.
Of course n = O (2^n) by the definition of Big-O.
I might suspect that maybe the recursion isn't actually posted here correctly if what your professor says is so off the mark.