text:
Q: check files - count python def countsfunc(path, stri):
    f = open('C:\Users....\sometextfile.txt','r')
    dicts = {}
    for line in f:
        words = line.split()
        dicts[words[1]] = dictst.get(words[0], 0) + 1
        print countdict[word[0]]
    f.close()

I made a function that needs to check if the second word of every line in the text is equal to "stri". But I also want that this function will count how many times it happens.
for example the text is like:

Old MacDonald had a farm, E-I-E-I-O.
Old MacDonald had a farm, E-I-E-I-O.
Old MacDonald had a farm, E-I-E-I-O.
Here a moo, there a moo, everywhere a moo moo

If this shows in the shell:
countsfunc(sometextfile, MacDonald)
then it should print me "3"
and if:
countsfunc(sometextfile, a)
then just "1"
and if:
countsfunc(sometextfile, Mac)
then "0".
Can someone help me please? My code isn't that good, I get something else. You're more than welcome to check it out.
Thanks.
edit:
Thanks guys, I have found the solution. Thanks anyway

A: def countsfunc(path, string):
    counter = 0
    with open(path) as f:
        for line in f:
            words = line.split()
            if words[1] == string: #check if the second word is equal to string
                counter+= 1
    return counter

Pass the filepath and your word to the function. The function will return the counter number.

A: As a one liner:
def count_2nd_words(lines, match):
    return sum(line.split()[1] == match for line in lines)

with open('C:\Users....\sometextfile.txt','r') as f:
    print count_2nd_words(f, 'MacDonald')

A: My pythonic code golf version:
from collections import Counter
def countsfunc(path,string):
    file = open(path,'r')
    second_words  = [line.rstrip().split(' ')[1] for line in file if line!='\n']
    print Counter(second_words)[string]


text:
Q: How to access different attributes of different implementation of the same interface I have an interface
public interface Inter {
    int interAttr = 0;
}

And two classes that implements it, each one with an additional attribute and each one of different type.
@AllArgsConstructor
public class Impl1 implements Inter {
    public int impl1Attr;
}

@AllArgsConstructor
public class Impl2 implements Inter {
    public String impl2Attr;
}

And I have list of Inter objects that are a mix of Impl1 and Impl2
public class main {
    public static void main(String[] args) {
        Impl1 i11 = new Impl1(0);
        Impl1 i12 = new Impl1(1);
        Impl2 i21 = new Impl2("zero");
        Impl2 i22 = new Impl2("one");
        List<inter> implList = new ArrayList<Inter>();
        implList.add(i11);
        implList.add(i12);
        implList.add(i21);
        implList.add(i22);
        for (Inter el : implList){
            // this of course works
            int a = el.interAttr1;
            // But how do I get access to impl1Attr and impl2Attr?
        }
    }
}

Of course I can query i11.impl1Attr or impl21.impl2Attr in the body of the main
But is there a way for me to have access to the attributes of the different implementations in the list in the for loop?

