text:
Q: Detects sound and sets GPIO I am looking for a solution that detects sound and sets GPIO21 to low and GPIO21 to high, after 5 minutes when there is no sound.
I need it for a streamer (Raspberry Pi) that will run shairport-sync, tidal-connect and spotify. When sound is detected, GPIO should trigger my amplifier.
Unfortunately I can not code python, so I hope someone can help

A: I think you might find this link helpful: Detecting audio. You shouldn't need all of the code in that answer, just the part on detecting silence.
I believe you can use the python gpiozero library for using the GPIO ports. You should be able to treat it as an LED.
import gpiozero     #For GPIO
import time         #To sleep

###REPLACE THIS WITH YOUR OWN FUNCTION (Like the one I posted in the above link)###
def is_silent():
    return True

pin = gpiozero.LED(21)  #Set up the GPIO pin

pin.on()        #Turn it on

seconds_since_sound = 300   #Set seconds since last sound to high

while(True):
    if(is_silent):      #Check if there is no sounds
        if(seconds_since_sound >= 300):         #If there is no sounds and it has been more than 5 mins since the last sound
            pin.on()        #Turn on
        else:
            seconds_since_sound += 1        #Otherwise increment by a second
            time.sleep(1)   #Sleep for a second
    else:
        seconds_since_sound = 0         #If there is a sound then set timer to 0
        pin.off()       #Turn off

Unfortunately I am unable to test if the code works as I do not have access to a raspberry pi.
It looks like the silence detection does not work in python 3.
EDIT:
It looks like you can record the soundcard on some devices using this line of code:
import pyaudio    #import pyaudio
p = pyaudio.PyAudio()   #setup pyaudio
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK_SIZE, input_device_index=2)    #open pyaudio stream

snd_data = array('h', stream.read(CHUNK_SIZE))    #Capture data (should be done in while loop)

return (max(snd_data) > threshold)    #Check if data is louder than threshold

(Change the input device index to point to the output of your sound card)
Once again, I am unable to test if this works as it only runs of python 2. It uses pyaudio.

A: @SolveltPlanet
It is disabled via #dtparam=audio=on and I have Python 2.7.16 installed. Here is aplay -l
**** List of PLAYBACK Hardware Devices ****
card 1: AUDIO [SMSL USB AUDIO], device 0: USB Audio [USB Audio]
  Subdevices: 0/1
  Subdevice #0: subdevice #0


text:
Q: iPhone HTML Parsing child elements with XPath I'm trying to get the 'title' fields and 'background-color' style out of the  element. - I'm so new to objective-c and this is most likly easy...
My HTML (sample repeats with different :

	09

Mu

My Objective-c:
NSString *tutorialsXpathQueryString = @"//a";

NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
NSLog(@"here is url: %@", tutorialsNodes);

NSMutableArray *newTutorials = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in tutorialsNodes) {

    Tutorial *tutorial = [[Tutorial alloc] init];
    [newTutorials addObject:tutorial];

    tutorial.title = [[element firstChild] content];

    tutorial.url = [element objectForKey:@"style"];

    tutorial.title = [element objectForKey:@"title"];

redpajama_set_name: RedPajamaStackExchange


text:
Q: Center figure image and caption in Bootstrap 4 I have a figure containing an image and caption as shown below:

Plot of pressure at different altitudes.

I am using Bootstrap 4 to style the web page. Using the text-center class for the caption, I'm able to center the caption text. I would also like to center the image in the figure. The mx-auto and text-center classes do not work when the image is within a figure (see example below).

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Elit ratione dolorum velit nesciunt aliquid Vitae culpa exercitationem ex animi quis praesentium Fuga sapiente dignissimos deserunt quia officiis nihil. Vero dignissimos excepturi iste ut fugiat! Nostrum quibusdam labore molestiae.

Plot of pressure at different altitudes.

How can I horizontally center the entire figure in the column?

A: The problem is two fold. Your original issue was that you only had .text-center on the figcaption. To center the img and figcaption in the figure, move .text-center to figure instead and that will center the inline img and text in the figcaption horizontally.
Then when you said that didn't work and included the context of the rest of the page, turns out you're wanting the figure to be centered relative to the content around it, too. figure has class .figure, which adds display: inline-block; so it will be left aligned in the .col by default. The easiest way to center the contents of the figure relative to the content outside of the figure is to either remove the .figure class so the element can be it's native display: block and .text-center will center it's contents, or you can add the class .d-block to the figure if you want to retain the .figure class.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Elit ratione dolorum velit nesciunt aliquid Vitae culpa exercitationem ex animi quis praesentium Fuga sapiente dignissimos deserunt quia officiis nihil. Vero dignissimos excepturi iste ut fugiat! Nostrum quibusdam labore molestiae.

Plot of pressure at different altitudes.

A: You can override the "figure" class:
.figure {display: table;margin-right: auto;margin-left: auto;}

.figure-caption {display: table-caption;caption-side: bottom;text-align: center;}

A: Try w-100 text-center class in figure tag.
Your code should look like this:

Plot of pressure at different altitudes.


text:
Q: Unable to plot dynamically updating y-values on Highcharts spline plot I'm trying to dynamically update the points on a highcharts spline plot. I'm accessing a phpMyAdmin database, which holds constantly updating data fields, using a json.AJAX HTTP get request (for its asynchronous updating capabilities).
From what I can tell from the console log, and a little bit of testing, my AJAX HTTP request is successfully grabbing the data from the database and returning it to my host. THE ISSUE IS WITH THE HIGHCHARTS SYNTAX. I don't know how to properly "give" the data to my "y" coordinate for my new point.
See the attached code:

A: You need to add point inside success callback, for example:
success: function (noiseValue, textstatus) {
    if (!('error' in noiseValue)) {
        yourVariable = Number((noiseValue[0])["test"]);
        console.log(yourVariable);
        series.addPoint([x, yourVariable]);
    } else {
        console.log(noiseValue.error);
    }
}


text:
Q: Strange behavior of this simple C file using Visual Studio that creates an Empty list ( 'segmentation fault (core dumped)' - 'nullptr' ) Hi I'm still a total noob about C programming. I'm actually studying lists, and I tried with the following code to understand their behavior. When I compile it and get to terminal, it exits from terminal with a strange value that is not 1 as if 'malloc()' did not create a correct pointer. I do not get the text of the last 'printf()' in case program worked well either. By debugging it, I get a 'segmentation fault (core dumped)' error and an 'p is nullptr' exception. I originally made a more complex code but it gave this error, then I decided to reduce it to this basic code to find the error. I'm sure I'm misunderstanding something about logic behind struct's pointer.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int *v;
    int last;
    int length;
} t_list;

t_list *p;
t_list list;

void makenullList(t_list *p, int dim);

int main(void) {
    int dim;

    printf("put dim: ");
    scanf("%d", &dim);
    getchar();
    printf("\n\n");

    makenullList(p, dim);

    free(p->v);
}

void makenullList(t_list *p, int dim) {

    if ((p->v = (int*)malloc(sizeof(int) * dim)) == NULL) {
        printf("error");
        exit(1);
    }

    printf("success\n\n");
}

A: Allocate memory to p before passing it to function.
Also, free p in main(), but after free(p->v).

A: First solution, you can use t_list list then using the reference when you call the function makenullList:
makenullList(&list, dim);

Remember never free list.
Second solution, using the pointer, but you have to allocate for it. In this case, you have to allocate p in main function, not in makenullList function.
p = malloc(sizeof(t_list));
if(!p)
  exit(-1);

Never cast the malloc as you did in your code:
p->v = malloc(sizeof(int) * dim) // Do not cast (int *) here

When you do not still use p, do not forget free it:
free(p->v);
free(p);


text:
Q: Atomic Integer increment program not working as expected I am trying to implement a counter using atomic integer and then printing the final value after all threads finish their tasks , but i am not getting the latest value , in my case the value i should get should be 20 but it is fluctuating like 17,18,16,19,20 etc
the program is as follows:
class AtomicOperations implements Runnable
{
private AtomicInteger ai;
private int a;

AtomicOperations(int aivalue, int ivalue) {
    ai = new AtomicInteger(aivalue);
    this.a = ivalue;
}

@Override
public void run() {
    ai.getAndIncrement();
}

  public static void main(String args[]) {
    AtomicOperations obj = new AtomicOperations(10, 10);
    Thread[] t = new Thread[10];
    synchronized (obj) {
        for (int i = 0; i < t.length; i++) {
            t[i] = new Thread(obj, "Thread-" + (i + 1));
            t[i].start();
        }
    }
    System.out.println(obj.ai);
  }
}

A: You aren't waiting until the threads are done, so the number of increments that have completed when you print can vary.


text:
Q: $.ajax() variable scoping issues I have a scoping issue I am not able to figure out.
Please see this code:
setTimeout(function () {
    var jq = $.ajax({

            });

    jq.done(function(data){

    })
},1000);

// How to access jq object here?

How can I access jq outside setTimeout? Here's a live sample http://jsfiddle.net/g54Cx/

A: Move var jq; out of Timeout definition, like this:
var jq;

setTimeout(function () {
      jq = $.ajax({

      });

      jq.done(function(data){

      })
}, 1000);

console.log(jq);

A: in addition to the other suggestions...
You can pass it to another function:
http://jsfiddle.net/7aZdm/
myFunction(jq) {
  //access in here
}

setTimeout(function () {
    var jq = $.ajax({
                url: "/echo/json/",
                type: "POST",
                data: {json: '{"message": "Hello"}'},
                dataType: "json"
            });
    myFunction(jq);
    jq.done(function(data){
        $("#msg").text("Response is = " + data.message);
    })
},1000);

or just assign it to the window object, but that's generally bad practice
window.jq = jq


text:
Q: bnlearn.plot libreary is not working in python I am following a simple tutorial to learn the structure of a Bayesian Network with the following code but bn.plot is not working
import bnlearn as bn
from tabulate import tabulate

# Load example
df = bn.import_example('sprinkler')
# Structure learning
model = bn.structure_learning.fit(df, methodtype='ex', scoretype='bic')
# Compute edge strength using chi-square independence test and remove (prune) the not-signficant edges
model = bn.independence_test(model, df, alpha=0.05, prune=True)

# Examine the output of the chi-square test. All P values are significant. Nothing is removed.
print(tabulate(model['independence_test'], tablefmt="grid", headers="keys"))

bn.plot(model)


text:
Q: Live Chat support in my website I just wanted to know if there is any (preferently freeware) solution to provide live chat support in my website, but connected to a Live Messenger account, because I would like to answer by this way.

A: You can try eBuddy embed. They provide widget to be embed in your webpage to chat with you.

A: I'm not sure there's any easy way to do this with Live Messenger.
If you can use Yahoo! Messenger instead of Live Messenger, they provide a nice easy free widget which does what you want, called Yahoo! Messenger Pingbox.

A: If you are using ASP.Net and OK with using Silverlight, you can look into this flexible option. It is a Polling duplex solution easy to implement. For PHP Chantlive is an option.

A: I think I'll try Windows Live Messenger Web Toolkit to develop my white-labeled solution, but thanks to all of you guys!

A: Take a look at olark (olark.com). Super easy to embed on the page, and it works with most chat clients, so you don't have to use new software.


text:
Q: Play one song after the another javafx I'm trying to get song location from DB and play one song after the another but in here it plays the last song in the database and stops playing. I want to play the first song, then the second song.
public  class FX_Musicplayer extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(final Stage stage) throws Exception {

        final ArrayList<String> list = new ArrayList<String>();

        try {
            Statement stmt = null;
            // connect to database radio
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/radio", "root", "");
            stmt=conn.createStatement();

                    String sql = "SELECT location FROM Request";
                    ResultSet rs = stmt.executeQuery(sql);

                     while(rs.next()) {
                        list.add(rs.getString(1));
                    }
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

            for (int j = 0; j < 3; j++) {

                final Group root = new Group();
                String item = list.get(j);

                System.out.println(item);

                Media media = new Media(list.get(j));
                final MediaPlayer player = new MediaPlayer(media);
                MediaView view = new MediaView(player);

                root.getChildren().add(view);
                Scene scene = new Scene(root, 400, 400, Color.BLACK);
                stage.setScene(scene);
                stage.show();
                player.play();

            player.setOnEndOfMedia(new Runnable() {
                @Override public void run()
                {
                    player.stop();
                    return;
                }
                });

            }
    }
}

A: You have a logical issue with your code. Instead of just changing the media, you are trying to add everything again in the loop. The loop just builds everything again for you and at the end you just get the last media playing. You need to play the first one and on its completion, add the second one, play it and so on.
Replace the for loop with this piece of beauty.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Example extends Application {

    final MediaView view = new MediaView();
    Iterator<String> itr ;
    @Override
    public void start(Stage stage) throws Exception {
        final Group root = new Group();
        List<String> list = new ArrayList<String>();
        itr = list.iterator();
        //Plays the first file
        play(itr.next());
        root.getChildren().add(view);
        Scene scene = new Scene(root, 400, 400, Color.BLACK);
        stage.setScene(scene);
        stage.show();
    }
    public void play(String mediaFile){
        Media media = new Media(mediaFile);
        MediaPlayer player = new MediaPlayer(media);
        view.setMediaPlayer(player);
        player.play();
        player.setOnEndOfMedia(new Runnable() {
            @Override
            public void run() {
                player.stop();
                if (itr.hasNext()) {
                    //Plays the subsequent files
                    play(itr.next());
                }
                return;
            }
        });
    }
    public static void main(String[] args) {
        launch(args);
    }
}


text:
Q: Codeigniter create custom custom config files I am using codeigniter and git for this project.
Is it possible to create custom config files for each different developer and between develop and production branch. Because between develop and master branch we have different values for the database login credentials and other variables.
What I hope to achieved is at the config.php in the config folder, have something like
$this->load->file('Developer_file')
where 'Developer_file' is the file for each different developer.
What I have now is just lumping all config variables in the config.php file in the config folder, just want to have  a cleaner way of doing this.

A: I think environments are the way to go here. It is already built in CI so you won't need to make your own system.
I have a similar setup as yours I think: GIT+CI and multiple devs.
You can add as many as you want and easily create separate config files, such as database connections and paths. In your projects index.php you'll define the dev's or sites environments.
define('ENVIRONMENT', 'development');

So you will have a config folder structure like this:
/application
    /config
        /development
        /other-dev
        /staging
        /production

Watch out if you use git that you don't include the index.php in your repo (or at least not with that name). You'll have to upload that one manually.

A: You can try some think like this:

*

*Add different config files to config folder.

*Define in index.php some constant, something like this define('DEVELOPER_TYPE', 'developer');

*Change config/autoload.php. Something like this:
switch(DEVELOPER_TYPE){
    case 'developer':
        $autoload['config'] = array('developer_config');
        break;
    case 'tester':
        $autoload['config'] = array('tester_config');
        break;
}


text:
Q: Dotvvm multiselect business pack filtering backspace doesn't work I Used component from Business pack called MultiSelect viz code:
<bp:MultiSelect DataSource="{value: UserRoleGroupNames}" SelectedValues="{value: UserDetailDTO.UserRoleGroupNames}" Placeholder="Vyberte uživatelské role" class="form-control"/>

Everything looks good expect filtering. I cant delete letters with backspace key.

A: Thank you! I've been able to repro this issue. It will be fixed in next release.


text:
Q: Determining whether a Schur complement is invertible Consider the symmetric matrix
$$M = \begin{bmatrix}
      A   &  B \\
      B^T & -C
\end{bmatrix}$$
where $A \in \cal{R}^{n \times n}$ and $C \in \cal{R}^{m\times m}$ are symmetric, positive semidefinite, highly sparse matrices.
Is there an efficient way of checking if the Schur complement
$$S = A + BC^{-1}B^T$$
is invertible by looking at the properties of matrices $M$, $A$, $B$, $C$?
Inverting $C$ is expensive and the inverse of a sparse matrix is a full matrix, which is undesirable.
Thank you all.


text:
Q: Where are the console logs in an asp.net core application hosted by IIS I've added logging to an asp.net core application, using the excellent Serilog library. I have added sinks for both Sql Server and Literate console.
The sql server sink works perfectly of course, but, well this is a little embarrassing, I have no clue how to display the logs in a console window.
This is what ive tried:

*

*In the published directory I have run the command dotnet run but got an error saying that the project.json does not exist. This of course works if I run the command on my dev machine where that file is located. The logs are displayed the console that is opened.

*I've also tried to run the exe directly, and it was saying that it is listening on: http://localhost:5000, but no logging was displayed in console window.

Here's the code:
public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();

        ConfigureLogging();
    }

    private void ConfigureLogging()
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .WriteTo.LiterateConsole(LogEventLevel.Verbose)
            .WriteTo.RollingFile(".\\Logs\\log-{Date}.txt")
            .WriteTo.MSSqlServer(Configuration.GetConnectionString("Logging"), "Logs"/*, columnOptions: new ColumnOptions()*/)
            .CreateLogger();
    }

    public IConfigurationRoot Configuration { get; }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
    {
        app.Use(async (context, next) =>
        {
            await next();

            // If there's no available file and the request doesn't contain an extension, we're probably trying to access a page.
            // Rewrite request to use app root
            if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
            {
                context.Request.Path = "/"; // Put your Angular root page here
                await next();
            }
        });

        loggerFactory
            .AddSerilog();

        // Ensure any buffered events are sent at shutdown
        appLifetime.ApplicationStopped.Register(Log.CloseAndFlush);

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseDefaultFiles();
        app.UseStaticFiles();

        //app.UseCors(builder => builder.AllowAnyOrigin());
        app.UseMvc();

        //app.UseHangfireDashboard();             // Will be available under http://localhost:5000/hangfire
        //app.UseHangfireServer();
    }

How do I display the logs in the console window?

A: Under IIS the console logs aren't collected. You'll need to use one of the other sinks for an IIS hosted app, such as the rolling file you've configured.


text:
Q: Wrong placement in 2d vector I'm trying to print a full closed maze (where the user inputs width and height), but when I print the maze the "|" walls are not placed correct. Why is this, because the parameters are set. Also the right amount of "|" are placed but at wrong positions
    int vectorLength = (userRows * 2) + 1;
int vectorWidth = (userColloms * 4) + 1;

std::vector<std::vector<std::string>> maze(vectorWidth, std::vector<std::string>(vectorLength, ""));

for (unsigned int i = 0; i < vectorLength; i++) {
    int testj = 0;
    for (unsigned int j = 0; j < vectorWidth; j++) {
        if (i % 2 == 0){
            if (j % 4 == 0) {
                maze.at(j).at(i) = "+";
            } else {
                maze.at(j).at(i) = "-";
            }
        }
        if (i % 2 != 0){
            if (j % 4 == 0) {
                maze.at(j).at(i) = "|";
            }
        }

    }

}

The output for input 3 3 :
+---+---+---+
||||
+---+---+---+
||||
+---+---+---+
||||
+---+---+---+
Program ended with exit code: 0

A: It looks like your code works by replacing characters in your maze vector. Since your vector is initialized all to empty strings, there is nothing between each "|" to give space. You should either initialize your vector to be full of spaces " " or find another way to pad the space between each bar.


text:
Q: Best way of doing global polling in react app So i have few polling services that are triggered when user is authenticated and are running all the time under hood on Navigator level so code looks like this
const Navigator() => {
   usePolling1();
   usePolling2();
   usePolling3();

   return <AppComponent/>
}

Each of these polling are updating the state where we use recoil for state management. Issues that i'm facing are:

*

*Dom tree gets re-render

*If i render component that is reading from the state that have been updated from the global polling it doesn't get unmounted even if i'm not on this route anymore, so how to handle global polling what is the best practice but when i leave the component to get unsubscribed from state and not being rednered anymore


text:
Q: error C2440: 'initializing': cannot convert from 'initializer list' to 'std::vector>' I tried to compile the following codes:
vector<char*> art = { "a","an","the" };

but received error message:
error C2440: 'initializing': cannot convert from 'initializer list' to 'std::vector<char *,std::allocator<_Ty>>'
1>        with
1>        [
1>            _Ty=char *
1>        ]
1> note: No constructor could take the source type, or constructor overload resolution was ambiguous

If i changed the element type to 'const char *' like this:
vector<const char*> art = { "a","an","the" };

it can be compiled.Can someone tell me the reason?Thanks a lot.

A: The reason is because string literals are constants and they are being stored in the read-only memory. Why?
if it suits you, you can alternatively use:
vector<string> art = { "a","an","the" };

A: There are two things going on here. First and the most basic one, is that string literals are const by default in C++. Shadi gave a very good link in his answer.
The second thing is that brace initialization cannot accept narrowing conversions. This is very well explained in the item 7 of Meyers' Effective Modern C++ book, very advisable one.
It's a matter of the type system: when you initialize a container with values within braces, like in { "a","an","the" };, this braced expression is deduced to have the type std::initializer_lists<const char *>, which then will call the container's constructor that takes an initializer list as a parameter. But, remember that string literals have type const char * in C++, but you declared your vector to hold elements of type char *. This will imply a narrowing conversion const char * -> char *, which brace initialization doesn't allow. Therefore, this constructor is discarded, no other is found, and your compiler complains.


text:
Q: KnockoutJS setting focus after adding to array/collection I have viewmodel with an array of diagnosis codes. In my html I have a button data-bound to a click that adds a blank diagnosis code to the array. This all works.
What I cant figure out, is how to set focus to the dynamically added textbox when a code is added. What can I add :