A: I'm probably oversimplifying the problem, but is instanceof + casting not an option?
for (Inter el : implList) {

    int a = el.interAttr;

    if (el instanceof Impl1)
        System.out.println(((Impl1)el).impl1Attr);

    if (el instanceof Impl2)
        System.out.println(((Impl2)el).impl2Attr);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Entity framework 6 data context from wcf data service I used to access the data context of my (ef 5.0) entities from inside a wcf data services service operation with this.CurrentDataSource.MyEntity.
My data service inherited from DataService<T>. Now I wanted to use entity framework 6.0 and read on the internet, I should inherit the service from EntityFrameworkDataService<T>. But now from inside my service operations, I cannot access my data context anymore. this.CurrentDataSource doesn't contain any reference to the entities.

A: Here's my workaround using an extension method that gets the underlying data model via (cached) reflection info.  It works for the current Microsoft.OData.EntityFrameworkProvider  version 1.0.0 alpha 2.
Sample usage is for a custom WebGet method:
    [WebGet]
    public string GetMyEntityName(string myEntityKey)
    {
        var model = this.CurrentDataSource.GetDataModel();
        var entity = model.MyEntity.Find(myEntityKey);
        return entity.Name;
    }

And implementation:
public static class EntityFrameworkDataServiceProvider2Extensions
{
    /// <summary>
    /// Gets the underlying data model currently used by an EntityFrameworkDataServiceProvider2.
    /// </summary>
    /// <remarks>
    /// TODO: Obsolete this method if the API changes to support access to the model.
    /// Reflection is used as a workaround because EntityFrameworkDataServiceProvider2 doesn't (yet) provide access to its underlying data source.
    /// </remarks>
    public static T GetDataModel<T>(this EntityFrameworkDataServiceProvider2<T> efProvider) where T : class
    {
        if (efProvider != null)
        {
            Type modelType = typeof(T);

            // Get the innerProvider field info for an EntityFrameworkDataServiceProvider2 of the requested type
            FieldInfo ipField;
            if (!InnerProviderFieldInfoCache.TryGetValue(modelType, out ipField))
            {
                ipField = efProvider.GetType().GetField("innerProvider", BindingFlags.NonPublic | BindingFlags.Instance);
                InnerProviderFieldInfoCache.Add(modelType, ipField);
            }

            var innerProvider = ipField.GetValue(efProvider);
            if (innerProvider != null)
            {
                // Get the CurrentDataSource property of the innerProvider
                PropertyInfo cdsProperty;
                if (!CurrentDataSourcePropertyInfoCache.TryGetValue(modelType, out cdsProperty))
                {
                    cdsProperty = innerProvider.GetType().GetProperty("CurrentDataSource");
                    CurrentDataSourcePropertyInfoCache.Add(modelType, cdsProperty);
                }
                return cdsProperty.GetValue(innerProvider, null) as T;
            }
        }
        return null;
    }

    private static readonly ConditionalWeakTable<Type, FieldInfo> InnerProviderFieldInfoCache = new ConditionalWeakTable<Type, FieldInfo>();
    private static readonly ConditionalWeakTable<Type, PropertyInfo> CurrentDataSourcePropertyInfoCache = new ConditionalWeakTable<Type, PropertyInfo>();
}

System.Runtime.CompilerServices.ConditionalWeakTable was used to cache reflection results based on a suggestion taken from Caching reflection data

A: It worked! Here is the code converted in VB.NET
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Data.Services.Providers

Public Module EntityFrameworkDataServiceProvider2Extensions

    ''' <summary>
    ''' Gets the underlying data model currently used by an EntityFrameworkDataServiceProvider2.
    ''' </summary>
    ''' <remarks>
    ''' TODO: Obsolete this method if the API changes to support access to the model.
    ''' Reflection is used as a workaround because EntityFrameworkDataServiceProvider2 doesn't (yet) provide access to its underlying data source.
    ''' </remarks>
    <System.Runtime.CompilerServices.Extension> _
    Public Function GetDataModel(Of T As Class)(efProvider As EntityFrameworkDataServiceProvider2(Of T)) As T
        If efProvider IsNot Nothing Then
            Dim modelType As Type = GetType(T)

            ' Get the innerProvider field info for an EntityFrameworkDataServiceProvider2 of the requested type
            Dim ipField As FieldInfo = Nothing
            If Not InnerProviderFieldInfoCache.TryGetValue(modelType, ipField) Then
                ipField = efProvider.[GetType]().GetField("innerProvider", BindingFlags.NonPublic Or BindingFlags.Instance)
                InnerProviderFieldInfoCache.Add(modelType, ipField)
            End If

            Dim innerProvider = ipField.GetValue(efProvider)
            If innerProvider IsNot Nothing Then
                ' Get the CurrentDataSource property of the innerProvider
                Dim cdsProperty As PropertyInfo = Nothing
                If Not CurrentDataSourcePropertyInfoCache.TryGetValue(modelType, cdsProperty) Then
                    cdsProperty = innerProvider.[GetType]().GetProperty("CurrentDataSource")
                    CurrentDataSourcePropertyInfoCache.Add(modelType, cdsProperty)
                End If
                Return TryCast(cdsProperty.GetValue(innerProvider, Nothing), T)
            End If
        End If
        Return Nothing
    End Function

    Private ReadOnly InnerProviderFieldInfoCache As New ConditionalWeakTable(Of Type, FieldInfo)()
    Private ReadOnly CurrentDataSourcePropertyInfoCache As New ConditionalWeakTable(Of Type, PropertyInfo)()
End Module

A: It seems that the EntitiyFrameworkDataService doesn't provide access to the underlying DataService and its current datasource, as stated here and here.
So the only way seems to change each service operation to create a new data context each time.


text:
Q: Python list loop from a index I have a list of dic
MyList=[
    {'Buy': 'Yes', 'date': monday, 'item': '1234'},
    {'Buy': 'Yes', 'date': monday, 'item': '4'},
    {'Buy': 'Yes', 'date': sunday, 'item': '134'},
    {'Buy': 'Yes', 'date': sunday, 'item': '124'},
    {'Buy': 'Yes', 'date': friday, 'item': '14'},
    {'Buy': 'Yes', 'date': friday, 'item': '234'}
]

I use a loop
for data in Mylist:

so it will go through all the items
if I want to do the same but I want to choose the begin and the end of le loop
for example a loop start from 0 to 3
or a loop from 2 to end
how can I do that?
thanks in advance

A: Use slicing:
for data in Mylist[:3]:

or:
for data in Mylist[2:]:

Related: Python's slice notation

A: To loop through the first n elements:
for i in itertools.islice(L, 0, n):
    # do stuff

To loop through the last n elements:
for i in itertools.islice(L, len(L)-n, len(L)):
    # do stuff

To loop through the first n and the last m elements:
for i in itertools.chain(itertools.islice(L, len(L)-n, len(L)), itertools.islice(L, len(L)-m, len(L))):
    # do stuff

A: If you were interested in printing items 0 through 3, for example, you could do something like this:
for item in MyList[:3]:
    print item


text:
Q: How to split a char array into two diferent types in c? So, I need to use the stdin to read a file that has two columns, the first one is a char, the second is an integer.
The input file is something like this:
i 10
i 20
i 30
i 40
i 50
i 45
r 48

My code currently:
int main(){
    char line[MAX];
    int n = 0;
    while(fgets(line, MAX, stdin)){
            printf("string is: %s\n",line);

    }
    return 0;

The output results in:
string is: i 10

string is: i 20

string is: i 30

string is: i 40

string is: i 50

string is: i 45

string is: r 48

So, what i need to do now is to assign an char array with the first column and an integer array with the second. Something like int V[size] = [10,20,30,40,50,45,48] and char W[size] = [i,i,i,i,i,i,r]. How can I do that?

A: Use sscanf() to parse the string and extract the data you want.
#include <stdio.h>
#include <stdlib.h>

#define MAX 500

int main(void)
{
  int num[MAX] = {0}, lines = 0;
  char line[MAX] = {0}, sym[MAX] = {0};

  while (fgets(line, MAX, stdin))
  {
    if (lines >= MAX) /* alternative check comments */
    {
      fprintf(stderr, "arrays full\n");
      break; /* break or exit */
    }

    if (sscanf(line, "%c %d", &sym[lines], &num[lines]) != 2) /* check return value for input error */
    {
      /* handle error */
      exit(EXIT_FAILURE);
    }

    lines++;
  }

  for (int i = 0; i < lines; i++)
  {
    printf("char: %c | num: %d\n", sym[i], num[i]);
  }

  exit(EXIT_SUCCESS);
}

You may also use feof() and ferror() to determine if fgets() failed or you reached EOF .


text:
Q: Ionic httpClient response use toast i send login data to service, after get response in login.ts toast is not difined, how to resolve this ?
i try my toast function in another function withot condition in service its work

this my function for load service login.ts:

import { Component, OnInit } from '@angular/core';
import { NavController, MenuController, PopoverController } from "ionic-angular";
import { TabsInfluencerComponent } from '../../influencer/tabs/tabs';
import { RegisterComponent } from '../register/register';
import { ResetComponent } from '../reset/reset';
import { OfferComponent } from '../../advertiser/offer/offer';
import { ngForm } from '@angular/forms';
import { AuthService } from '../../../services/auth';
import { ToastController } from 'ionic-angular';

@Component({
    templateUrl: 'login.component.html',

})

export class LoginComponent implements OnInit {

    constructor(
        public nav:NavController,
        public menu:MenuController,
        public popover: PopoverController,
        private AuthService : AuthService,
        private toastCtrl: ToastController) {

    }

    responseData : any;
    public isChoose: boolean = false;
    public isshowP: boolean = false;
    //login and get data in service
    login(form: ngForm){
        this.AuthService.login(form.value.email, form.value.password)
        .then(function(data) {
            if(data.success == true){
                localStorage.setItem('userToken',data.token);
                localStorage.setItem('userData',JSON.stringify(data.user));
            }else{
                let toast = this.toastCtrl.create({
                  message: data.error,
                  duration: 3000
                });
                toast.present();
            }
        })
        .catch(function(error) {
            console.log(error);
        })
    }

}

this my service auth.ts:

    import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators'

@Injectable()
export class AuthService {
    private loginUrl : string = 'http://localhost:8000/api/login';
    data : any;
    constructor(private http: HttpClient){}
    //function for login
    login(email : string, password :string){
        const body = {email : email, password : password};
        return new Promise(resolve => {
          this.http.post(this.loginUrl, body)
            .subscribe(data => {
              this.data = data;
              resolve(this.data);
            });
        });
    }

    register(email : string, password :string){

    }
}

after run i have error like this :
TypeError: Cannot read property 'toastCtrl' of undefined

A: In this case it is a problem with your this reference in your login.ts.
.then(function(data) {
    ...
    let toast = this.toastCtrl.create({
        message: data.error,
        duration: 3000
    });
    ...
})

The this is referring the anonymous function in your then block, but you want to refer back to your LoginComponent class.
How to solve this?
You could use arrow functions, that are really popular right now.
.then((data) => {
    ...
    let toast = this.toastCtrl.create({
        message: data.error,
        duration: 3000
    });
    ...
})


text:
Q: GEE: masking for multiple pixel values The GEE tutorial shows how to mask an image for one pixel value using .eq(pixel value).
However, I want to mask all pixels in an image with a value of 15 or less in this dataset
var riverflow = ee.Image('WWF/HydroSHEDS/15ACC');

var flowAccumulation = riverflow.select('b1');

And now I need to use .updateMask. This must be very straightforward right?

A: If you want to keep pixels that have a value of 15 or less than 15 and mask the rest of the pixels:
var riverflow = ee.Image('WWF/HydroSHEDS/15ACC');

var flowAccumulation = riverflow.select('b1');
//Map.addLayer(flowAccumulation)

var masked = flowAccumulation.updateMask(flowAccumulation.lte(15));
//Map.addLayer(masked)

On the other hand, If you want to mask the pixels that have a value of 15 or less than 15 and keep the rest of the pixels:
var riverflow = ee.Image('WWF/HydroSHEDS/15ACC');

var flowAccumulation = riverflow.select('b1');
//Map.addLayer(flowAccumulation)

var masked = flowAccumulation.updateMask(flowAccumulation.gte(15));
//Map.addLayer(masked)

Hope it helps.


text:
Q: tkinter Checkbutton not working as expected I am trying to recreate the example as given in https://www.askpython.com/python-modules/tkinter/tkinter-checkbox-and-checkbutton, which uses the following code:
from tkinter import *

def click_me():
print(i.get())

root =Tk()
i=IntVar()
c = Checkbutton(root, text = "Python", variable=i)
c.pack()

b = Button(root,text="Click here",command=click_me)
b.pack()

root.geometry("400x400+120+120")
root.mainloop()

However, for me, it doesn't have the desired output. In the example they obtained a value of 1 for the checkbox being clicked and 0 for the checkbox being no clicked. However, I obtain a value of 0 for both when it is and is not checked. Any ideas about what I'm doing wrong been stumped for a while on this!
Versions used:
conda -- 4.10.1
tk -- 8.6.10 -- hb0a8c7a_0
spyder -- 4.2.5 -- py38hecd8cb5_0
Thanks in advance


text:
Q: android expandablelistview can not use notifyDataSetChanged()? i want to refresh my expandablelistview , but it seems there is no way to use notifyDataSetChanged()??
how can i refresh my expandablelistview?? thx

A: Have your adapter extend BaseExpandableListAdapter or one of its subclasses.  This class has the notifyDataSetChanged method in it.

A: Why not notifyDataSetChanged()?


text:
Q: Spring Boot + Swagger UI We have REST API created in Spring Boot and secured by Spring Security. Swagger-UI is used for documenting the API. It works well.
Now we decided to create two user roles and allow each role specific access.
We have two roles:
role1, role2
Current situation:
/endpoint1 (secured only for role1)
/endpoint2 (secured only for role1)
/endpoint3 (can access both role1 and role2)

Securing endpoints works well by spring security @Secured annotation.
The problem is the documentation is generated in one swagger-ui.html file and both role1 and role2 can access it and see doc for all endpoints.
We would like each user role see only docs for it's endpoints. So we have idea to separate swagger-ui.html docs somehow to two files because it is easy to configure spring security roles for different endpoints.
Something like this:
/a/swagger-ui.html:
/endpoint1
/endpoint2
/endpoint3

Accessible only for role1
And:
/b/swagger-ui.html:
/endpoint3

Accessible only for role2
Is it good idea? What do you think is the best practice to follow our scenario? If solution is to split swagger-ui to two files than how can we do that? Or any other solution?


text:
Q: Terminating UDP Stop and wait I am coding a stop and wait UDP file transfer.
Everytime i send a packet, ill start a timeout timer and wait for acks. If i recv an ack, ill transmit the next packet. If i recv a nack or did not recv acks, once my timeout expires, ill retransfer the packet.
For the receivers end, whenever i recv a packet, ill transmit a ack when checksum and seq number tallies. Else a nack.
This is my school assignment, to code a udp file transfer with error detection.
So dont ask me to use tcp.
The problem is when i want to end the connection. Once the last packet has been sent, ill now send a EOF message to the receiver, signalling the end of file transfer. So i send the EOF message, and start the timer. The reciver, receives the EOF message, sends back an ACK message and shutsdown. However, if this ACK message gets discarded, the sender is gonna timeout and will repeatedly resend the EOF message. How do i go about preventing this?


text:
Q: 'System.TypeInitializationException' being thrown on previously working code My code worked fine previously, but now when I run it; it throws up this exception:

An unhandled exception of type 'System.TypeInitializationException'
  occurred in Debug Chamber.exe  Additional information: The type
  initializer for 'varBank' threw an exception.

What's even weirder is that I have changed nothing except for adding this class:
public class readParameters
{
    public static void readLog(int start, int end)
    {
        for (int x = start; x < end; x++)
        {

        }
    }
    public static void nextLine()
    {
        string[,] logArr = new string[4, 5];
    }
}

The line in question is highlighted in the block below

/// </data bank>
public class varBank
{
    public static string logInput { get; set; }

    public static PathType FilePath { get; private set; }

    public static EventLogReader evl = new EventLogReader(logInput, FilePath);

    public static EventRecord bsnRecord = evl.ReadEvent();
}
/// </data bank>

namespace EventLogInfoReader
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Log Location: ");

          varBank.logInput = Console.ReadLine();

            Console.WriteLine("Enter Read Parameters: ");
            int i = 1;
            while (++i > 0)
            {
                Console.WriteLine("Enter Property: ");
                string CommandInput = Console.ReadLine();
                getInfo.callInfo(CommandInput);
            }
        }
    }
}

A: That exception means an exception was thrown from a static constructor or field initializer.  I suspect it's in the initializer for evl, since it's referencing static properties that do not have initial values set (they will be null).
I would move that code to a static constructor so you can do better error handling and/or logging.  Both evl and bsnRecord have static initializers thatr are vulnerable to run-time exceptions and should not go unchecked.
I also question why you have static properties that's initialized using other static properties.  What do you expect to happen if client code sets the FilePath property?


text:
Q: Make a countdown timer display a modal window bootstrap I have another issue. This time I want to make that when a countdown timer reaches 0 it triggers or display a modal window to show up.
I have both the codes for the modal and the countdown timer, but I dunno how exactly make it so it calls for the modal.
I've tried several suggestions I've read but none works or it just screws the code.
Many thanks in advance.

var seconds = 300; //**change 120 for any number you want, it's the seconds **//
function secondPassed() {
    var minutes = Math.round((seconds - 30)/60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds;
    }
    document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        clearInterval(countdownTimer);
        document.getElementById('countdown').innerHTML = "Last chance!";
    } else {
        seconds--;
    }
}

var countdownTimer = setInterval('secondPassed()', 1000);

This is your last chance!

              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Your spot can't be reserved any longer! Click the button to join now!

            <button id="btnjoin" type="submit" onclick="location.href='http://google.com';">Join!</button>

            This is your last chance!

Over 87 people have claimed their spot. Get yours before time runs out!

A: Just use
$('#ventanamdl').modal('show');

For your purpose
var seconds = 300; //**change 120 for any number you want, it's the seconds **//
function secondPassed() {
    var minutes = Math.round((seconds - 30)/60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds;
    }
    document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        clearInterval(countdownTimer);
        document.getElementById('countdown').innerHTML = "Last chance!";
        $('#ventanamdl').modal('show');
    } else {
        seconds--;
    }
}

//now your setInterval call is ok
var countdownTimer = setInterval(secondPassed, 1000);

Your setInterval call was not ok.
Make sure your bootstrap CSS and JS and jQuery are properly loaded.


text:
Q: C# Drag and Drop sem um evento especifico Estou desenvolvendo uma aplicação em C#(WPF) e gostaria de saber se alguém sabe como obter os dados do drag n drop do mouse sem nenhum evento ser disparado.
Existe alguma maneira de retornar esses dados do dragndrop do mouse(um arquivo sendo arrastado por exemplo) sem nenhum evento específico ou se é possível simular o Drop e obter os dados do Mouse naquele momento?


text:
Q: Entity Framework: Fluent API. How should I map this relationship? My table is as follows:
create table Entities(
    EntityId bigint not null identity(1, 1),
    Name nvarchar(64) not null,
    ParentEntityId bigint null
)
alter table Entities add constraint PK primary key (EntityId)
alter table Entities add constraint FK foreign key (ParentEntityId) references Entities(EntityId)

My model looks like this:
public class Entity
{
    [Required]
    public virtual long EntityId { get; set; }

    [Required]
    public virtual string Name { get; set; }

    public virtual long? ParentEntityId { get; set; }

    public virtual Entity ParentEntity { get; set; }
}

and I'm trying to map the ParentEntity property with fluent api mapping, but I couldn't get this to work. How can I do it?
Thanks in advance!
EDIT: Fixed code discrepancy.

A: This fluent will work for you:
        modelBuilder.Entity<Entity>()
            .HasOptional(e => e.ParentEntity)
            .WithMany()
            .HasForeignKey(e => e.ParentEntityId );

Created this database for me:


text:
Q: sending a char to usb port by java coded in eclipse IDE I have an arduino USB interfacing boarding which is already coded to glow an LED when it receives an "L" from usb port. I just want a java code. rxtx is already correctly setup.. test file run successfully.
here is my code:(I took help from internet)
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

import java.io.*;
import java.util.*;

 public class SimpleWrite {
@SuppressWarnings("rawtypes")
static Enumeration portList;
static CommPortIdentifier portId;
static String messageString = "L";
static SerialPort serialPort;
static OutputStream outputStream;

public static void main(String[] args) throws IOException{
    portList = CommPortIdentifier.getPortIdentifiers();
    int i;
    while (portList.hasMoreElements()) {
        portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
             if (portId.getName().equals("COM12")) {
           // if (portId.getName().equals("/dev/term/a")) {
        while(( i=System.in.read()) != 13)
        messageString += (char)i;
    try {
                    serialPort = (SerialPort)
                        portId.open("SimpleWriteApp", 2000);
                } catch (PortInUseException e) {System.out.println(e);}
                try {
                    outputStream = serialPort.getOutputStream();
                } catch (IOException e) {System.out.println(e);}
                try {
                    serialPort.setSerialPortParams(9600,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
                } catch (UnsupportedCommOperationException e) {System.out.println(e);}
                try {               System.out.println(messageString);
                    outputStream.write(messageString.getBytes());
                } catch (IOException e) {System.out.println(e);}
            }
        }
    }
}
}

there is no warning no error shown in eclipse console. But LED remain in off stage. COM-PORT , BAUDRATE PARITY everything were checked by XCTU.
Where am I going wrong?


text:
Q: Creating combinations from a tuple I take the data from the database. From the database they come in the form of a tuple:
[('test1', 'test12', 'test13', 'test14'),
('test21', 'test22', 'test23', 'test24'),
('test31', 'test32', 'test33', 'test34'),
('test41', 'test42', 'test43', 'test44'),
('test51', 'test52', 'test53', 'test54'),
('test61', 'test62', 'test63', 'test64'),
('test71', 'test72', 'test73', 'test74'),
('test81', 'test82', 'test83', 'test84'),
('test91', 'test92', 'test93', 'test94'),
('test11', 'test12', 'test13', 'test14')]

And that's what I want:
make combinations of these input... so the output I had a combination of 4 parameters (such as in example) and...
1) most importantly, new combinations,the values were always in its place, i.e. if in the original combinations the values were index [1], this means that in the new combination, it should also be [1]...
2) there are no duplicate combinations
As example:
I got tuple:
[('test91', 'test92', 'test93', 'test94'),
('test11', 'test12', 'test13', 'test14')]

And from this I got new combinations:
[('test91', 'test12', 'test13', 'test14'),
('test11', 'test92', 'test93', 'test94')]

Maybe it's possible to do using the method of pairwise or something else.
Help.

A: You need to use product method from builtin package itertools which gives cartesian product of input iterables.
Here is code that do what you desire.
But be careful, because huge list would produce a ton of combinations, try not to run out of memory.
from itertools import product

data = [('test91', 'test92', 'test93', 'test94'),
('test11', 'test12', 'test13', 'test14')]

b = list(zip(*a))  # making list of n-th elements
# b = [('test91', 'test11'),  <- first elements
# ('test92', 'test12'),  <- second elements
# ('test93', 'test13'),  <- third elements
# ('test94', 'test14')]
variations = product(*b)
output = set(variations) - set(a)  # this is unique variations without input data
#  output = {('test11', 'test12', 'test13', 'test94'),
#  ('test11', 'test12', 'test93', 'test14'),
#  ('test11', 'test12', 'test93', 'test94'),
#  ('test11', 'test92', 'test13', 'test14'),
#  ('test11', 'test92', 'test13', 'test94'),
#  ('test11', 'test92', 'test93', 'test14'),
#  ('test11', 'test92', 'test93', 'test94'),
#  ('test91', 'test12', 'test13', 'test14'),
#  ('test91', 'test12', 'test13', 'test94'),
#  ('test91', 'test12', 'test93', 'test14'),
#  ('test91', 'test12', 'test93', 'test94'),
#  ('test91', 'test92', 'test13', 'test14'),
#  ('test91', 'test92', 'test13', 'test94'),
#  ('test91', 'test92', 'test93', 'test14')}

If you want output to be with input data you can simply
output = set(variations)

If you need a list instead of set, just do
output = list(output)


text:
Q: Asterisk and isdn phone: can "receive" calls, but outgoing calls are not seen by asterisk I have configured a b410p isdn card with four NT ports. On the 4th NT port i put a TA which is on Windows os, and run an old isdn phone software(rvs phone).
I have configured the extensions.conf file like this
[from-dahdi]
exten => 084766508,1,Dial(DAHDI/g14/${EXTEN})
exten => 084766508,2,Hangup()
exten => _039.,1,Dial(DAHDI/4/${EXTEN})

If from console i call the 084766508 number the phone ring(but if I answer the call fail with 3302 isdn error), but if I call from the isdn phone a test number (200 for example)
the software phone put the 039 prefix, so I wrote the extension _039.
The problem is the outgoing call is not seen by asterisk, i also write
pri set debug on span 4

but report nothing.

A: Solution found, I forgot to said the Windows was a virtual machine, If I redirect the usb TA adapter with usb redirection works very bad, can receive but not send the packets, if I put a pci-e usb adapter and redirect it(vfio pci-e redirect) then I connect the usb TA to it, works perfect: can answer, can call, can send packets.


text:
Q: Android: Decoding JSON [{"placeID":"p0001","placeName":"INTI International University","placeType":"Education","placeLat":"2.813997","placeLng":"101.758229","placePict":""},{"placeID":"p0002","placeName":"Nilai International College","placeType":"Education","placeLat":"2.814179","placeLng":"101.7700107","placePict":""}]
How do I decode the JSON sent from my PHP script on Android?

A: please try this
 String s = "[{\"placeID\":\"p0001\",\"placeName\":\"INTI International University\",\"placeType\":\"Education\","
            + "\"placeLat\":\"2.813997\",\"placeLng\":\"101.758229\",\"placePict\":\"\"},"
            + "{\"placeID\":\"p0002\",\"placeName\":\"Nilai International College\",\"placeType\":\"Education\",\"placeLat\":\"2.814179\",\"placeLng\":\"101.7700107\",\"placePict\":\"\"}]";
    ArrayList<String> arrplaceID = new ArrayList<String>();
    ArrayList<String> arrplaceName = new ArrayList<String>();
    try {
        JSONArray arr = new JSONArray(s);
        for (int i = 0; i < arr.length(); i++) {
            JSONObject jsonObject = arr.getJSONObject(i);
            arrplaceID.add(jsonObject.optString("placeID"));
            arrplaceName.add(jsonObject.optString("placeName"));
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    for (int i = 0; i < arrplaceID.size(); i++) {
        Log.e("arr[" + i + "] place Name", arrplaceName.get(i));
    }

A: What is the problem in this Please Read this tutorial for parsing JSON it might be helpful in future also.json parsing link

A: Follow below points.
1) it seems the response you are getting is Json Array. so create one json array by response string.
              JSonArray jArray = new JsonArray(responseString);

2) now you have your response in jArray. now iterate a loop and take json object from JsonArray, in your case you have two json objects.
      for(i,i<jArray.size,i++)
   {
      JsonObject obj=jArray.get(i);
     // here you got your first entry in jsonObject.
     // nor use this obj according to ur need. you can say obj.getString("placeID");
    // and so on.
     }

refer this to understand more on json link

A: use JSONArray class:
JSONArray jsonplaces = new JSONObject(stringPlaces);

then your able to iterate throught array by using for-loop:
for (int i = 0; i < jsonplaces.length(); i++) {
    JSONObject jsonplace = (JSONObject) jsonplaces.get(i);
    //read items, for example:
    String placeName = jsonplace.getString("placeName");
}


text:
Q: JNI memory management Question 1: In the function below I want to call ReleaseStringUTFChars method before returning value. How I can do that as in this case may application crashes.
String JNIXMLDOMDocument::GetXML() const
{
    String strXML;

    jmethodID method = m_JavaEnv->GetMethodID(m_XMLDomDocClass, "GetXML", "(Lorg/w3c/dom/Document;)Ljava/lang/String;");
    if(method == NULL) {
        return NULL;
    }

    jstring jstrXML = (jstring)m_JavaEnv->CallObjectMethod(m_XMLDomDocClassObject, method, m_XMLDomDocument);
    if (jstrXML == NULL) {
    return strXML;
    }

    strXML = m_JavaEnv->GetStringUTFChars(jstrXML, 0);

    /* Question 1:  **/
    m_JavaEnv->ReleaseStringUTFChars(jstrXML, strXML.c_str());

    return strXML;

} /* String GetXML() const **/

Question 2: Is it correct to attach thread in the constructor and use it in all functions, and detach in the destructor, if my application use multithreading ?
JNIXMLDOMDocument::JNIXMLDOMDocument()
{
    /* Check If the current thread is attached to the virtual machine. **/
    int needToDetach;
    /* Question 2:  **/
    m_JavaEnv = AttachCurrentThread(&needToDetach);
    if (m_JavaEnv != NULL)
    {
        /* Try to find JAVA 'XMLDOMDocument' class. **/
    m_XMLDomDocClass = m_JavaEnv->FindClass("com/fido/android/framework/service/XMLDOMDocument");
    if (m_XMLDomDocClass != NULL) {
        jmethodID constructor = m_JavaEnv->GetMethodID(m_XMLDomDocClass, "<init>", "()V");
        if (constructor != NULL) {
            m_XMLDomDocClassObject = m_JavaEnv->NewObject(m_XMLDomDocClass, constructor);
        }
        else DBG_ERROR(DBG_CTX, ("Can't create object of 'XMLDOMDocument' class!\n"));
    }
    else DBG_ERROR(DBG_CTX, ("Can't find 'XMLDOMDocument' class!\n"));

    /* Try to find 'XMLDOMNode' class. **/
    jclass localXMLDomNodeClass = m_JavaEnv->FindClass("com/fido/android/framework/service/XMLDOMNode");
    if (localXMLDomNodeClass != NULL) {
        jmethodID constructor = m_JavaEnv->GetMethodID(localXMLDomNodeClass, "<init>", "()V");
        if (constructor != NULL) {
            m_XMLDomNodeClassObject = m_JavaEnv->NewObject(localXMLDomNodeClass, constructor);
        }
        else DBG_ERROR(DBG_CTX, ("Can't create object of 'XMLDOMNode' class!\n"));
    }
    else DBG_ERROR(DBG_CTX, ("Can't find 'XMLDOMNode' class!\n"));

    }

} /* JNIXMLDOMDocument() **/

A: First part: i don't know what type your String is. From the fact that it apparently can take const char* assignment and has a c_str() method, i guess a std::string or similar. Guessing further, your String is making a copy of the cstring you are giving to it, so it should survive releasing the original cstring. But you are releasing the cstring inside your String, not the one you got from GetStringUTFChars. So you are returning an invalid String.
So while the answer is yes, you indeed must call ReleaseStringUTFChars, the correct way is
String strXML;
const char* tempStr = m_JavaEnv->GetStringUTFChars(jstrXML, 0);
strXML = tempStr;
m_JavaEnv->ReleaseStringUTFChars(jstrXML,tempStr);
return strXML;

I can't answer the second part confidently, i am not into NDK. Make separate question.

A: To answer your second question alone, there's not enough information provided, but in general you can attach and detach via a constructor/destructor pair if both are called by the same thread.


text:
Q: Windows Python 3.7 closing before .py file is done running I wrote a python script in Spyder and am trying to run it on my machine but Python 3.7 on windows closes it to early.
My code is:
print('Campus Pizza Ordering Program\n')

crust = input('What crust? Regular or Wheat? ')
num_toppings = int(input('How many toppings (please enter a whole number)? '))
price = format((7 + num_toppings * 0.75),".2f") #looked up how to round to 2 decimals

print('\nYou have a '+crust+' pizza with '+str(num_toppings)+' toppings. ' +
      'The final price of the pizza is $'+str(price)+".")

The program closes though before the final print statement is executed. Why?

A: I am assuming you are running this script through "run python file"(python terminal). This will close the window directly after you are done. The way to bypass this is by adding an empty input at the bottom.
print('Campus Pizza Ordering Program\n')

crust = input('What crust? Regular or Wheat? ')
num_toppings = int(input('How many toppings (please enter a whole number)? '))
price = format((7 + num_toppings * 0.75),".2f") #looked up how to round to 2 decimals

print('\nYou have a '+crust+' pizza with '+str(num_toppings)+' toppings. ' +
      'The final price of the pizza is $'+str(price)+".")
input()

A: Most likely what is happening here is that the program prints the final line then terminates immediately causing you to not see the print.
Try adding this to the end of your script:
input('\nPress "ENTER" to exit')

A: Make sure that spyder is up to date because it can close if it is on an outdated version

A: Consider importing time and using time.sleep(5) at the end of your program so you can see if the output prints.


text:
Q: Windows could not start the SharePoint search host controller service on local computer. Error:5 Access is denied I am unable to start the SharePoint search host controller service though I run the services.msc as an administrator.
When I am trying to update a list item, I am getting the following error.

The server was unable to save the form at this time. Please try again.

Update 1:
This is how my service looks like right now:

As you can see that the Log On As is set to Network Service.
Will this be an issue?

A: Make sure that the service for search host controller is run under the correct domain account. Make sure its an account that has enough credentials and that the password does not expire! also make sure its a managed account within central admin
for details on managed accounts and password change: Click here
make sure that the account that your using is part of the local admin group as well!
goto users and computers to add the managed user account to wss_admin_wpg

Go to "active directory users and computers" -> select the account that
  is a domain account that is used for the service -> right click the
  account and select "add to group" -> click advanced and search for wss
  -> it should show three groups... You need to select WSS_ADMIN_WPG and click OK -> OK and now it should have correct access.

what version of SharePoint your using?
as for changing the account or checking:

goto services.msc -> goto the service in question -> right click and
  select properties -> within the new popup select on "log on" tab ->
  change to an account that has the right privileges to run that service!

so what have we done?
1) made sure the account were using is managed within central admin so that password is auto changed and doesn't effect services and is now accessible when creating services through central admin to be selected as a service account
2) made sure it has the correct privileges on the server to run the queries or anything that needs elevated rights or resources only available as admin on the local server like local resources
3) changed the service to use the new account or updated account if it is not the correct one!
EDIT
you can use the network account but it would still need the right privileges and is not adhering to best practices... you should have a new account that is a service account specific to search. please refer here
as noted the account Network Service doesn't have the right privileges and ideally you shouldn't elevate its privileges but rather create a new account through central admin and add it as a service account -> make sure its part of wss_admin_wpg and then change the service to this new account and do an iis reset and all should work fine!

A: The most common cause for that , that I've found, was sharepoint being installed on the box, but the service instance being in a disabled state.
Get-spenterprisesearchserviceinstance -identity <servername> to confirm
if disabled, do $ssi = get-spenterprisesearchserviceinstance -identity servername>
then $ssi.provision()


text:
Q: similar to the Magento2 - Fail I've created an extension which I uploaded on marketplace for technical review. I got the following response in technical submission:
Review Results:

Tech: Code quality issues: CPD: This extension contains duplicated code.

vendor/MCB/CreditmemoCronTime.php - similar to the Magento2 - Fail
magento/module-backup/magento-module-backup-100.3.0-beta32/Model/Config/Backend/Cron.php
vendor/MCB/ContactsCronTime.php - similar to the Magento2 - Fail
magento/module-backup/magento-module-backup-100.3.0-beta32/Model/Config/Backend/Cron.php
vendor/MCB/InvoicesCronTime.php - similar to the Magento2 - Fail
magento/module-backup/magento-module-backup-100.3.0-beta32/Model/Config/Backend/Cron.php
vendor/MCB/ItemsCronTime.php - similar to the Magento2 - Fail
magento/module-backup/magento-module-backup-100.3.0-beta32/Model/Config/Backend/Cron.php

ContactsCronTime.php file

<?php

namespace Vendor\Test\Model\Config\Backend;

class ContactsCronTime extends \Magento\Framework\App\Config\Value
{
    /**
     * Cron string path variable
     */
    const CRON_STRING_PATH = 'crontab/default/jobs/test_contacts_job/schedule/cron_expr';

    /**
     * Cron model path variable
     */
    const CRON_MODEL_PATH = 'crontab/default/jobs/test_contacts_job/run/model';

    /**
     * @var \Magento\Framework\App\Config\ValueFactory
     */
    protected $_configValueFactory;

    /**
     * @var string
     */
    protected $_runModelPath = '';

    /**
     *
     * @param \Magento\Framework\Model\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $config
     * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
     * @param \Magento\Framework\App\Config\ValueFactory $configValueFactory
     * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
     * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
     * @param string $runModelPath
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\App\Config\ScopeConfigInterface $config,
        \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
        \Magento\Framework\App\Config\ValueFactory $configValueFactory,
        \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
        \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
        $runModelPath = '',
        array $data = []
    ) {
        $this->_runModelPath = $runModelPath;
        $this->_configValueFactory = $configValueFactory;
        parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
    }

    /**
     * {@inheritdoc}
     *
     * @return $this
     * @throws \Exception
     */
    public function afterSave()
    {
        $time = $this->getData('groups/synchronization/groups/test_contacts/fields/cron_time/value');

        // phpcs:disable
        if ($time == '60') {
            $time = 0;
            $cronExprArray = [
                intval($time), //Minute
                '*', //Hour
                '*', //Day of the Month
                '*', //Month of the Year
                '*', //Day of the Week
            ];
        } elseif ($time == '120') {
            $time = 2;
            $cronExprArray = [
                '0', //Minute
                '*/'.intval($time), //Hour
                '*', //Day of the Month
                '*', //Month of the Year
                '*', //Day of the Week
            ];
        } else {
            $cronExprArray = [
                '*/'.intval($time), //Minute
                '*', //Hour
                '*', //Day of the Month
                '*', //Month of the Year
                '*', //Day of the Week
            ];
        }

        $cronExprString = join(' ', $cronExprArray);

        try {
            $this->_configValueFactory->create()->load(
                self::CRON_STRING_PATH,
                'path'
            )->setValue(
                $cronExprString
            )->setPath(
                self::CRON_STRING_PATH
            )->save();
            $this->_configValueFactory->create()->load(
                self::CRON_MODEL_PATH,
                'path'
            )->setValue(
                $this->_runModelPath
            )->setPath(
                self::CRON_MODEL_PATH
            )->save();
        } catch (\Exception $e) {
            throw new \Exception(__('We can\'t save the cron expression.'));
        }
        // phpcs:enable

        return parent::afterSave();
    }
}

Although core file and mine file code is totally different.

Can anyone explain what is the meaning of this error and how can I fix this to resubmit it again for technical review?

A: You are using the duplicated code of Magento core class
magento/module-backup/magento-module-backup-100.3.0-beta32/Model/Config/Backend/Cron.php

in your following classes
vendor/MCB/CreditmemoCronTime.php
vendor/MCB/ContactsCronTime.php
vendor/MCB/InvoicesCronTime.php
vendor/MCB/ItemsCronTime.php

you need to extend your classes from Magento core class instead of duplicating its code
EDIT
please check it your code is duplicated with the core file


text:
Q: How can I navigate through a list using arrow keys in react? I am modifying an existing react application where I display a list, and would like to navigate through the list using the up/down arrow keys. Right now, I can't seem to get the onKeyDown event to fire when I place it in the div.
Before anybody tags as duplicate, I have looked through related questions and can't seem to work the solutions into my own code - they don't work for me. I was most recently trying to follow the accepted answer here and was able to get event to register when I add to an input div tag, but not on its own.
I've placed it in a few different div tags to try to get it in the right spot, but nothing seems to work for me.
I tried adding the following to the div tags below:
onKeyDown={() => console.log("keyPressed"} I've also tried adding tabIndex="0" but I get an error about assigning a string to a number.
return(
     <BaseLayout>

         <myList className="custom-list-a" items={allListItems} />
)

There are other elements on the page, I'd like to just be iterating through my list with the up and down arrow keys. (I have a separate irrelevant function called onKeyPressed that will increment the index etc, I'm just needing the event to be responded to.)
Thanks in advance.

A: import React, {useEffect, useState} from 'react';

export default () => {
  const [arrow, updateState] = useState('')
  useEffect(() => {
    document.addEventListener("keydown", (e) => {
      if(e.key === 'ArrowDown') {
        updateState(String.fromCharCode(8595));
      } else if(e.key === 'ArrowUp') {
        updateState(String.fromCharCode(8593))
      }
    })
  }), [];
  return
{arrow}

}

Stack Blitz


text: Q: What determines the penetration of electromagnetic waves? What is it that determines whether or not an electromagnetic wave can penetrate different materials and how far it can go? For example light can penetrate through glass, but not concrete walls, but radio waves can penetrate concrete walls in large distances


text:
Q: My EF query can't return the datetime in c# I have this database as you can see :

In My code i want to return some of these records with datetime condition as you can see :
private void lblSubmitDate_EditValueChanged(object sender, EventArgs e)
{
  DateTime subDateTime = Convert.ToDateTime(lblSubmitDate.EditValue).Date;
            gridControlDocument.DataSource =
                new BindingList<Document>(_documentRepository
                .Get()
                .Where(i => i.SubmitDateTime==subDateTime)
                .ToList())
                { AllowNew = true };
}

But no records returned.
The image of my input :

The result in sqlprofiler :
exec sp_executesql N'SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[Number] AS [Number],
    [Extent1].[Class] AS [Class],
    [Extent1].[Discipline] AS [Discipline],
    [Extent1].[Unit] AS [Unit],
    [Extent1].[SubmitDateTime] AS [SubmitDateTime]
    FROM [dbo].[Documents] AS [Extent1]
    WHERE [Extent1].[SubmitDateTime] = @p__linq__0',N'@p__linq__0 datetime2(7)',@p__linq__0='2016-07-27 00:00:00'

A: What Josh said is correct.

You will never retrieve any values because you are parsing the
  DateTime, but then taking only the Date portion. This means the Time
  portion will be 00:00:00:

You have to use EntityFunction.TruncateTime to get only the Date
gridControlDocument.DataSource =
          new BindingList<Document>(_documentRepository
          .Get()
          .Where(i => EntityFunctions.TruncateTime(i.SubmitDateTime)==subDateTime)
          .ToList()) { AllowNew = true };

A: You will never retrieve any values because you are parsing the DateTime, but then taking only the Date portion. This means the Time portion will be 00:00:00:
DateTime subDateTime = Convert.ToDateTime(lblSubmitDate.EditValue).Date;

When you try to select the rows, you are comparing to SubmitDateTimes that have a time component:
gridControlDocument.DataSource = new BindingList<Document>(_documentRepository.Get().Where(i => i.SubmitDateTime==subDateTime).ToList()) { AllowNew = true };

You need to compare the Date portion from the database field with the parsed Date from the user selection.


text:
Q: AWS API Gateway default response and Trigger AWS Lambda I have been experimenting with AWS API Gateway and AWS Lambda to try out a serverless architecture. Have been going through blogs and AWS documentation. Have tried out sample GET/POST. But, I have the following requirement w.r.t tracking user events from my custom application

*

*Events are posted from my application to API end point

*

*I wanted the API to respond back with a custom response (Say {'fine'})
(acknowledging that the request has been received)

*After the response is sent, hand over the event payload to a AWS Lambda function

As per the documentation, I understand,
 a) I can post events to API end point
 b) On GET/POST trigger an AWS Lambda Function
   - Respond back from AWS Lambda function to API request
I wanted to change the above and modify it to
 a) Post events to API end point
  a.0) Respond back acknowledging that request is received [Say {'fine'} ]
 b) Trigger AWS Lambda function to process the event payload
Please share across suggestions on how to achieve the same.

A: If you want a fast response from the API and not have to wait for the processing of data, you could:

*

*post an event to an API Gateway endpoint

*trigger an AWS Lambda Function A

*call asynchronously a Lambda Function B using the AWS SDK in the Lambda Function A

*Call context.succeed() or context.done() or the callback function in the Lambda Function A so it respond back to API Gateway

*the Lambda Function B can process the data while API Gateway already received a response

A: Another asynchronous model many customers have used:

*

*Set up an API configured to send requests to Amazon Kinesis. This API could acknowledge the request.

*Set up AWS Lambda to consume your Kinesis stream.

This setup has some advantages for high workload APIs as fetches from the Kinesis stream can be batched and don't require a 1-to-1 scaling of both your API Gateway limits and Lambda limits.
Update
To answer your questions about scalability:
Kinesis
Kinesis scales by adding what it calls "shards" to the stream. Each shard handles a portion of your traffic, based on a partition key. Each shard scales up to 1000 rps or 1MBps (see limits). Even with the lower default 25 shards, this would support up to 25,000 rps or 25MBps with an evenly distributed partition key.
API Gateway
API Gateway has a default account level limit of 500 rps, but this can easily be extended by requesting a limit increase. We have customers in production that are using the service at limits above your current suggested scale.

A: You should first run some tests to see what type of real world response times you are getting from having your lambda function complete all the logic. If the times are above what you feel are acceptable for your use case, here is another asynchronous solution utilizing an SNS Topic to trigger a secondary Lambda function.

*

*Client Request to API Gateway -> Calls Lambda function A

*Lambda A verifies payload and then publishes to SNS Topic X

*Lambda A returns {fine} success message -> API Gateway -> client

*SNS Topic X triggers Lambda function B

*Lambda function B implements given logic


text:
Q: C# referencing values across forms Im having a problem trying to reference values across forms, i tried using the method below but im receiving an error.
Error:
"System.NullReferenceException: 'Object reference not set to an instance of an object.'
tmp was null."
Is there another way I can reference values across forms or am i doing something wrong.  Any Help would be appreciated.Thanks.
public partial class PlayMenu : Form
{
    private void PlayMenu_KeyDown(object sender, KeyEventArgs e)
    {
        if (finishline = true)
        {
            getNewTimeElapsed();
            MainMenu tmp = (MainMenu)this.Owner;
            tmp.addLastScoreLevel1(TimeElapsed);
            this.Close();
        }
    }
    public float getNewTimeElapsed()
    {
        return TimeElapsed;
    }
}

public partial class MainMenu : Form
{
    public void addLastScoreLevel1(float newScore)
    {
        HighScoresMenu tmp2 = (HighScoresMenu)this.Owner;
        PlayMenu tmp3 = (PlayMenu)this.Owner;

        if (newScore < tmp2.HighScores[4])
        {
            tmp2.HighScores[4] = newScore;
            tmp2.HighScoresName[4] = getPlayersName();
            Array.Sort(tmp2.HighScores, tmp2.HighScoresName);
        }
    }
}

A: So you need to get the parent class of PlayMenu.
Instead of
MainMenu tmp = (MainMenu)this.Owner;

try using
MainMenu tmp = (MainMenu)this.Parent;


text:
Q: BigQuery GetQueryResultsResponse.getPageToken() returns null when BigQuery Table is getting inserts by another application I have a BigQuery table with millions of records.
I am able to paginate using the GetQueryResultsResponse.getPageToken() method. The getPageToken is returning null if the underlying BigQuery Table is getting new inserts. The pageToken works fine if there are no inserts happening.
How to avoid this and be able to traverse the table even when inserts are happening on the bigquery table?
I am using google-api-services-bigquery v2-rev330-1.22.0"

A: Not clear, but I think you are talking about tables.list pagination (query result cannot have records streaming into it)
In such cases  - instead of pageToken you can use startIndex (along with maxResults)
Knowing items count in response (real page size) you can always calculate starting Index for next page to request (without using pageToken).
Having some extra management around those start Index in your app - you can manage paging in both directions (Next and Prev).
And of course you can always manage navigation to :
First Page (startIndex = 1)
and
Last Page (startIndex = totalRows - expected page size) .
One more note: in case if table is under streaming (has streaming buffer at a time you do list) totalRows can be not available - in this case you can use extra call to Tables: get API and get numRows instead


text:
Q: kafka streams not fetching all records I have a java Kafka streams application that reads from a topic do some filtering and transformations and writing the data back to Kafka to a different topic.
I print the stream object on every step.
I noticed that if I send more than dozens of records to the input topic, some records are not consumed by my Kafka streams application.
when using kafka-console-consumer.sh to consume from the input topic, I do receive all records.
I'm running Kafka 1.0.0 with one broker and one partition topic.
Any idea why?
public static void main(String[] args) {
  final String bootstrapServers = System.getenv("KAFKA");
  final String inputTopic = System.getenv("INPUT_TOPIC");
  final String outputTopic = System.getenv("OUTPUT_TOPIC");
  final String gatewayTopic = System.getenv("GATEWAY_TOPIC");
  final Properties streamsConfiguration = new Properties();
  streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "PreProcess");
  streamsConfiguration.put(StreamsConfig.CLIENT_ID_CONFIG, "PreProcess-client");
  streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
  streamsConfiguration.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
  streamsConfiguration.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
  streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
  streamsConfiguration.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 300L);

  final StreamsBuilder builder = new StreamsBuilder();
  final KStream<String, String> textLines = builder.stream(inputTopic);
  textLines.print();
  StreamsTransformation streamsTransformation = new StreamsTransformation(builder);
  KTable<String,Gateway> gatewayKTable = builder.table(gatewayTopic, Consumed.with(Serdes.String(), SerdesUtils.getGatewaySerde()));
  KStream<String, Message> gatewayIdMessageKStream = streamsTransformation.getStringMessageKStream(textLines,gatewayKTable);
  gatewayIdMessageKStream.print();
  KStream<String, FlatSensor> keyFlatSensorKStream = streamsTransformation.transformToKeyFlatSensorKStream(gatewayIdMessageKStream);
  keyFlatSensorKStream.to(outputTopic, Produced.with(Serdes.String(), SerdesUtils.getFlatSensorSerde()));
  keyFlatSensorKStream.print();

  KafkaStreams streams = new KafkaStreams(builder.build(), streamsConfiguration);
  streams.cleanUp();
  streams.start();
  // Add shutdown hook to respond to SIGTERM and gracefully close Kafka Streams
  Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    streams.close();
  }));

}


text:
Q: is there a 2D dictionary in python? I was about to create a matrix like :
    33  12  23  42  11  32  43  22
33  −   1   1   1   0   0   1   1
12  1   −   1   1   0   0   1   1
23  1   1   −   1   1   1   0   0
42  1   1   1   −   1   1   0   0
11  0   0   1   1   −   1   1   1
32  0   0   1   1   1   −   1   1
43  1   1   0   0   1   1   −   1
22  1   1   0   0   1   1   1   −

I want to query by horizontal or vertical titles, so I created the matrix by:
a = np.matrix('99 33    12  23  42  11  32  43 22;33    99  1   1   1   0   0   1   1;12    1   99  1   1   0   0   1   1;23    1   1   99  1   1   1   0   0;42    1   1   1   99  1   1   0   0;11    0   0   1   1   99  1   1   1;32    0   0   1   1   1   99  1   1;43    1   1   0   0   1   1   99  1;22    1   1   0   0   1   1   1   99')

I want to have the certain data if I query a[23][11] = 1
so is there a way we can create a 2D dictionary, so that a[23][11] = 1?
Thanks

A: You're clearly asking for something outside of numpy.
A defauldict with the default_factory as dict gives a sense of the 2D dictionary you want:
>>> from collections import defaultdict
>>> a = defaultdict(dict)
>>> a[23][11] = 1
>>> a[23]
{11: 1}
>>> a[23][11]
1

A: Another possibility is to use tuples as the dictionary keys
dict((33,12):1, (23,12):1, ...]

scipy.sparse has a sparse matrix format that stores it's values in such a dictionary.  With your values such a matrix would represent a 50x50 matrix with mostly 0 values, and just 1's at these selected coordinates.
Keep in mind that the keys of a dictionary (ordinary at least) are not ordered
What are going to be doing with this data?  A dictionary, whether type or nested, is good for one kind of usage, but bad for others.  A matrix such as you sample is better for other things, like operations along rows or columns.  The dictionary format largely obscures that kind of ordered layout.

A: Are you looking for a dictionary with pairs as keys?
d = {}
d[33, 12] = 1
d[33, 23] = 1
# etc

Note that in python d[a, b] is just syntactic sugar for d[(a, b)]

A: If I understand correctly you just want to label your row/columns. To stay within the numpy array framework, a simple solution would be to create a mapping between the labels and the array order. I am also going to assume that it is OK to convert the labels into strings as they can be anything (though integers would also be fine).
l = {str(x) : ind for ind , x in enumerate((33,12,23,42,11,32,43,22))}
a = sp.linalg.circulant([99,1,1,1,0,0,1,1])
a[l['32'],l['23']]


text:
Q: saved token in login page and how to receive it on List page in flutter? I have two pages,

*

*Login page

*list page

Already saved token in login page, but how to receive it on list page inside Future?
Login page response
Future<Album> createAlbum(String employee_custom_id, String password) async {
    final response = await http.post(
      Uri.parse('https://portal-api.jomakhata.com/api/auth/login'),
      headers: <String, String>{
        'Content-Type': 'application/json',
      },
      body: jsonEncode(<String, String>{
        'employee_custom_id': employee_custom_id,
        'password': password,
      }),
    );

    final data = json.decode(response.body);

    if (response.statusCode == 200) {
     saveToken(data);
      log('$data');
      return Album.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Failed to create album.');
    }
  }
 //save token
  void saveToken(data) async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString("token", data['token']);
    sharedPreferences.setInt("userId", data['userId']);
  }

Now i want to received it on list page, but can't set it on token section
**List page **
    Future<List<ListAlbum>> listData() async {
      final token = // I want to receive token here that i saved in login page.
      String url =
          'https://portal-api.jomakhata.com/api/getOrganizationData?token=${token}';

      Dio dio = new Dio();
      dio.options.headers['Content-Type'] = 'application/json';
      final body = {'limit': 100, 'orderBy': 'idEmployee', 'orderType': 'DESC'};
      final response = await dio.post(url, data: body);
   }

A: If I understand correctly you are asking this
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final token = sharedPreferences.getString("token");

A: Wouldn't this make sense?
Future<List<ListAlbum>> listData() async {
      SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
      final token = sharedPreferences.getString("token");
      String url =
          'https://portal-api.jomakhata.com/api/getOrganizationData?token=${token}';

      Dio dio = new Dio();
      dio.options.headers['Content-Type'] = 'application/json';
      final body = {'limit': 100, 'orderBy': 'idEmployee', 'orderType': 'DESC'};
      final response = await dio.post(url, data: body);
   }


text:
Q: Passing an object member (as this.member) to a class method in javascript I'm trying to pass this.SOME_MEMBER to a method, but it doesn't go thru as that same member. The code below should make a little more sense at what I'm trying to get at.
function App()
{
    this.canvas = new Object();
}

App.prototype.createCanvas = function(obj, width, height)
{
    obj = document.createElement('canvas');
    obj.setAttribute('width', width);
    obj.setAttribute('height', height);

    log(obj == this.canvas); //false
    log(this.canvas == app.canvas); //true
                                    //it's clear that this refers to app

    //so why doesn't obj refers to this.canvas?
    //how do i get obj to equal this.canvas?
}

App.prototype.init = function()
{
    this.createCanvas(this.canvas, 800, 600);
    log(this.canvas.width); //undefined
}

var app = new App();
app.init();

Now, I understand that i can simply just do the following:
function App()
{
    this.canvas = new Object();
}

App.prototype.createCanvas = function(width, height)
{
    this.canvas = document.createElement('canvas');
    this.canvas.setAttribute('width', width);
    this.canvas.setAttribute('height', height);
}

App.prototype.init = function()
{
    this.createCanvas(800, 600);
    log(this.canvas.width); //800
}

var app = new App();
app.init();

This would work for most applications but I'm restricted to naming the variable as this.canvas. I'll eventually need the method to be a little more flexible that that.
Keep in mind, that I'm using the functions document.createElement and element.setAttribute as a mere example; they could be replaced with anything that modifies the variable obj.

So when "this.canvas" is being used as an argument, what happens to it? How would i achieve what I'm looking to do?
Thanks in advance!

A:
so why doesn't obj refers to this.canvas?

Because the first thing you've done in the function is give it a different value instead:
App.prototype.createCanvas = function(obj, width, height)
{
    obj = document.createElement('canvas');
//  ^------------------------------------------ here
    obj.setAttribute('width', width);
    obj.setAttribute('height', height);

    log(obj == this.canvas); //false
    log(this.canvas == app.canvas); //true
                                    //it's clear that this refers to app

    //so why doesn't obj refers to this.canvas?
    //how do i get obj to equal this.canvas?
}

JavaScript is a purely pass-by-value language. The obj argument has the value you passed in (which comes from this.canvas because that's what you gave when calling it); obj is not a reference to the this.canvas property. To do what you wanted to do in the way you wanted to do it would require passing this.canvas (the property) by reference, which you can't do in JavaScript. (But see below.)

Now, I understand that i can simply just do the following:
(code omitted)
This would work for most applications but I'm restricted to naming the variable as this.canvas. I'll eventually need the method to be a little more flexible that that.

That's a somewhat strange requirement (surely all App instances should have the canvas in canvas), but if you want to be able to tell createCanvas what property on the object to put the canvas on, you can do that:
JavaScript supports two ways of referencing object properties: Dotted notation using literals (this.canvas), and bracketed notation using strings (this["canvas"]). In the latter case, the string doesn't have to be a literal, it can be the result of any expession — including a variable reference.
So your createCanvas becomes:
App.prototype.createCanvas = function(propName, width, height)
{
    // Create the canvas
    var obj = document.createElement('canvas');
    obj.setAttribute('width', width);
    obj.setAttribute('height', height);

    // Save that canvas to the given property
    this[propName] = obj;
}

and you call it like this:
App.prototype.init = function()
{
    this.createCanvas("canvas", 800, 600);
}

That said, it would be rather more direct to just have createCanvas return the canvas so the calling code can put it wherever it wants:
App.prototype.createCanvas = function(width, height)
{
    // Create the canvas
    var obj = document.createElement('canvas');
    obj.setAttribute('width', width);
    obj.setAttribute('height', height);
    return obj;
}

then
App.prototype.init = function()
{
    this.canvas = this.createCanvas(800, 600);
}

Side note: You're missing semicolons, when you have x = ... it needs a ; at the end, even if the .. is a function expression. So for instance, the App.prototype.init = ... needs a ; at the end:
App.prototype.init = function()
{
    this.canvas = this.createCanvas(800, 600);
}; // <=== Here

It doesn't cause a syntax error because of the horror that is automatic semicolon insertion, but I'd strongly recommend not relying on it, the edge cases where it does the wrong thing will bite you when you least expect it (and can least afford it). Always including the correct semicolons saves time in the long run.

A: Your line,
obj = document.createElement('canvas');

overrides the obj variable passed into the createCanvas method, and sets it as a new object entirely. The variable allocation breaks the previous reference, and creates a new reference to the new object. The obj variable is a reference to another object. You can't use it to change the referenced object into being a competely different object.
If you act on the obj variable by calling methods or changing properties, those will all act on the original object. So, maybe pass the this object into the method instead (although this seems a little pointless unless you're planning to call the function in a different scope).


text:
Q: How can i align one div in to middle?

html,body {
  width : 100%;
  height : 100%;
  }

#side-bar{
  background-color:yellow;
  width:15%;
  height:100%;
  float:left;
}
#content{
  border:1px solid green;
  width:50%;
  height:6%;
}

Here is My code ,I'm trying to align the  #content part in to middle of side bar,I'm tried the following thinks.
#side-bar{ align-content : center; }

and then
#content{margin-left:auto;margin-right:auto;}

but both are not worked for Me,how can I do that?

A: The common way to center a div would be to use margin: 0 auto;. See this guide for centering with CSS.

html,
body {
  width: 100%;
  height: 100%;
}
#side-bar {
  background-color: yellow;
  width: 15%;
  height: 100%;
  float: left;
}
#content {
  border: 1px solid green;
  width: 50%;
  height: 6%;
  margin: 0 auto;
}

A: Only Using     margin: 0 auto; in #content

html,body {
  width : 100%;
  height : 100%;
  }

#side-bar{
  background-color:yellow;
  width:15%;
  height:100%;
  float:left;
}
#content{
  border:1px solid green;
  width:50%;
  height:6%;
  margin: 0 auto;
}

A: If you need ah center of #content apply margin:auto.
if need ah middle on on both vertical and horizontal apply with position:relative;top:47% also.If you no need just remove that

html,body {
  width : 100%;
  height : 100%;
  }

#side-bar{
  background-color:yellow;
  width:15%;
  height:100%;
  float:left;
}
#content{
  position:relative;/*for both vertical and horizontal center*/
  border:1px solid green;
  margin:auto;/*for center*/
  top:47%;/*for both vertical and horizontal center*/
  width:50%;
  height:6%;
}


text:
Q: npm install module from gitlab In node module package.json I have:
"repository" : {
"type":"git",
"url":"https://git.domainName.com/Mastash3ff/someprojectname.git"
},

Trying to install via npm.
Tried various commands like from https://docs.npmjs.com/cli/install:
npm install gitlab:git.domainName.com/Mastash3ff/someProjectName.git

also tried
npm install https://git.domainName.com/Mastash3ff/someProjectName.git
https:// install command hangs after enter is pressed.  npm install gitlab command spits out:
npm ERR! git clone --template=/home/Mastash3ff/.npm/_git-remotes/_templates --mirror git@gitlab.com:git.domainName.com/Mastash3ff%2FsomeProjectName.git /home/Mastash3ff/.npm/_git-remotes/git-gitlab-com-git-domainName-com-Mastash3ff-2FsomeProjectName-git-a88a1dff9012cf9dc7b0780cba303741: Cloning into bare repository '/home/Mastash3ff/.npm/_git-remotes/git-gitlab-com-git-domainName-com-Mastash3ff-2FsomeProjectName-git-a88a1dff9012cf9dc7b0780cba303741'...
npm ERR! git clone --template=/home/Mastash3ff/.npm/_git-remotes/_templates --mirror git@gitlab.com:git.domainName.com/Mastash3ff%2FsomeProjectName.git /home/Mastash3ff/.npm/_git-remotes/git-gitlab-com-git-domainName-com-Mastash3ff-2FsomeProjectName-git-a88a1dff9012cf9dc7b0780cba303741: Permission denied (publickey).
npm ERR! git clone --template=/home/Mastash3ff/.npm/_git-remotes/_templates --mirror git@gitlab.com:git.domainName.com/Mastash3ff%2FsomeProjectName.git /home/Mastash3ff/.npm/_git-remotes/git-gitlab-com-git-domainName-com-Mastash3ff-2FsomeProjectName-git-a88a1dff9012cf9dc7b0780cba303741: fatal: Could not read from remote repository.
.....

For gitlab, we don't have ssh auth setup so we only use https://.  Not sure why it would be asking for public key.  The way we git clone is by pointing it to cert file.  I also have my ~/.npmrc file pointing to:
  cafile=/home/Mastash3ff/git.someDomainName.com.cert

I'm out of ideas. I'm hoping this problem can be solved my pointing out incorrect npm install command usage :/

A: Check your access to the repo.

Permission denied (publickey)


text:
Q: IIS 7 throws 401 responses on application whose physical directory has been shared I have an IIS 7, Windows Server 2008 R2 box with a relatively fresh install.  I've deployed a .NET 2.0 application using windows autentication to the server, and from the default website, added it as an application.  I updated the IIS authentication to enable Windows Authentication.
When I went to share out the physical directory for the application so that a developer could deploy updates, the users began to receive 401 errors.  I can reliably recreate the issue by sharing out the directory of any newly created application.  The IIS user has the necessary read/write access to the directory.
What do I need to do to keep web users from receiving 401's while at the same time allowing this developer to have access to the physical directory for deployments?
Thanks in advance!


text:
Q: How to change only one value of a list from repl.it database? I'm trying to code a Discord game bot on repl.it and I use its database to store the players' data.
So I'm now making a command to let players rename themselves but then there is a problem. The following lines work but involve affecting a new value to the entire player_data list which stores the data of every player:
renamer = player_id.index(message.author.id)
new_name = message.content[len(prefix)+7:]
player_data = db["player_data"]
player_data[renamer][0] = new_name
db["player_data"] = player_data
await message.channel.send('You successfully renamed yourself into '+new_name+'.')

So I'm afraid that if someone starts playing while another is changing his nickname, the 'old' player_data will overwrite the new one, which has the new player's data.
I want something similar to these lines (which don't work) to only change the involved player's data:
renamer = player_id.index(message.author.id)
new_name = message.content[len(prefix)+7:]
db["player_data"][renamer][0] = new_name
await message.channel.send('You successfully renamed yourself into '+new_name+'.')

A: So since I can create many keys in the repl.it database, I decided to create a key for every player, and those lines work without having to get the other players' data :
new_name = message.content[len(prefix)+7:]
player_data = db["player_data"+str(message.author.id)]
player_data[0] = new_name
db["player_data"+str(message.author.id)] = player_data
await message.channel.send('You successfully renamed yourself into '+new_name+'.')

If anyone has a solution for the initial problem, I'm still interested.


text:
Q: Comparing all elements of two tuples (with all() functionality) So i know that comparisons on tuples work lexicographically:

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.
If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).

So from this:
>>> a = (100, 0)
>>> b = (50, 50)
>>> a > b
True

But i want to compare all elements of 2 tuples in order, so functionally i want something akin to (using values from above):
>>> a > b
(True, False) #returned tuple containing each comparison
>>> all(a > b)
False

As an example in practice, for something like screen coordinates, if you wanted to check if something was 'inside' the screen at (0,0), but done a comparison like coord > (0,0), if the x coord was bigger than 0, but the y coord was smaller it would still return true, which isn't what is needed in this case.
As sort of a sub question/discussion:
I am not sure why comparing 2 tuples of different values is returned in such a way. You are not given any sort of index, so the only thing you get from comparing a tuple (that isn't testing equality) is that at some point in the tuple, one of the comparisons will throw a true or false value when they are not equal. How could you take advantage of that?

A: You can achieve this with a list comprehension and the zip built-in:
>>> a = (100, 0)
>>> b = (50, 50)
>>> [(a > b) for a, b in zip(a,b)]
[True, False]

You can use all() or any() on the returned list.

A: Replace a > b with tuple(i > j for i, j in zip(a,b)) in your second code sample.
>>> a = (100, 0)
>>> b = (50, 50)
>>> tuple(i > j for i, j in zip(a,b))
(True, False)
>>> all(i > j for i, j in zip(a,b))
False

A: You might consider using the following vectorized approach, which is usually more performant, and syntactically/semantically very clear:
>>> import numpy
>>>
>>> a = (100, 0)
>>> b = (50, 50)
>>> numpy.array(a) > b
array([ True, False], dtype=bool)
>>>
>>> (numpy.array(a) > b).any()
True
>>> (numpy.array(a) > b).all()
False

*

*numpy is quite performant, and the resulting objects above also embed the any()/all() query methods you want. If you will be performing vector-like operations (as your screen coordinates example suggests), you may consider working with 'a' and 'b' as numpy arrays, instead of tuples. That results in the most efficient implementation of what you seek: no pre-conversion necessary, and Python-based loops are replaced with efficient numpy-based loops. This is worth highlighting because there are two and potentially three loops involved: (1) a preprocessing loop during conversion (which you can eliminate); (2) an item-by-item comparison loop; and (3) a query loop to answer the any/all question.

*Note that I could've also created a numpy array from 'b', but not doing so eliminated one conversion step and pre-processing time. Since that approach results in one operand being a numpy array and the other a tuple, as the sequences grow, that may/may-not result in less speedy item-by-item comparisons (which strict numpy-to-numpy is good at). Try it. :)

A: I felt like the use of map and lambda functions was missing from the answers
>>> a = (100, 0)
>>> b = (50, 50)
>>> all(map(lambda x,y: x > y, a, b))
False

A: To get the described behavior, try:
[ai > bi for ai,bi in zip(a,b)]

The reason that comparisons of tuples are returned in that way is that you might want to write something like:
if a >= (0.,0.):
    print "a has only positive values"
else:
    print "a has at least one negative value"

If Python were to return the tuple that you describe, then the else would never happen. Try
if (False,False):
    print "True!" # This is what is printed.
else:
    print "False!"

I hope this helps.


text:
Q: How to use isql COLUMN Format option I am getting syntax error when I used COLUMN Format in sybase isql
1> column FEEDNAME format "A30"
2> go
Incorrect syntax near format.
please advise.

A: COLUMN FORMAT setting is not available in Sybase


text:
Q: CSS and JQuery errors for hovering a dynamic element I want to creat a little menu, which gets positioned by hovering an element (will be shown between two elements). After that moving the mouse to the "X" will slideDown the menu, where some buttons are displayed. But the menu has some bugs for displaying and hovering. Also I don't like the code as I tried it. I think this could be done much more smarter...
Update: The behavior should be like this: If the cursor is on a .item, the menu should be displayed at the left corner - in the middle of two .item. The arrow should point to the space between these two .item. The menu just shows the "X"; the buttons are hidden. If the cursor points to the "X", then the buttons are shown (slideDown), so the user can click on these buttons. One problem for me is, that first (when just the "X" is shown) the width is just 25px. When displaying the buttons, the width changes, so the container has to expand to the left.
Please have a look here:
JSFiddle: http://jsfiddle.net/b1gpd1n1/1/
JS:
$(document).on('mouseenter', '.item', function( event ) {
    var left = $(this).offset().left - 50;
    $(".item_menu").css("left", left).css("top", $(this).offset().top - 15);
        $(".item_menu").hover(function() {
            var that = this;
            $(this).find('header').fadeOut(200);
            $(this).animate({'left': left-90, 'width': 120}, 200, function() {
                $(that).find('.buttons').slideDown(200);
            });

        }, function() {
            $(this).animate({'left': left, 'width': 25}, 200);
            $(this).find('header').fadeIn(200);
            $(this).find('.body').slideUp(400);
        });
});

HTML:

    X

<button>Example</button>

I would be very glad if you could have a look at the code to improve it.
My problems:

*

*Improve the arrow, which should be displayed at the right upper corner (with a little margin to the top)

*Is there a better HTML-construct for the menu?

*Hovering the menu makes some display-errors

A: After many updates, here I go:
$(function(){
    var time = 400;
    var item = $(".item_menu");

    var item_width_button = item.width();
    $(".buttons button").hide();
    var item_width = item.width();

    var item_padding = item.css("padding");
    var pos = $(".item:first").offset();

    item.css({
        "right": ($(document).width() - pos.left) + "px",
        "top": (pos.top + $(".arrow").height()) + "px",
        "width": "0"
    });

    var now;
    $(".wrap .item").on("mouseenter", function(){
        now = $(this);
        show_item();
    });
    $("header").on("mouseenter", function(){
        show_buttons();
    });
    item.on("mouseleave", function(){
        show_item();
    });

    function show_item () {
        $(".buttons button").stop().slideUp(time, function(){
            item.show().stop().animate({
                "top": now.offset().top + "px",
                "width": item_width + "px",
                "padding": item_padding
            }, time);
        });
        $(".arrow").fadeIn(time);
    }

    function show_buttons(){
        item.animate({
            "width": item_width_button + "px",
        }, time, function(){
            $(".buttons button").stop().slideDown(time);
        });
        $(".arrow").fadeOut(time);
    }

});


text:
Q: Adding to a WAV file in Python I want to add to a wav file, ideal would be from a numpy array. I tried the following code:
data = stream.read(CHUNK)
audio_numpy = numpy.frombuffer(data, dtype=numpy.int16)
scipy.io.wavfile.write(FILENAME, RATE, audio_numpy)

where stream is created by
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

as I heard that scipy would add to the file and not overwrite it. Unfortunately however, it overwrites the file.
How can I append to a WAV file? The input comes from the microphone.
The WAV file should be accessed from ffmpeg later, so that the WAV file should not be written in total again, as this is also inefficient.


text:
Q: Cannot use object of type PDOStatement I get this error when I try to put the id on button
Fatal error: Cannot use object of type PDOStatement as array...

The code where is the error is this
   $pdo = Database::connect();
   $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

   $q = "SELECT * FROM books where user = '".$_SESSION['level']."'";

   if($res = $pdo->query($q))
   {
         if($res->fetchColumn() > 0)
         {
                foreach($pdo->query($q) as $res)
                {
                        echo ' '.$res['name'].' ';
                }
         }
         else
         {
                echo 'Create Book';
         }
    }
    Database::disconnect();

What I trying is when user log if there is no books to show him button Create book. And the error is there in the else block where is users/bookAdd.php?user_id='. $res['user_id'] .' Any idea how to fix this?

A: The error is already clear, you can't try to access indices in context of a PDOStatement object.
You can't just use ->query(), and then try to access the values from the created object. You haven't fetch the results yet.
You need to fetch the results properly:
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prep the statement
$q = $pdo->prepare("SELECT * FROM books WHERE user = :level");
$q->bindParam(':level', $_SESSION['level']); // bind it
$q->execute();
// fetch the results
$results = $q->fetchAll(PDO::FETCH_ASSOC);
if(count($results) > 0) {
    foreach($results as $res) {
        echo ' '.$res['name'].' ';
    }
} else {
    echo 'Create Book';
}

Database::disconnect();


text:
Q: Div tag within img tag I need to add a text on each of the image and I have the image gallery constructed using img tags. Can't I append div tags under img tags. Similar to the one shown here :

HELLO1_1

Though the div is appended to img tag , but I cant see the text "HELLO1_1" on the image.
Please can anyone help me?
If you need the source code I can share it with you.
Here is the link to test the scenario :
http://jsfiddle.net/XUR5K/9/

A: An image tag can not have child elements. Instead, you need to position the DIV on top of the image using CSS.
Example:

Text

That's but one example. There's plenty of ways to do this.

A: The img element has a self closing tag, so you can't give it child elements and expect it to work. Its content model is defined as empty. Source.
I suspect any children you specify won't be rendered because an img element is a replaced element, as mentioned in the W3C spec.

A: Rules of good tone.

*

*Use null source in IMG tag.

*Use CSS content:"" for WebKit browsers.

*Insert element through JavaScript. Clear in HTML does not affect.
Also you can use pseudo elements.
Example: https://github.com/Alexei03a/canvas-img


text:
Q: bash profile works for user but not sudo I've modified my .profile to include a folder if a flash drive is plugged in. When running the command as the user it works fine but tells me the scrip must be run by sudo (this is what i want). However, when i try to run it with sudo i get "command not found"
I have a symlink (flash) in my /var/www folder pointing to my /media/flash drive. (nevermind this setup since is just for dev)
this is my user's .profile :
# set PATH so it includes flash scripts
if [ -d "/var/www/flash/scripts" ] ; then
    PATH="/var/www/flash/scripts:$PATH"
fi

when trying to run as sudo i get:
sudo: script: command not found

any ideas?

A: When you run the script as sudo you are trying to access root. So your $HOME/.profile wont be accessed instead /root/.profile will be accessed.
So make the changes what ever you did in $HOME/.profile to /root/.profile. To create /root/.profile. Use the following commands.
sudo su
cd /root
touch .profile

after making the changes try running the script.
or edit $HOME/.bashrc and add the following line
alias sudo='sudo env PATH=$PATH $@'

Hope this helps.

A: that is the behavior of sudo in ubuntu..
for example run following command
echo 'echo $PATH' | sh

and than this one
echo 'echo $PATH' | sudo sh

you see the output is different!
to avoid different paths put the following in your ~/.bashrc
alias sudo='sudo env PATH=$PATH'

A: You can preserve the value of $PATH when using sudo. Use visudo to add $PATH to the list of variables to keep. A line like the following in /etc/sudoers should do the trick:
Defaults env_keep += "PATH"

A: You can also move your file in a sudoers used directory :
    sudo mv $HOME/bash/script.sh /usr/sbin/


text:
Q: Change the hiera 5 environment layer hiera.yaml location Background
I am using puppet5 & hiera5 on a puppet master from separate git repos.
The code is deployed using r10k into their respective locations using the branch to environment directory mapping.
Due to the environment conflict limitation in r10k (apologies if this is no longer the case) I use a separate location for my hieradata:
Puppet code - /etc/puppetlabs/code/envirnments/
Hiera code - /etc/puppetlabs/code/hieradata/
I have a global hiera.yaml file in /etc/puppetlabs/puppet/hiera.yaml and an environment specific hiera.yaml file in my hiera branch / environment location.
e.g. /etc/puppetlabs/code/hieradata/production/hiera.yaml
Problem
My environment hiera.yaml is ignored due to its location, it is expected to be where my puppet <ENVIRONMENT> code is:
/etc/puppetlabs/code/environments/production/hiera.yaml
taken from https://docs.puppet.com/puppet/5.0/hiera_config_yaml_5.html#location
but instead it is:
/etc/puppetlabs/code/hieradata/production/hiera.yaml
Solution
The only solution that I have been able to find is to locate a hiera.yaml in my puppet code repo with a datadir set to
datadir: ../../hieradata/%{::environment}/hieradata
(it must be relative)
Which works ok but is not ideal so I am looking for other solutions.
Even if I set the global hiera.yaml datadir to:
/etc/puppetlabs/code/hieradata/%{::environment}/
(it can be a full path)
and do not have a hiera.yaml file in my puppet repo, hiera works, but the environmental hiera.yaml located there is ignored.
Another idea was to swap the locations but then my puppet code does not work.
So ideally what I need to do is set the environment layer hier.yaml location as it seems to be hard coded to <ENVIRONMENT>, which is where my puppet code is.
I still want to use r10k and I want to host my environmental hiera.yaml in my hiera repo.

A: my working code:
datadir: "/etc/puppetlabs/code/environments/%{environment}/hiera"

but path should be correct.


text:
Q: How can I hide the hash route in Angularjs I would like to keep the integrity of the hash like for breadcrumbs and such but i just don't want to display the hash in the route. Is there any way to keep the hash in the background but hide it in the URL? I have done some research on this already and I have found some answers that all get rid of the hash completely. Any help would be appreciated. Thank you.

A: angular.module('scotchy', [])

.config(function($routeProvider, $locationProvider) {

    $routeProvider
        .when('/', {
            templateUrl : 'partials/home.html',
            controller : mainController
        })
        .when('/about', {
            templateUrl : 'partials/about.html',
            controller : mainController
        })
        .when('/contact', {
            templateUrl : 'partials/contact.html',
            controller : mainController
        });

    // use the HTML5 History API
    $locationProvider.html5Mode(true);
});

Read this blog, it should have every thing you need to know. Pretty URLs


text:
Q: LSZ formula applied to two-point correlation function I was trying to find the scattering amplitude using the LSZ formula for a trivial process i.e. applying it to the two-point correlation function, but I kept getting 0 as the answer.
I'm not sure exactly if this is correct or not, and, if it is, how to interpret why $\langle p_f | p_i \rangle = 0$ physically.

A: The $S$-matrix is often split into a trivial identity part, plus a non-trivial $T$-matrix called the "transfer matrix", for this exact reason.
$$S=1+iT$$
Furthermore, when calculating scattering amplitudes we can factor out a general momentum-conserving delta-function from $T$:
$$T=(2\pi )^4 \delta^4\left(\sum p^\mu_f - \sum p^\mu_i\right) \mathcal{M}$$
The whole framework of calculating scattering amplitudes using Feynman rules and LSZ is for calculating $i\mathcal M$. One must keep in mind how $\mathcal M$ and $S$ are related when calculating cross sections or decay rates, which directly involve $S$.
For more you may check out chapter 5 of Schwartz.


text:
Q: Can't escape spaces in variable name I trying to deal with spaces in directory names. As an example:
drive=/mnt/g; export drive
mydir="$drive/directory with spaces in name"
echo "$mydir"

The result:
/mnt/g/directory with spaces in name

Which of course, blows up on use, as bash sees this as separate arguments. The desired result would be something like:
"/mnt/g/directory with spaces in name"

as a single argument for subsequent processing (moves, copies, or whatever).  I had thought that a double quote does the trick. Obviously not. Bash keeps eating the double quotes. Can someone point me to the proper procedure for handling variables with embedded spaces?
I'm using the Windows subsystem for Linux in Windows 10, but Ubuntu 20.04 LTS has the same behavior, so I'm assuming what works for one, will work for both.  (Something with ILS maybe, IDK.)

A: Your code is fine! You have spaces in variable that why will be spaces out of echo as well.
So if you want to use a parameter that contains spaces you have to put between quotes like you do.
example:
command "${variable1}" "${variable2}"

A: If the desired output is
"/mnt/g/directory with spaces in name"
the code you need is
drive=/mnt/g; export drive
mydir="\"$drive/directory with spaces in name\""
echo "$mydir"


text:
Q: Wait for canvas.toBlob() before continue I want to upload a cropped image with jquery ajax. Therefore I create a blob out of the canvas element to append it to the form data. This works fine so far but I have some sync/async problems I guess. I searched the web for javascript callbacks but I'm not sure if this is the correct thing in general here. The problem is that

return formData;

will be executed before the blob is added to the form data. I think there is an easy solution to solve my problem but I can't get it done, maybe you can help me.
$.ajax({
    url: this.$upload.data('url'),
    method: 'POST',
    contentType: false,
    processData: false,
    cache: false,
    data: (function(_this) {
        var formData = new FormData();
        _this.getCroppedImage().toBlob(
            function(blob) {
                formData.append('file', blob, _this.file.name);
            },
            _this.file.type
       );
       $.each(_this.$element.data(), function(key, value) {
           formData.append(key, value);
       });
       return formData;
    })(this)
});

Maybe it's important to know: I also use https://github.com/blueimp/JavaScript-Canvas-to-Blob to have the toBlob method available to all browsers.

A: To accomplish this you're going to want to look into promise objects, a good library for this is q.js
Basically you create a function that will build your form data, and then you wait for the form data to be completed, when the promise resolves it will pass the form data into your ajax function via the "then" callback. Then your ajax call will be run
function ajaxFn(){
    //result is your formData in this case
    getFormData().then(function(result){
        //this won't run until the promise resolves, aka formData is complete
        $.ajax({
            url: this.$upload.data('url'),
            method: 'POST',
            contentType: false,
            processData: false,
            cache: false,
            data: result
        });
    });

}

function getFormData(){
    var deferred = Q.defer();

    var formData = new FormData();

    $.each(_this.$element.data(), function(key, value) {
       formData.append(key, value);
    });

    _this.getCroppedImage().toBlob(
        function(blob) {
            formData.append('file', blob, _this.file.name);

            //this is what will get passed into your then function above
            deferred.resolve(formData);
        },
        _this.file.type
   );

    return deferred.promise;
}


text:
Q: C# Windows application- How to span tag value show in textbox1? Actually I am want to span the data value show in my textbox1.Text area.
This is full code.
Security code: 7201

This is the received code
7201

I have  checked many sources for a solution but I failed to find a solution so I am waiting anyone good reply.
I want to know how to span value shown in textbox1.Text area.
I also tried the code below but that doesn't work.
HtmlElementCollection bColl = webBrowser3.Document.GetElementsByTagName("span");
foreach (HtmlElement bEl in bColl)
{
    if (bEl.GetAttribute("style").Contains("font-family:'Segoe UI Bold'"))
        txtlink.Text = bEl.OuterHtml;
}

A: Try this RegEx:
.*?(.*?)<\/span><\/td>

The data you want is stored in the 1st Capture Group
Live Demo on Regex101
How it works:
          # Opening  with attributes
.*?                # Optional Data - i.e. Security Code: (Lazy)
        # Opening  with attributes
(.*?)              # The data you need to Capture - i.e. 7201
<\/span>           # Closing
<\/td>             # Closing