Diagnosis Codes<input type="button" value="Add" data-bind="click:AddDiagnosisCode"/>

<input type="text"  data-bind="value:$data"/>

A: Use the built-in binding hasFocus and set it to true
<input type="text" data-bind="value:$data, hasFocus: true">

See http://jsfiddle.net/eT3Y8/

A: It can be done with a custom binding. The harder part in this approach is to not focus on the boxes of the elements that are initially in the list. That's why I needed an extra isNew property, which is false for the already existing elements. I also used jquery to focus :) Fiddle: http://jsfiddle.net/hv9Dx/1/
html:

Diagnosis Codes<input type="button" value="Add" data-bind="click:AddDiagnosisCode"/>

<input type="text"  data-bind="value:value, focusOnCreate:isNew()"/>

js:
var Record = function(value, isNew){
    var self = this;
    self.value = ko.observable(value);
    self.isNew = ko.observable(isNew || false);
}

var VM = function() {
    var self = this;
    self.DiagnosisCodes = ko.observableArray([
        new Record("2345"),
        new Record("6789")]);
    self.enableFocus = ko.observable(true);
    self.AddDiagnosisCode = function(){
        self.DiagnosisCodes.push(new Record("", true));
    }
}

ko.bindingHandlers.focusOnCreate = {
    init:function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        if(valueAccessor()){
            $(element).focus();
        }
    }
}

     ko.applyBindings(new VM());


text:
Q: AJAX error message on Chrome, MIME type checking is enabled Every time I run this code I get this error message:

index.html:1 Refused to execute script from 'http://quotesondesign.com/wp-json/posts?callback=jQuery321021689358047216856_1511579115978' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

$.ajax({
    url: "http://quotesondesign.com/wp-json/posts",
    type: "GET",
    dataType: 'jsonp',
    cache: true,
    success: function (data, status, error) {
        console.log('success', data);
    }
});

I cant find a solution, please help me resolve this bug.

A: You are telling jQuery to read it as JSONP.
JSON and JSONP are different.
You need to either change the server to respond with JSONP or change the JavaScript to expect JSON.
If you change the client to expect JSON, then you also need to change the server (quotesondesign.com) to provide the CORS headers that give the browser permission to ignore the Same Origin Policy.


text:
Q: If $\emptyset\subsetneq A\subseteq (0,1)$ and $a,b\in A, aI am looking for a simple and short solution of this problem using only basic definitions of $\sup$ etc. Here is my somewhat complicated solution that uses sequences and the Axiom of Countable Choice.
Obviously $0<\sup A\le 1$. Assume $\sup A\notin A$. Then there exists a sequence $x_n\in A$ that is strictly increasing and $x_n\to \sup A$. Indeed, take $x_1\in A$ so that
$$\sup A-1<x_1<\sup A$$
and having defined $x_1<...<x_n$, $x_i\in A$ so that
$$\sup A-\frac1n<x_n<\sup A$$
pick $x'_{n+1}\in A$ s.t.
$$\sup A-\frac1{n+1}<x'_{n+1}<\sup A$$
and $x_{n+1}\in A$ s.t.
$$\sup A-(\sup A-x'_{n+1})<x_{n+1}<\sup A\implies \sup A-\frac1{n+1}<x'_{n+1}<x_{n+1}<\sup A$$
By hypothesis,
$$x_n<x_{n+1}\implies \frac{x_n}{x_{n+1}}\in A\implies \frac{x_n}{x_{n+1}}\le \sup A\implies 1=\frac {\sup A}{\sup A}\le \sup A\le 1$$
hence $\sup A=1$


text:
Q: Mask a div with css Here is my Fiddle : http://jsfiddle.net/4wd6vmjL/
I want to mask a div to show my image skew . but i dont want image to skew.
now there is a gap in mask and image can't fill all mask .
.mask{
 background-image: url('http://www.birds.com/wp-content/uploads/home/bird4.jpg');
    height:200px;
       -webkit-transform: skew(-16deg);
    -moz-transform: skew(16deg);
    -o-transform: skew(16deg);
    transform: skew(16deg);
}

Any advice ? Thanks

A: You need to change your css of .mask class.

.wrapper{
    display: block;
    height:200px;
    background: #f8f8f8 none repeat scroll 0 0;
    text-align: left;
    -webkit-transform: skew(-16deg);
    -moz-transform: skew(-16deg);
    -o-transform: skew(-16deg);
    transform: skew(-16deg);
    border-right:medium none;
    margin-bottom: 26px;
    margin-left: 44px;
    overflow: hidden;
    z-index: 100;
    width:300px;

}
.mask {
    background-image: url("http://www.birds.com/wp-content/uploads/home/bird4.jpg");
    background-position: center top;
    height: 480px;
    transform: skew(16deg);
    width: 430px;
    padding-left: 70px;
}

asdassadd

A: Just add the image inside another div and counterskew it with the exact opposite. The hardest bit is positioning your div now, which would take some tweaking - depending on the angle your inside div needs to be bigger. I have also positioned it at the center of the wrapping div.

.mask {
    position: relative;
    left: 100px;
    width: 200px;
    height:200px;
    overflow: hidden;
    -webkit-transform: skew(-16deg);
       -moz-transform: skew(-16deg);
        -ms-transform: skew(-16deg);
            transform: skew(-16deg);
}
.mask > * {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 370px;
    height:370px;
    color: #fff;
    background-image: url('http://www.birds.com/wp-content/uploads/home/bird4.jpg');
    -webkit-transform: skew(16deg) translate(-50%,-50%);
       -moz-transform: skew(16deg) translate(-50%,-50%);
        -ms-transform: skew(16deg) translate(-50%,-50%);
            transform: skew(16deg) translate(-50%,-50%);
}

This is just text to show your skew is now undone. This is just text to show your skew is now undone. This is just text to show your skew is now undone.This is just text to show your skew is now undone. This is just text to show your skew is now undone. This is just text to show your skew is now undone. This is just text to show your skew is now undone. This is just text to show your skew is now undone.This is just text to show your skew is now undone. This is just text to show your skew is now undone. This is just text to show your skew is now undone.


text:
Q: i want to compare if useranme exist in database or not i want to take data from database and compare it with some inputed text i.e want to checck if username is already presnt in database or not.
here is my code of DBHelper.
public Boolean checkusername(String name) throws SQLException {

    Cursor mCursor =
            db.query(true,Login_Table, new String[] { KEY_ROWID, KEY_USERNAME,KEY_STATUS }, KEY_USERNAME

                    + "=" + "'" + name + "'", null, null, null, null, null);

    if (mCursor.moveToFirst()) {

        return true;

    }

    return false;

}
code where comparison is done
public class Registration extends Activity implements OnClickListener, OnItemSelectedListener

{
 // Variable Declaration should be in onCreate()
 private Button mSubmit;
 private Button mCancel;

 private EditText mFname;
 private EditText mLname;
 private EditText mUsername;
 private EditText mPassword;
 private EditText mEmail;
 private Spinner mGender;
 private String Gen;
 boolean check;

private DBHelper DB = new DBHelper(Registration.this);

 @Override
 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.register);

  //Assignment of UI fields to the variables
  mSubmit = (Button)findViewById(R.id.submit);
  mSubmit.setOnClickListener(this);

  mCancel = (Button)findViewById(R.id.cancel);
  mCancel.setOnClickListener(this);

  mFname = (EditText)findViewById(R.id.efname);
  mLname = (EditText)findViewById(R.id.elname);

  mUsername = (EditText)findViewById(R.id.reuname);
  mPassword = (EditText)findViewById(R.id.repass);
  mEmail = (EditText)findViewById(R.id.eemail);

  mGender = (Spinner)findViewById(R.id.spinner1);

  // Spinner method to read the on selected value
  ArrayAdapter<State> spinnerArrayAdapter = new ArrayAdapter<State>(this,
               android.R.layout.simple_spinner_item, new State[] {
            new State("Male"),
            new State("Female")});
  mGender.setAdapter(spinnerArrayAdapter);
  mGender.setOnItemSelectedListener(this);

 }

 public static boolean isvalidEmail(String email) {
        boolean isValid = false;

        String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
        CharSequence inputStr = email;

        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

 public void onClick(View v)
 {

  switch(v.getId()){

  case R.id.cancel:
   Intent i = new Intent(getBaseContext(), Home.class);
   startActivity(i);
   //finish();
   break;

  case R.id.submit:

   String fname = mFname.getText().toString();
   String lname = mLname.getText().toString();

   String uname = mUsername.getText().toString();
   String pass = mPassword.getText().toString();
   String email = mEmail.getText().toString();
   String status="s";

   boolean invalid = false;
  boolean checkEmail=isvalidEmail(email);

   if(fname.equals(""))
   {
    invalid = true;
    Toast.makeText(getApplicationContext(), "Enter your Firstname", Toast.LENGTH_SHORT).show();
   }
   else
       if(fname.matches("[0-9]+" ))
               {
           invalid = true;
            Toast.makeText(getApplicationContext(), "Enter valid name", Toast.LENGTH_SHORT).show();

               }
   else
       if (fname.matches(".*\\s+.*"))
       {
           invalid = true;
            Toast.makeText(getApplicationContext(), "Spaces are not allowed in Firstname", Toast.LENGTH_SHORT).show();
       }
   else

   if(lname.equals(""))
   {
    invalid = true;
    Toast.makeText(getApplicationContext(), "Please enter your Lastname", Toast.LENGTH_SHORT).show();
   }
   else
       if (fname.matches(".*\\s+.*"))
       {
           invalid = true;
            Toast.makeText(getApplicationContext(), "Spaces are not allowed in Lastname", Toast.LENGTH_SHORT).show();
       }
   else

    if(uname.equals(""))
    {
     invalid = true;
     Toast.makeText(getApplicationContext(), "Please enter your Username", Toast.LENGTH_SHORT).show();
    }
    else
           if (uname.matches(".*\\s+.*"))
           {
               invalid = true;
                Toast.makeText(getApplicationContext(), "Spaces are not allowed in Username", Toast.LENGTH_SHORT).show();
           }
    else

      if(pass.equals(""))
     {
      invalid = true;
      Toast.makeText(getApplicationContext(), "Please enter your Password", Toast.LENGTH_SHORT).show();

   }
      else
       if (pass.matches(".*\\s+.*"))
       {
           invalid = true;
            Toast.makeText(getApplicationContext(), "Spaces are not allowed in Password", Toast.LENGTH_SHORT).show();
       }
     else
      if(email.equals(""))
   {
    invalid = true;
    Toast.makeText(getApplicationContext(), "Please enter your Email ID", Toast.LENGTH_SHORT).show();
   }
      else if(checkEmail==false)
      {
            invalid = true;
            Toast.makeText(getApplicationContext(), "Please enter valid Email ID", Toast.LENGTH_SHORT).show();
      }
      else

DB.open();
  if (DB.checkusername(uname)) {

      invalid = true;
      Toast.makeText(getApplicationContext(), "username alredy in use enter another", Toast.LENGTH_SHORT).show();

  }

     else
      if(invalid == false)
      {
       addEntry(fname, lname, Gen, uname, pass, email);
       login( uname, pass, status);
       Intent i_register = new Intent(Registration.this, Login.class);
       startActivity(i_register);
       //finish();
      }

      break;
      }

    }

 public void onDestroy()
 {
  super.onDestroy();
  DB.close();
 }

private void login(String username,String password,String status)
{

      SQLiteDatabase db = DB.getWritableDatabase();
      ContentValues values = new ContentValues();
      values.put("username", username);
      values.put("password", password);
      values.put("status", status);
      try
      {
       db.insert(DBHelper.Login_Table, null, values);
      }
      catch(Exception e)
      {
       e.printStackTrace();
      }
}

 private void addEntry(String fname, String lname, String Gen, String uname, String pass, String email)
 {

  SQLiteDatabase db = DB.getWritableDatabase();

  ContentValues values = new ContentValues();
  values.put("firstname", fname);
  values.put("lastname", lname);
  values.put("gender", Gen);
  values.put("username", uname);
  values.put("password", pass);
  values.put("email", email);

  try
  {
   db.insert(DBHelper.DATABASE_TABLE_NAME, null, values);

   Toast.makeText(getApplicationContext(), "your details submitted Successfully...", Toast.LENGTH_SHORT).show();
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }

}

here is error logcat
07-07 02:02:48.623: E/AndroidRuntime(8297): FATAL EXCEPTION: main
07-07 02:02:48.623: E/AndroidRuntime(8297): java.lang.NullPointerException
07-07 02:02:48.623: E/AndroidRuntime(8297):     at com.google.data.DBHelper.checkusername(DBHelper.java:164)
07-07 02:02:48.623: E/AndroidRuntime(8297):     at com.google.data.Registration.onClick(Registration.java:209)
07-07 02:02:48.623: E/AndroidRuntime(8297):     at android.view.View.performClick(View.java:2408)
07-07 02:02:48.623: E/AndroidRuntime(8297):     at android.view.View$PerformClick.run(View.java:8816)
07-07 02:02:48.623: E/AndroidRuntime(8297):     at android.os.Handler.handleCallback(Handler.java:587)
07-07 02:02:48.623: E/AndroidRuntime(8297):     at android.os.Handler.dispatchMessage(Handler.java:92)
07-07 02:02:48.623: E/AndroidRuntime(8297):     at android.os.Looper.loop(Looper.java:123)
07-07 02:02:48.623: E/AndroidRuntime(8297):     at android.app.ActivityThread.main(ActivityThread.java:4627)
07-07 02:02:48.623: E/AndroidRuntime(8297):     at java.lang.reflect.Method.invokeNative(Native Method)
07-07 02:02:48.623: E/AndroidRuntime(8297):     at java.lang.reflect.Method.invoke(Method.java:521)
07-07 02:02:48.623: E/AndroidRuntime(8297):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-07 02:02:48.623: E/AndroidRuntime(8297):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-07 02:02:48.623: E/AndroidRuntime(8297):     at dalvik.system.NativeStart.main(Native Method)

A: It seems without open the database you are performing query. you need to first open database before performing any operations.
Example:  db.open()


text:
Q: Custom EditText does not show lines above I am building a custom EditText from this answer, this is the output I am getting,

Problem
The lines are not starting right at the top,they are starting somewhere in the middle, what could be wrong.
Here is the code,
public class LinedEditText extends EditText {

    private static Paint linePaint;

    static {
        linePaint = new Paint();
        linePaint.setColor(Color.BLACK);
        linePaint.setStyle(Paint.Style.STROKE);
    }

    public LinedEditText(Context context, AttributeSet attributes) {
        super(context, attributes);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Rect bounds = new Rect();
        int firstLineY = getLineBounds(0, bounds);
        int lineHeight = getLineHeight();
        int totalLines = Math.max(getLineCount(), getHeight() / lineHeight);

        for (int i = 0; i < totalLines; i++) {
            int lineY = firstLineY + i * lineHeight;
            canvas.drawLine(bounds.left, lineY, bounds.right, lineY, linePaint);
        }

        super.onDraw(canvas);
    }
}

Here is my XML,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/PeachPuff"
    >

    <TextView
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView"
        android:padding="8dp"
        android:layout_margin="10dp"
        android:background="@drawable/shape"
        android:layout_gravity="center_horizontal" />

    <com.random.simplenotes.LinedEditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        />

</LinearLayout>

A: All I did was added the gravity and everything was fine,
<com.random.simplenotes.LinedEditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inputType="textMultiLine"
        android:gravity="top|left"
        />


text:
Q: Using webpack and react × becomes × with minification I'm using webpack.optimize.UglifyJsPlugin() to minify my React code.
This is my render function
return (

                    <button type='button' className='close' data-dismiss='modal'>×</button>

Column Picker

                        {listItems}

                        <button type='button' className='btn btn-sm btn-primary' data-dismiss='modal' onClick={props.onSave}>Save</button>

                        <button type='button' className='btn btn-link' data-dismiss='modal'>Cancel</button>

);

The close button uses &times but when it actually renders I see
<button type="button" class="close" data-dismiss="modal">×</button>

If I remove webpack.optimize.UglifyJsPlugin() it renders as one would expect.  Does anyone know how to fix this?

A: Specifying the charset in the HTML will preserve the correct character.
Try adding <meta charset="UTF-8"/> (or whatever charset) to the meta tag on your html file.

A: I've just had the same issue using angular-cli (V2.4.6). In this case the problem only happens in production mode.
Angular-cli uses webpack internally but provides no access to which options are used in production vs development mode.
Adding
    <meta charset="UTF-8"/>
also worked for me.


text:
Q: Proof : $S$ a subspace of a vector space is generated by $n$ vectors, any $m$ vectors in $S$ , where $m > n$ are linearly dependent. Constraints :

*

*Basis and dimensions are not introduced yet

*Matrix and system of equations can't be used

I am aware that this might possibly be a duplicate of the same question here, but I wanted to take this question further and see if any of you have come across an alternative proof than the one mentioned in the first answer. Btw, I am new to this platform, so in case I am making a mistake by posting this, please let me know.

A: The following proof may resemble the second answer of the linked post, but I do not fully understand the argument there.
Clearly, the assertion in the title follows from Lemma 1 below (if $v_1,\cdots,v_n$ are linearly dependent, then the space $S$ can be spanned by fewer than $n$ vectors).
Lemma 1. Let $v_1,\cdots,v_n$ be independent and $$S=<v_1,\cdots,v_n>.$$ Then any $n+1$ vectors in $S$ are linearly dependent.
Lemma 2. Assume Lemma 1 holds for $n=k-1$. Let $$S=<v_1,\cdots,v_k>,~{\rm and~}w_1,\cdots,w_k\in S,$$ where $v_1,\cdots,v_k$ (resp. $w_1,\cdots,w_k$) are linearly independent. Then $$S=<w_1,\cdots,w_k>.$$
Proof. Given the assumption, it suffices to show that $$S=<v_1,\cdots,v_k>=<w_i,v_2,\cdots, v_k>\quad (1)$$ for some $1\leq i\leq k$ and $w_i,v_2,\cdots,v_k$ are linearly independent. Repeating the argument, one can achieve the result by replacing all $v_i$'s by $w_i$'s up to ordering.
To prove (1), one uses the assumption that Lemma 1 holds for $n=k-1$. It follows that there exists $i$ such that $$w_i\notin ~<v_2,\cdots,v_k>,$$ since $w_1,\cdots,w_k$ are linearly independent. Now $$w_i=c_1v_1+c_2v_2+\cdots+c_kv_k~{\rm with~}c_1\neq 0,$$ hence $$v_1\in ~<w_i,v_2,\cdots,v_k>~\supseteq ~<v_1,\cdots,v_k>$$
$$\Rightarrow ~<w_i,v_2,\cdots,v_k>=<v_1,\cdots,v_k>,$$ since the other inclusion is trivial. The independence of $w_i,v_2,\cdots,v_k$ can be verified by definition. $\Box$
Proof of Lemma 1. One proves it by induction on $n$, the case $n=1$ being clear. Assume the case $n=k-1\geq 1$ is true. One needs to show that case for $n=k$: Namely if $S=<v_1,\cdots,v_k>$, and $v_1,\cdots,v_k$ are linearly independent, then any $k+1$ vectors $w_1,\cdots,w_k,w_{k+1}$ in $S$ are linearly dependent.
If $w_1,\cdots,w_k$ are linearly dependent, the result is clear. Hence one may assume that $w_1,\cdots,w_k$ are linearly independent. But then by Lemma 2, one has $$S=<v_1,\cdots,v_k>=<w_1,\cdots,w_k>.$$ Since $w_{k+1}\in S=<w_1,\cdots,w_k>,$ one has $$w_{k+1}=\sum_{i=1}^k c_iw_i$$ $$\Rightarrow w_1,\cdots,w_{k+1}$$ are linearly dependent. QED

A: For comparison with my previous writing, the following is a slightly different write up.
The result of the OP's assertion follows from the following lemma. One makes sure not to use matrices, linear equations, bases, or dimension.
Lemma. Let $v_1,\cdots,v_n$ be independent and $$S=<v_1,\cdots,v_n>.$$ Then any $n+1$ vectors in $S$ are linearly dependent.
Proof. One proceeds by induction on $n$, the case $n=1$ being clear.
(IH) Assume that the result is true for $n=k-1\geq 1,$ i.e. if $v_1,\cdots,v_{k-1}$ are linearly independent and $T=<v_1,\cdots,v_{k-1}>.$ Then any $k$ vectors in $T$ are linearly dependent.
For $n=k$, let $v_1,\cdots,v_k$ be linearly independent and $S=<v_1,\cdots,v_k>.$ Let $w_1,\cdots,w_{k+1}\in S.$ One needs to show that $w_1,\cdots,w_{k+1}$ are linearly dependent.
Case 1. $w_1,\cdots,w_k$ are linearly dependent.
Clearly $w_1,\cdots,w_{k+1}$ must be linearly dependent in this case.
Case 2. $w_1,\cdots,w_k$ are linearly independent.
Claim: $S=<v_1,\cdots,v_k>=<w_1,\cdots,w_k>.$
Proof of Claim: It suffices to show that $$S=<v_1,\cdots,v_k>=<w_i,v_2,\cdots,v_k>$$ for some $1\leq i \leq k,$ and $w_i,v_2,\cdots,v_k$ are linearly independent. ......(1)
(Repeating the argument, one can achieve the Claim by replacing all $v_i$'s by $w_i$'s up to reordering.)
To prove (1), note that by induction hypothesis (IH) applied to $T=<v_2,\cdots,v_k>,$ one sees that not all $w_j$'s are in $T$, since $w_1,\cdots,w_k$ are linearly independent. It follows that there exists $i,1\leq i\leq k$ such that $w_i\notin T=<v_2,\cdots,v_k>.$ Now $$w_i=c_1v_1+c_2v_2+\cdots+c_kv_k~{\rm with~}c_1\neq 0,$$ hence $$v_1\in ~<w_i,v_2,\cdots,v_k>~\supseteq~<v_1,\cdots,v_k>$$
$$\Rightarrow <w_i,v_2,\cdots,v_k>=<v_1,\cdots,v_k>,$$ since the other inclusion is trivial. The independence of $w_i,v_2,\cdots,v_k$ can be verified by definition. This concludes the proof of (1), hence the Claim.
Now to finish Case 2 and show that $w_1,\cdots,w_k,w_{k+1}$ are linearly dependent, note by the Claim that $w_{k+1}\in S=<w_1,\cdots,w_k>,$ hence $$w_{k+1}=\sum_{i =1}^k c_iw_i$$ $$\Rightarrow w_1,\cdots,w_{k+1}~{\rm are ~linearly ~dependent.}$$
This concludes the proof for Case 2, and the Lemma. QED


text:
Q: angularjs ani-theme build not working Based on the instructions given here

*

*Downloaded zip file of ani-theme project from here and extracted zip file contents to C:\dev\angular\ani-theme-master

*Installed npm, gulp and bower, here are version info for each tool.
C:\dev\angular\ani-theme-master>gulp -v
[12:49:20] CLI version 3.9.1
[12:49:20] Local version 3.9.1
C:\dev\angular\ani-theme-master>bower -v
1.8.0
C:\dev\angular\ani-theme-master>npm -v
3.10.10

*From command prompt change directory to C:\dev\angular\ani-theme-master

*bower install

    C:\dev\angular\ani-theme-master>bower install
    bower ui-router#~0.2.13                        cached github.com/angular-ui/ui-router.git#0.2.18
    bower ui-router#~0.2.13                 validate 0.2.18 against github.com/angular-ui/ui-router.git#~0.2.13
    bower json3#^3.3.0                                  cached github.com/bestiejs/json3.git#3.3.2
    bower json3#^3.3.0                                validate 3.3.2 against github.com/bestiejs/json3.git#^3.3.0
    bower angular#^1.3.0                                cached github.com/angular/bower-angular.git#1.6.4
    bower angular#^1.3.0                         validate 1.6.4 against github.com/angular/bower-angular.git#^1.3.0
    bower es5-shim#^4.0.0                          cached github.com/es-shims/es5-shim.git#4.5.9
    bower es5-shim#^4.0.0                        validate 4.5.9 against github.com/es-shims/es5-shim.git#^4.0.0
    bower angular-mocks#~1.3.0                cached github.com/angular/bower-angular-mocks.git#1.3.20
    bower angular-mocks#~1.3.0         validate 1.3.20 against github.com/angular/bower-angular-mocks.git#~1.3.0
    bower bootstrap#^3.2.0                         cached github.com/twbs/bootstrap.git#3.3.7
    bower bootstrap#^3.2.0                  validate 3.3.7 against github.com/twbs/bootstrap.git#^3.2.0
    bower angular-animate#~1.3.15        cached github.com/angular/bower-angular-animate.git#1.3.20
    bower angular-animate#~1.3.15 validate 1.3.20 against github.com/angular/bower-angular-animate.git#~1.3.15
    bower bootstrap-btn-outline-rounded#~0.0.3                          cached github.com/sahusoftcom/bootstrap-btn-outline-rounded.git#0.0.4
    bower bootstrap-btn-outline-rounded#~0.0.3                        validate 0.0.4 against github.com/sahusoftcom/bootstrap-btn-outline-rounded.git#~0.0.3
    bower jquery#1.9.1 - 3                                                                                cached github.com/jquery/jquery-dist.git#3.2.1
    bower jquery#1.9.1 - 3                                                                          validate 3.2.1 against github.com/jquery/jquery-dist.git#1.9.1 - 3
    bower angular#1.3.20                                                                                cached github.com/angular/bower-angular.git#1.3.20
    bower angular#1.3.20                                                                                validate 1.3.20 against github.com/angular/bower-angular.git#1.3.20
    bower angular                                                                                extra-resolution Unnecessary resolution: angular#1.3.14
    bower es5-shim#^4.0.0                                                                                install es5-shim#4.5.9
    bower json3#^3.3.0                                                                                install json3#3.3.2
    bower ui-router#~0.2.13                                                                          install ui-router#0.2.18
    bower angular#1.3.20                                                                                install angular#1.3.20
    bower bootstrap#^3.2.0                                                                                install bootstrap#3.3.7
    bower bootstrap-btn-outline-rounded#~0.0.3                         install bootstrap-btn-outline-rounded#0.0.4
    bower angular-mocks#~1.3.0                                                                  install angular-mocks#1.3.20
    bower angular-animate#~1.3.15                                                          install angular-animate#1.3.20
    bower jquery#1.9.1 - 3                                                                                install jquery#3.2.1
    es5-shim#4.5.9 bower_components\es5-shim
    json3#3.3.2 bower_components\json3
    ui-router#0.2.18 bower_components\ui-router
    └── angular#1.3.20
    angular#1.3.20 bower_components\angular
    bootstrap#3.3.7 bower_components\bootstrap
    └── jquery#3.2.1
    bootstrap-btn-outline-rounded#0.0.4 bower_components\bootstrap-btn-outline-rounded
    angular-mocks#1.3.20 bower_components\angular-mocks
    └── angular#1.3.20
    angular-animate#1.3.20 bower_components\angular-animate
    └── angular#1.3.20
    jquery#3.2.1 bower_components\jquery

*npm install

    C:\dev\angular\ani-theme-master>npm install
    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
    npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

*gulp build
C:\dev\angular\ani-theme-master>gulp build
[23:42:56] Using gulpfile ~\ani-theme-master\gulpfile.js
(node:9516) DeprecationWarning: process.EventEmitter is deprecated. Use require('events') instead.
[23:42:56] Starting 'clean'...
[23:42:56] Finished 'clean' after 99 ms
[23:42:56] Starting 'build'...
[23:42:56] Starting 'jshint'...
[23:43:01] Starting 'jscs'...
[23:43:10] Starting 'styles'...
[23:43:26] Starting 'images'...
[23:43:26] Starting 'fonts'...
[23:43:28] Starting 'extras'...
[23:43:28] Finished 'build' after 32 s
[23:43:29] Finished 'jshint' after 33 s
[23:43:29] Finished 'jscs' after 28 s
[23:43:30] Finished 'images' after 3.1 s
[23:43:37] Finished 'styles' after 27 s
[23:43:37] Starting 'html'...
[23:43:53] Finished 'extras' after 25 s
events.js:160
throw er; // Unhandled 'error' event
                ^
Error: styles\main.css: error: couldn't process source due to parse error
Unexpected character '@' (1:0)
at transform (C:\dev\angular\ani-theme-master\node_modules\gulp-ng-annotate\index.js:20:11)
at Transform._transform (C:\dev\angular\ani-theme-master\node_modules\gulp-ng-annotate\index.js:68:25)
at Transform._read (C:\dev\angular\ani-theme-master\node_modules\gulp-ng-annotate\node_modules\readable-stream\lib\_stream_transform.js:184:10)
at Transform._write (C:\dev\angular\ani-theme-master\node_modules\gulp-ng-annotate\node_modules\readable-stream\lib\_stream_transform.js:172:12)
at doWrite (C:\dev\angular\ani-theme-master\node_modules\gulp-ng-annotate\node_modules\readable-stream\lib\_stream_writable.js:237:10)
at writeOrBuffer (C:\dev\angular\ani-theme-master\node_modules\gulp-ng-annotate\node_modules\readable-stream\lib\_stream_writable.js:227:5)
at Transform.Writable.write (C:\dev\angular\ani-theme-master\node_modules\gulp-ng-annotate\node_modules\readable-stream\lib\_stream_writable.js:194:11)
at Readable.ondata (_stream_readable.js:555:20)
at emitOne (events.js:96:13)
at Readable.emit (events.js:188:7)

Anyone know why this error happens, i see npm install shows an error that Unsupported platform for fsevents 32-bit vs 64-bit. May i know which tool is looking for 64-bit?

A: hope I'm not too late for an answer:
Try changing the the if condition in the html task inside the gulpfile like this:
 .pipe($.if('**/*.js', $.ngAnnotate()))
    .pipe($.if('**/*.js', $.uglify()))
    .pipe($.if('**/*.css', cssChannel()))
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe($.if('**/*.html', $.minifyHtml({conditionals: true, loose: true})))
    .pipe(gulp.dest('docs'));


text:
Q: Изменение цвета текста в коде java Мне необходимо реализовать следующее: Цвет текста в элементах RecyclerView изменяется в зависимости от даты. Если дата меньше текущей - красный, если за 3 дня - желтый, всё остальное без изменений(т.е. черный) Но у меня какая беда, цвет меняется у первый элементах в RecyclerView, то есть подсвечивает красным и желтый, но в конце списка просто рандомно элементы тоже красятся в красный и желтый цвет. Помоги решить проблему. Debug прогонял, там всё нормально. все if срабатывают как надо. Ниже будет код (p.s. всё сделал в адаптере RecyclerView).
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

    holder.setData(mainArray.get(position).getTitle());
    holder.tvDatetime.setText(mainArray.get(position).getDatetime());

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();
    Date date1 = new Date();
    Date dateBeforce = new Date(date1.getTime() + 3 * 24 * 3600 * 1000);

    try {
        date = format.parse(mainArray.get(position).getDatetime());
    } catch (ParseException e) {
        e.printStackTrace();
    }

    int result = date.compareTo(date1);
    int result1 = date.compareTo(dateBeforce);

    if (result < 0){
        holder.tvDatetime.setTextColor(Color.RED);
    }
    else if(result == 1){
        if (result1 < 0){
            holder.tvDatetime.setTextColor(Color.YELLOW);
        }
    }
}

A: Ответ просто, и просто нужно было разобраться, всегда при использовании оператора if в адаптере RecylerView необходимо указывать else при котором возвращать исходное значение.


text:
Q: Which number is bigger: $\sqrt[10]{2}$ or $1.2$? What is the general method for finding such inequalities? I have some more problems of this kind in the text I am using.

A: By the AM-GM Inequality,
$$\frac{2+1+1+1+1+1+1+1+1+1}{10} \geq \sqrt[10] 2$$
$$\frac{11}{10} \geq \sqrt[10] 2 \Rightarrow 1.2 \geq \sqrt[10] 2$$
The AM-GM inequality sometimes works when you have an n-th root but it depends on the problem.

A: There is no general method. There have been numerous books written on just inequalities. For example, see Inequalities: Theorems, Techniques and Selected Problems. However, oftentimes, simple inequalities like yours may be approached by applying some subtle manipulations, much as mathlove's excellent answer has done. Consider the following example.
Example: Compare $6^{1/4}$ and $4^{1/3}$ without using a calculator. Is one greater than the other?
Answer. Observe that
$$
6^{\frac{1}{4}}=6^{\frac{3}{12}}=(6^3)^{\frac{1}{12}}=216^{\frac{1}{12}}
$$
and
$$
4^{\frac{1}{3}}=4^{\frac{4}{12}}=(4^4)^{\frac{1}{12}}=256^{\frac{1}{12}}.
$$
Since $256$ and $216$ are both being raised to the same power, and $256>216$, we can clearly see that $4^{1/3} > 6^{1/4}$ since
$$
4^{\frac{1}{3}} = 256^{\frac{1}{12}} > 216^{\frac{1}{12}} = 6^{\frac{1}{4}}.
$$

Knowing that it helps to make such manipulations comes with time and practice. Notice that it would otherwise be quite difficult to compare the values in the example as $4^{1/3}\approx 1.5874$ and $6^{1/4}\approx 1.5651$.

A: Using the binomial theorem,
$$1.2^{10}=\left(1+\frac 15\right)^{10}\gt 1+\binom{10}{1}\frac 15=3\gt 2\Rightarrow 1.2\gt \sqrt[10]2.$$

A: Try raising $1.2$ to higher and higher powers:
$$
(1.2)^2=1.44 > 1.4,
$$
$$
(1.2)^4 > (1.4)^2 = 1.96 > 1.9,
$$
$$
(1.2)^5 > (1.2)(1.9)=2.28 > 2.
$$
So already $(1.2)^5 > 2$, hence $1.2 > \sqrt[5]{2} > \sqrt[10]{2}$.

A: $\sqrt[10]2\lt\sqrt[8]2$. $\sqrt[8]2$ is easy to compute by $\sqrt{\sqrt{\sqrt2}}$, which is certainly $\lt 1.2$.

A: Think of an investment that returns $20\%$ per year (and let me know if you can find one...).  Simple interest would return $100\%$ -- i.e. double -- in five years, hence quadruple in ten.  Compound interest, which is what $1.2^{10}$ represents, necessarily does better, so $1.2$ is quite a bit larger than $\sqrt[10]2$.


text:
Q: Node Jquery Scraping Issue I am trying to run a simple scrape on my webpage, but the issue I am running into is that I can't seem to bee selecting the HTML elements with my scraper correctly. I thought that I was grabbing the attributes correctly from my
, but I'm getting an undefined value for each of my object properties.
I'm looking to grab the data-name, data-address and data-url values.
scrape.js
var request = require('request');
var cheerio = require('cheerio');

request('http://personalSite.com', function (error, response, html) {
  if (!error && response.statusCode == 200) {
    var $ = cheerio.load(html);

    $('li').each(function(i, element){

        var li = $(this).contents();

        var name = li.attr('name');
        var address = li.attr('address');
        var url = li.attr('url');

        var metadata = {
            name : name,
            address : address,
            url : url
        };
        console.log(metadata);
    });
  }
});

html:

                                    Jerry's Food

                                    5120 West 43rd Street

                                    Mike's Pizza

                                    13482 Seventh Avenue

A: With .attr() method you should use full attribute names
var name = li.attr('data-name');
var address = li.attr('data-address');
var url = li.attr('data-url');

Or you may use
var name = li.data('name');
var address = li.data('address');
var url = li.data('url');


text:
Q: Python requests fetching data different than what I see on browser So I am trying to access zillow URL. When access via Browser it gives different than what I see via code. Details below.
CURL
curl 'http://www.zillow.com/homes/KY_rb/' -H 'Host: www.zillow.com' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:49.0) Gecko/20100101 Firefox/49.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Referer: http://www.zillow.com/homes/fsbo/featured_sort/47.368594,-68.686523,28.110749,-124.936523_rect/3_zm/' -H 'Cookie: JSESSIONID=D9BF4E280B16431893C3A11A8FC3F825; abtest=3|DO8RElLJuj2felZqqw; zguid=23|%24b42a26dc-8387-4086-b000-cc49ddfbc450; search=6|1480915840720%7Crect%3D47.368594%252C-68.686523%252C28.110749%252C-124.936523%26zm%3D3%26disp%3Dmap%26mdm%3Dauto%26p%3D1%26sort%3Dfeatured%26z%3D1%26lt%3Dfsbo%26fs%3D1%26fr%3D0%26mmm%3D1%26rs%3D0%26ah%3D0%26singlestory%3D0%09%01%09%09%09%092%090%09US_%09; F5P=3005270026.0.0000; _ga=GA1.2.1136269898.1478324471; _gat=1; __gads=ID=3f2f3e2d6e19b149:T=1478323799:S=ALNI_Mava6ZGjT_MrRhAVG7ndewcDCN60A; ipe_s=fbc57b01-3937-f803-5da1-5c4887cc949d; _bizo_bzid=aa621351-3627-408d-8838-440c1bd3f163; _bizo_cksm=EE838E07FF3AF15E; ipe.29115.pageViewedCount=1; _bizo_np_stats=14%3D1028%2C' -H 'Connection: keep-alive' -H 'Upgrade-Insecure-Requests: 1'

Curl gives proper result.
Fetch.py
import requests
from bs4 import BeautifulSoup
from time import sleep
import xmltodict

state = 'KY'
url = 'http://www.zillow.com/homes/' + state + '_rb/'
property_urls = []
headers = {
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36',
    'upgrade-insecure-requests': 1,
    'accept-language': 'en-US,en;q=0.8',
    'Connection': 'keep-alive',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
}

try:
    session = requests.session()
    r = session.get(url, headers=headers, timeout=5)
    sleep(2)
    html = html = r.text
    soup = BeautifulSoup(html, 'lxml')
    print(html)
except requests.ConnectionError as e:

    print("OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.\n")

    print(str(e))

except requests.Timeout as e:

    print("OOPS!! Timeout Error")

    print(str(e))

except requests.RequestException as e:

    print("OOPS!! General Error")

    print(str(e))

except KeyboardInterrupt:

    print("Someone closed the program")

finally:
    print("Total Properties = " + str(len(property_urls)))
    try:
        # file to store state based URLs
        state_file = open(state + '_file.txt', 'a+')
        state_file.write("\n".join(property_urls))
        state_file.close()
    except Exception as ex:
        print("Unable to store records in CSV file. Techncical details below.\n")
        print(str(e))

A: Not sure what you mean by different data (can mean anything, slightly different, totally different, etc). Your curl is using --compressed that actually means request header Accept-Encoding: deflate, gzip. Try adding that header from your python code.


text:
Q: Как я могу передать пароль в bash команду В скрипте нужно выполнить команду:
adcli join --domain=domain.local --login-user=user

эта команда запрашивает пароль, как его передать средствами баша?
пробовал echo "password" | adcli join --domain=domain.local --login-user=user не работает.

A:
Из
документации:

--stdin-password   Read a password from stdin input instead of prompting for a password.


text:
Q: Как работает оператор else if и в чем отличие от if? Чем отличается оператор else if от обычного if ?
Цепочка операторов из if-else if
if (condition)
    statement;
else if (condition)
    statement;
else if (condition)
    statement;

Цепочка операторов из if
if (condition)
    statement;
if (condition)
    statement;
if (condition)
    statement;

Есть ли между ними разница в работе?

A: Есть. Формат if/else if гарантирует, что при выполнении какого-либо из условий блоки с другими условиями не будут выполнены. При использовании цепочки if это не гарантируется. Например:
int a = 10;
if( a > 1 )
  System.out.println( "Переменная 'a' больше 1" );
if( a > 5 )
  System.out.println( "Переменная 'a' больше 5" );

Будут выполнены оба блока, и выведется:
Переменная 'a' больше 1
Переменная 'a' больше 5

A: Как такового оператора else if нет, это лишь использование ещё одного if в ветке else другого if.
Но разница между ними есть. В первом случае второе условие отработает, если не отработает первое, а третье - если не отработает второе. Во втором случае отработают все условия (если где-то не возникнет, скажем, исключение).
НО. Судя по вашему коду, условия у вас одинаковые. Поэтому в первом случае сработает тоьлко первый if или не сработает ничего. А во втором либо сработают все три if, либо не сработает ничего

A: Достаточно рассмотреть простой пример, чтобы понять, в чем заключается разница.
int x = 0;

if ( x == 0 )
{
    System.out.printline( "x = " + x );
    ++x;
}
else if ( x == 1 )
{
    System.out.printline( "x = " + x );
    ++x;
}
else if ( x == 2 )
{
    System.out.printline( "x = " + x );
    ++x;
}

Вывод на консоль будет
x = 0

А если этот код переписать в виде
if ( x == 0 )
{
    System.out.printline( "x = " + x );
    ++x;
}
if ( x == 1 )
{
    System.out.printline( "x = " + x );
    ++x;
}
if ( x == 2 )
{
    System.out.printline( "x = " + x );
    ++x;
}

то вывод на консоль будет
x = 0
x = 1
x = 2

То есть в первом случае предложения  if выполняются в зависимости от условий, а во втором случае они выполняются безусловно, то есть не зависит от выполнения предыдущих if предложений.

A: В if вы даёте условие и если оно не выполняется можете вызвать else . Но в случаях когда нужно проверять условие одно за одним можно использовать  конструкцию else if . И тогда в else if вы вписание ещё одно условие .
       int x = 1;
    if(x==3){
        System.out.println("Это число 5");//к сожелению не выведет
    }else if(x==2){
        System.out.println("Это число 2");//к сожелению не выведет
    }else if(x==1){
        System.out.println("Это число 1");//выведет вот это
    }else {
        System.out.println("Число вообще не ходит");
    }

A: Во втором случае у вас проверяются всегда все условия. В первом случае если выполнится первое условие остальные уже не проверяются

A: Вообще, конструкция
if (condition)
    statement;
else if (condition)
    statement;
else if (condition)
    statement;

чаще всего применяется, когда нужно в зависимости от того, чему равно проверяемое значение, выполнить несколько вариантов действий. И вообще по-идее в таких ситуациях нужно пользоваться оператором ветвления (switch\case\select и т.д). Но во многих языках он обладает неприятными ограничениями, которые заставляют пользоваться вышеупомянутой конструкцией.
Зачем вставлять else, если логика последующих if такова, что проверку пройдёт только один? Чтобы избежать лишних проверок и явно указать читателю исходного кода, что здесь реализован по сути оператор ветвления.

В некоторых языках реализован специальный оператор elseif\elsif\elif позволяющий избегать лишнего вложения блоков.

A: Так же можно воспользоватся оператором множественного выбора switch().
int value;
cin >> value;

switch(value){
    case 1: return value+1;
    case 2: return value+2;
    default: return value;
}

A: Тут при выполнения первого условия, к второму условию не дойдёт. Если первого не отвечает условия, а второе да - прекратятся все проверки, до 3-го не дойдёт
if (condition)
    statement;
else if (condition)
    statement;

Тут выполнятся все условия, независимо сработает ли первое, ты по сути дублируешь проверку "если"
if (condition)
    statement;
if (condition)
    statement;

A: Достаточно понимать перевод данных значений:
if - если
else if - иначе если
Пример есть в песне советской "Если у вас нету тёти":
if у вас нету тёти - хорошо
else if вам её потерять - плохо

A: Да, в else-if варианте переход к следующей ветке происходит только тогда, когда предыдущая дала результат false.
int a = 1
int b = 2
int c = 3

if (a == 1)
    statement;
else if (b == 2)
    statement; // эта ветка не будет выполнена
else if (c == 3)
    statement; // эта ветка не будет выполнена

Если Вы уберете все else-if, все три ветки будут выполнены. Поэтому else-if используется как последовательность, которая должны быть проверена, если предыдущая дала неверный результат.


text:
Q: 2012 rds 2016 domain controller So we have a few 2012 R2 Terminal Servers at my company that were working fine until we started the process of replacing our Domain Controllers with new Windows 2016 Servers.
Since then our users are getting intermittent "Access Denied" errors when they try to RDP to these terminal servers.
Generally the "Access Denied" error occurs when a terminal servers starts to use one of the newly added 2016 domain controllers. We can workaround the problem by sending an command telling the terminal server to use one of the older 2012 R2 domain controllers instead.
Then things work again.
So the question:
Is there a misconfiguration with the new 2016 domain controllers or can an adjustment be made with the 2012 Terminal Servers?
Is the problem that Windows 2016 Domain Controllers are not compatible with 2012 R2 Remote Desktop Services servers?
We are having problems finding documentation on this.
What we do know is that if we decide to start upgrading to new 2016 Terminal Servers we will have to purchase new 2016 RDS Cals (not sure if we are budgeted for that...)
For those interested, you can find out the domain controller you are using by running the following elevated PowerShell command (this assumes the command is run remotely as you might be locked out due to the RDP access denied error):
nltest /Server:your-terminal-server /DSGETDC:ad-domain

to specify the domain controller you want to be on (in our case we want to switch to back to a 2012 R2 domain controller), the command is:
nltest /Server:your-terminal-server /SC_RESET:ad-domain\specific-domain-controller

A: We opened a ticket with MS support on this. They had us add this registry on the Windows 2016 DC's and it resolved the issue.
HKLM\SYSTEM\CurrentControlSet\Control\Lsa
add the value
RestrictRemoteSamAuditOnlyMode
DWORD=1
Reboot the server


text:
Q: Align text to top in multiline form fields for dynamically generated PDF I have a PDF form with text aligned in the middle for multiline fields, I am looking for a script that will execute when the file is opened to align those text to the top instead.
It has been created using this converter (https://www.idrsolutions.com/online-pdf-to-html5-converter) to generate an HTML version of a PDF form. Then there is a function to convert it back to PDF.
For example with this: https://files.idrsolutions.com/Examples/FDFForms/CVData/form.html
You can enter some text and then click the save icon to generate the PDF.
Here is the generated file too: https://devcn.000webhostapp.com/temp/sampleAlign.pdf
In the PDF generated the text that appears in the multiline form fields is aligned to the middle. If you edit the text with changes it then aligns it to the top. Also if you select the field properties and change the multiline checkbox deselecting and selecting it again the text then too aligns to the top. Would like to automate this somehow so that when the user opens the PDF the texts are aligned to the top.

A: First, multiline text fields in Acrobat always align to the top unless the field is set to allow rich text and the user defines the field to vertically align the text to the middle; there is no way to define vertically align center in a typical PDF field programmatically and have it stick through a user edit.
What you are seeing when you first open the file is the field appearance which was generated by the converter. You can add a script at the document level that toggles the "delay" property which will cause the appearance to be regenerated by the viewer. You'd add this to a document level script so it runs when the file is first opened. See code and warning below.
nFields = this.numFields;
for (var i = 0; i < nFields; i++) {
    var f = this.getField(this.getNthFieldName(i));
    f.delay = true;
    f.delay = false
}

However, this will only run in a JavaScript capable viewer the can edit PDF like Acrobat and Reader and a few others. When I selected your link, it opened in Chrome first, which doesn't execute JavaScript. Unfortunately, non-javascript capable viewers are built into most browsers now so the likelihood of the file first being opened by the user and having your script run is low. You need to fix the appearance in the conversion process, not in the viewer.
To do that, either preprocess the HTML so that the appearance generated by the converter matches the properties of the PDF field that will be generated or convince IDR to update their software to create appearances that reflect the properties of the field generated rather than the properties of the HTML field source.


text:
Q: Bundling AWS v3 SDK with Webpack in an AWS Lambda w/ Serverless Framework? I have an AWS application, implemented as a single Lambda function, that I'm developing in Typescript with the Serverless framework. It consists of an API and a simple web UI in Express. The application will start an ECS task (which is what the API does) and the UI will poll ECS for the task status and display such to the user.
I'd like to use the v3 AWS SDK for this. Reading over the docs for using the v3 SDK in the browser, I see that I should download the individual clients I want to use with npm or yarn, then bundle them into the Javascript file for the UI with Webpack. Trouble is, I'm already using Webpack to translate Typescript into Javascript. How do I configure Webpack to translate and bundle the Typescript for the API into one file and the Javascript for the UI into another?

A: in my team we decided to use not serverless framework. instead we are using cdk and lambda layers and aws-sdk v3 (typescript) for nodejs. with lambda layer I provide the node_modules folder and reference this layer in my own lambdas. But I also played around with webpack before, see the config files below. the structure in dist folder is needed to have easy reference in cdk. I think in your case you have only to change library target in webpack.config.js file and than it should work in browser also.
webpack.config.js
// webpack.config.js -> we´ve only one config for production/dev -> context: lambda (no minifiying etc. needed)
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const path = require('path');

module.exports = {
  target: "node14", // needed to build proper nodejs14 code (without browser stuff)
  mode: 'development',
  context: __dirname, // to automatically find tsconfig.json
  entry: {
    callCreateLogs: './src/functions/callCreateLogs/index.ts',
    // TODO: add new functions here, maybe later here an additional script will do this for us (the key must match to the folder for right cdk reference)
  },
  devtool: 'inline-source-map', // to find errors (we use that also in productions for backend lambdas)
  output: {
    filename: '[name]/index.js', // generated file based on the entry key
    path: path.resolve(__dirname, 'dist'),
    libraryTarget: 'commonjs', // important for aws lambda context
  },
  plugins: [
    new CleanWebpackPlugin(), // clean up dist folder before build
  ],
  resolve: {
    extensions: [".ts", ".tsx", ".js"],
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
        options: {
          // disable type checker - we will use it in fork plugin
          transpileOnly: true
        }
      }
    ]
  },
  plugins: [new ForkTsCheckerWebpackPlugin()]
};

tsconfig.json:
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": ["es2020"],
    "esModuleInterop": true,
    "declaration": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": false,
    "sourceMap": true,
    "strictPropertyInitialization": false,
    "typeRoots": ["./node_modules/@types"],
    "outDir": "dist"
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "**/*.spec.ts", "test"]
}

here a cdk snippet:
this.CreateLogLambda = new lambda.Function(this, 'createLogLambda', {
      runtime: lambda.Runtime.NODEJS_14_X,
      code: lambda.Code.fromAsset(path.resolve(__dirname, '../../../../backend/dist/createLogs')), // hint: only directory which include the file (no filename here)
      handler: 'index.handler', // filename.methodname (without file extension),
      //role: createLogsLambdaExecutionRole
    });


text:
Q: how do i using mysql join to arrange conversations with latest reply we have two tables, screenshot attached

this table named as messages

this table is named as conversations
Now every time a student sends a message, the conversations tables checks if conversation exists via convo unique id, and then puts the message on database with sender_id as the unique id of student receiver_id as the unique id of teacher, convo as the conversation_id which is unique for every single student and teacher conversation.
What we want to do is, we want to display conversations like facebook, latest conversation with latest message is going to be at the top, we are going to find latest message with created_at, and of course student can only see conversations he started, help us, we are stuck here, unable to write a proper mysql query for it, we are using codeigniter framework for our back end
So far we came up with this, but seems like not working
$this->db->select('*');
$this->db->from($this->conversation_table_name);
$this->db->join($this->message_table_name,'conversation.convo = messages.convo');
$this->db->where('conversation.student',$student_number);
$query = $this->db->get();

A: $this->db->select('*');
$this->db->from($this->conversation_table_name);
$this->db->join($this->message_table_name,'conversation.convo = messages.convo');
$this->db->where('conversation.student',$student_number);
$this->db->group_by("conversation.sender_id");
$this->db->order_by("messages.created_at", "desc");
$query = $this->db->get();


text:
Q: jQuery: Why is this function firing 4 times? I've written a bunch of jQuery stuff to help my friend out with his online portfolio which can be found here: http://bradleyrogerson.com/ (for reference of what I am about to describe).
Here is also a direct link to the javascript: http://bradleyrogerson.com/static/js/actions-take2.js
It is a rather long file, so it's probably best if I do not put it all in a code block on Stack Overflow directly.
The problem itself is pretty simple, and you can easily see broken animation on the site (link above).
Essentially my hideProject() function which basically hides the project and then slides the original overview of all his projects back into view is firing 4 times for a reason I simply cannot find.
The key issue with this is that in the last callback of the animations taking place, I animate the scrollLeft property of the body & html element so that is visually slides back to where you had left off before going to the 'more info` view.
Because the animation is firing 4 times, there is about a 1.2 second window in which time the viewport is animated which effectively breaks the ability to scroll right during that time.
This can easily be reproduced by going to his site right now and clicking on the image furthest to the right (horizontal scroll page layout), then once you've viewed the project simply click one of the images to trigger the hideProject() function and once the viewport has animated as far as it can go try immediately scrolling to the left.
You'll notice that you won't be able to with the animation still firing pushing your attempts to go left out the window forcing the scrollLeft value upon you again and again (4 times).
I have commented the javascript file very well (at least I think so) so it should be pretty easy to read and understand once opened.
I would really appreciate an answer to the issue, how to fix it but most importantly some advice on why it broke in the first place so I can learn from this and not make this mistake again.
Many thanks for reading.
Jannis
Note: the function in question (at least I think this is the cause) is on line 212 in this file.

A: After adding breakpoints, I can only see this function firing twice, once because you bound it to a click event for the element #project-media, the other because you bound it to the hashchange() event. Just make the click event trigger a hashchange() instead of calling hideProject() or simply remove the binding altogether. The binding is made on line 331.


text:
Q: What do I use to manipulate text files and extract data out of it and store the output in a tabular format? I have a text file which has daily data for various stocks identified by PERMNO.
So the text file looks like this:
PERMNO = 1234

PERMNO = 2134

Market data:

    Date | Price | Return | Volume
    --------------------------------
    2019-01-01| 120 | 100 | 100

PERMNO = 3456

Market data:

    Date | Price | Return | Volume
    --------------------------------
    2019-01-01| 200 | 150 | 130

What I want to do is extract all the PERMNO until the market data and club it and show it with the rest of market data by adding a new column PERMNO next to rest of data. So it should look something like this:
Market data:

    Date | Price | Return | Volume | PERMNO
    -----------------------------------------
    2019-01-01| 120 | 100 | 100 | 1234,2134
    2019-01-01| 200 | 150 | 130 | 3456

I am trying to use awk for this. I am able to extract PERMNO with this, but I am unable to club it with rest of the market data by adding new column. Any alternative to awk like sed will do as well. But I am still new to shell scripts so I am not aware of their full functionalities. Can anyone suggest how should I proceed with this problem?

A: You can get what you asked for with:
$ cat tst.awk
BEGIN { OFS=" | " }

/^PERMNO/ {
    permnos = ( permnos == "" ? "" : permnos ",") $NF
}

/^ +[[:alpha:]]/ && !doneHdr++ {
    indent = text = $0
    sub(/[^ ].*/,"",indent)
    sub(/^ +/,"",text)
    hdr = text OFS "PERMNO"
    sep = sprintf("%*s",length(hdr)+2,"")
    gsub(/ /,"-",sep)
    print "Market data:" ORS ORS indent hdr ORS indent sep
}

/^ +[0-9]/ {
    print $0, permnos
    permnos = ""
}

$ awk -f tst.awk file
Market data:

    Date | Price | Return | Volume | PERMNO
    -----------------------------------------
    2019-01-01| 120 | 100 | 100 | 1234,2134
    2019-01-01| 200 | 150 | 130 | 3456

but I highly recommend you just generate a CSV instead for ease of further analysis/manipulation:
$ cat tst.awk
BEGIN { FS="[ |]+"; OFS="," }

/^PERMNO/ {
    permnos = ( permnos == "" ? "" : permnos " ") $NF
}

sub(/^ +/,"") {
    $1 = $1
    if ( /^[[:alpha:]]/ && !doneHdr++ ) {
        print $0, "PERMNO"
    }
    else if ( /^[0-9]/ ) {
        print $0, permnos
        permnos = ""
    }
}

$ awk -f tst.awk file
Date,Price,Return,Volume,PERMNO
2019-01-01,120,100,100,1234 2134
2019-01-01,200,150,130,3456

You can always produce a table format from that if you like using various tools, e.g. with column:
$ awk -f tst.awk file | column -s, -o' | ' -t
Date       | Price | Return | Volume | PERMNO
2019-01-01 | 120   | 100    | 100    | 1234 2134
2019-01-01 | 200   | 150    | 130    | 3456

and if you like that line of underscores under the header:
$ awk -f tst.awk file | column -s, -o' | ' -t | awk '1;NR==1{gsub(/./,"-");print}'
Date       | Price | Return | Volume | PERMNO
---------------------------------------------
2019-01-01 | 120   | 100    | 100    | 1234 2134
2019-01-01 | 200   | 150    | 130    | 3456

A: This seems to give wanted output (using gawk 4.14):
#!/usr/bin/gawk -f
@include "join"
BEGIN { OFS="\t" }
/PERMNO/{ if(marketseen==1) {p=$3; marketseen=0} else p=p!="" ? p "," $3 : $3;  }
/Market/{ marketseen=1 }
{ split($0,a,"|");
        lc = "";
        if (a[1]~Date) lc = "PERMNO";
        if (a[1]~"0") lc = p;
        if (NF<4) lc="";
        print a[1],a[2],a[3],a[4], lc }

input:
$ cat MarketData.txt
PERMNO = 1234
PERMNO = 2134
Market data:
Date | Price | Return | Volume
--------------------------------
2019-01-01| 120 | 100 | 100
PERMNO = 3456
Market data:
Date | Price | Return | Volume
--------------------------------
2019-01-01| 200 | 150 | 130

output:
$ ./marketdata.sh MarketData.txt
PERMNO = 1234
PERMNO = 2134
Market data:
Date     Price   Return          Volume PERMNO
--------------------------------
2019-01-01       120     100     100    1234,2134
PERMNO = 3456
Market data:
Date     Price   Return          Volume PERMNO
--------------------------------
2019-01-01       200     150     130    3456

A: You can do it like:
BEGIN {FS=" = " ; H="Market data:\n\n    Date | Price | Return | Volume | PERMNO" ; print H}
/PERMNO/ {PNO = PNO "," $2 "," }
/2[0-9]{3}-/ { gsub(",,+",",",PNO) ; gsub("^,|,$","",PNO) ; print $0 " | " PNO ; PNO = ""; next}

*

*The first line sets up the field delimiter for PERMNO lines, and print the header.

*The secoind line saves (and appends) the PERMNO IDs (only on lines that matches PERMNO).

*The third line executes when the line matches that year like pattern (this might be extended/modified), cleans up the PNO variable (no leading, ending or duplicate commas), then prints the whole line with the value of PNO appended.

It can be seen in action at ideone.


text:
Q: Why is my ClaimsRequest coming back null? I have just begun experimenting with the DotNetOpenAuth project. Modifying the sample OpenIdRelyingPartyMvc project, I was able to get a ClaimRequest for Email to work with Google.
However, when I tried to add OpenID to my own project, the ClaimResponse always comes back null. I'm wondering if there is a project or environment setting that I'm missing?
Here's my Authenticate method:
public ActionResult Authenticate(string returnUrl)
{
    var response = openid.GetResponse();
    if (response == null)
    {
        // Stage 2: user submitting Identifier
        Identifier id;
        if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
        {
            try
            {
                IAuthenticationRequest req = openid.CreateRequest(Request.Form["openid_identifier"]);
                req.AddExtension(new ClaimsRequest { Email = DemandLevel.Require });
                return req.RedirectingResponse.AsActionResult();
            }
            catch (ProtocolException ex)
            {
                ViewData["Message"] = ex.Message;
                return View("Login");
            }
        }
        else
        {
            ViewData["Message"] = "Invalid identifier";
            return View("Login");
        }
    }
    else
    {
        // Stage 3: OpenID Provider sending assertion response
        switch (response.Status)
        {
            case AuthenticationStatus.Authenticated:
                ClaimsResponse sreg = response.GetExtension<ClaimsResponse>();
                if (sreg != null)
                {
                    var email = sreg.Email;
                    Session["Email"] = email;
                }
                Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
                FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            case AuthenticationStatus.Canceled:
                ViewData["Message"] = "Canceled at provider";
                return View("Login");
            case AuthenticationStatus.Failed:
                ViewData["Message"] = response.Exception.Message;
                return View("Login");
        }
    }
    return new EmptyResult();
}

}

A: <configuration>
       <configSections>
          <section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true"/>
       </configSections>
       <dotNetOpenAuth>
          <openid>
             <relyingParty>
                <behaviors>
                   <!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
                        with OPs that use Attribute Exchange (in various formats). -->
                   <add type="DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth" />
                </behaviors>
             </relyingParty>
          </openid>
       </dotNetOpenAuth>
    </configuration>

http://dotnetopenauth.net:8000/wiki/CodeSnippets/OpenIDRP/AXFetchAsSregTransform
Add the config info to your web.config.

Google has one unique trait, in that it ignores all attribute requests marked as 'optional'. You must request the user's email address as 'required' in order to ever get an email address from Google. Be wary though, that by marking the attribute as required, Google will refuse to authenticate the user unless the user is willing to give up their email address. So if you don't actually require the email address, it may be best to mark it as optional, and just forego getting it from your Google users in order to avoid chasing your users away by forcing them to give up their email address if they don't want to.


text:
Q: Visualize Jasmine tests in TeamCity I'm using Chutzpah console to run all tests in teamcity.
Command line options:
/junit jasmine_report.html /teamcity /failOnError

This produces JUnit report in xml format. How can i visualize this as TeamCity tab (as Specflow, etc.).
It will be great to see all passed/not passed tests. I know there is Tests tab, but it is not human-readable one.

A: I don't know anything about Chutzpah, but have you looked at jasmine-reporters? It is a collection of reporters supporting Jasmine 1.x or 2.x, and it includes a TeamCity reporter. Maybe you could add this extra reporter to your spec runner to get better TeamCity reporting?
https://github.com/larrymyers/jasmine-reporters

A: To show some html as tab on build details page, follow next instructions.
Also jasmine-reporters @bloveridge mentioned allows on-the-fly reporting about tests and test would be shown on tests tab.


text:
Q: React useCallback memory leak unmounted component I'm new to React and I'm getting this error:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

From what I understand, it appears as though I have a memory leak and need a useEffect cleanup for my useCallback hook?
I have tried adding a useRef to check mount but the return doesn't change the state to false.

const MyComponent = ({data}) => {
  const mounted = useRef(true);
  const [loading, setLoading] = useState(false);

  const isLoading = useCallback(async () => {
    setLoading(true);

    if (data) {
      console.log('YAY DATA: ', data);
    }

    return () => {
      setLoading(false); // unreachable code
      mounted.current = false; // does this do the cleanup?
    };
  }, [loading]);

  return (
    //...some component
  );
};

export default MyComponent;

A: If you perform an async operation that, on completion, needs to set something to the state, you must make sure that the component is still mounted before updating the state.
In order to do so, you try something like this:
const MyComponent = (props) => {
  const mounted = useRef(false);

  useEffect(() => {
        mounted.current = true; // Will set it to true on mount ...
        return () => { mounted.current = false; }; // ... and to false on unmount
  }, []);

  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);

  const myAsyncCallback = useCallback(async () => {
    setLoading(true);

    // Await for an async function...
    const data = await yourAsyncFunction(...); // Complete with proper code here

    // While waiting for yourAsyncFunction to be done,
    // It's possible that your component had been unmounted.

    // Therefore, you have to check if the component is still mounted before updating states
    if (mounted.current) {
      setLoading(false);
      setData(data);
    }
  }, []);

  return (
    //...some component that calls myAsyncCallback
  );
};

export default MyComponent;

A: As useEffect cleanUp on component unmount, you can not update the state (and since it unmounts where value could be stored)
Your code seem to be a code where api call is done in the useEffect .like that :
useEffect(() => {
    let mounted = true
    fetchAPI.then(() => {
        if (mounted) {
            setloading(false)
        }
    })

    return function cleanup() {
        mounted = false
    }
}, [])

If it's that look at here :
https://dev.to/otamnitram/react-useeffect-cleanup-how-and-when-to-use-it-2hbm