text:
Q: read pem file, get 63 bytes in DQ parameter I have a function that need RSA encryption/decryption. With provided .pem file, that contains pair key for RSA. By using Org.BouncyCastle as same as How to read a PEM RSA private key from .NET; or using the method in http://www.jensign.com/opensslkey/opensslkey.cs. What i received is "bad data" with parameter DQ has 63 byte (different from 64 byte). (the .pem file is said that been fine.) Is there any problem here?

A: All RSA parameters are simply (huge) numbers. Most of them will have identical sizes (for the same key pair length, e.g. 1024) but this is not always the case - and you need to cover this in your code.
Why ? because some numbers will be a bit smaller and will fit in less bits than others. In your case the number fits in 63 bytes, so it's base64 (PEM) encoded as such.
The solution is to pad the data you're reading, i.e. add a 0x00 byte before the 63 you're decoding. This will still be the same numbers (math wise) and it will pass all .NET validations for the RSA key parameters.
p.s. you can look at Mono source code to see how this is handled.


text:
Q: How to traverse a nested key value pair object in JUEL(Java Unified Expression Language) & return a certain index to evaluate against? I have an object with duplicate key value pairs. I need to traverse it & evaluate index [0] only against a condition:
var cells = {"cells": [{"key": "-18", "key1": "-9", "key2": "-51", "key3": "23"}, {"key":
"-18", "key1": "-9", "key2": "-51", "key3": "23"}, {"key": "-18", "key1": "-9", "key2": "-51",
"key3": "23"}]};

My code so far:
var result = true;

if (cells instanceof java.util.List && !cells.isEmpty()) {
 for (var i = 0; i < cells.size(); i++) {
    var cell = cells.get(i);

    var key = cell.get("key");
    var primeKey = key.get[0];
    if (primeKey) {
        if (parseInt(primeKey) < 5) {
            result = false;
            break;
        }
    } else {
        result = false;
        break;
    }
}
} else {
result = false;
}

return result;

The error that I get is:
Error encountered during evaluation: TypeError: Cannot read property "0.0" from undefined
(#12)

A: var primeKey = key.get[0]; is nonsensical as the "key" value pair is not an array to be iterated. However, if we simply change the i iterator to index 0 like so  var cell = cells.get(0); we can evaluate the condition against index 0 only. No need to traverse the entire nested loop as we are only comparing against index 0. See below for details:
var cells = {"cells": [{"key": "-18", "key1": "-9", "key2": "-51", "key3": "23"}, {"key":
"-18", "key1": "-9", "key2": "-51", "key3": "23"}, {"key": "-18", "key1": "-9", "key2": "-51",
"key3": "23"}]};

var result = true;

if (cells instanceof java.util.List && !cells.isEmpty()) {
 for (var i = 0; i < cells.size(); i++) {
    var cell = cells.get(0);

    var key = cell.get("key");
    if (primeKey) {
        if (parseInt(primeKey) < 5) {
            result = false;
            break;
        }
    } else {
        result = false;
        break;
    }
}
} else {
result = false;
}

return result;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need Help: Apex batch Class I'm still trying to figure out how batch work.  My error is SYSTEM_METHOD_ENTRY [9]|Database.getQueryLocator(String).
This is what I have so far.  I'm trying to upsert a list of records using apex batch.  Your help is appreciated.
Combine__c is the external ID field.
My Batch Class:
global class batchUpsertRecords implements Database.Batchable<sObject> {
    global final String query;

    global batchUpsertRecords(Business__c[] busRec) {
       Business__c[] query = busRec;
    }

    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }

    global void execute( Database.BatchableContext BC, Business__c[] scope){

        database.Upsert(Scope,business__c.Combine__c,false);
        Upsert scope;

    }

    global void finish(Database.BatchableContext BC){
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
                            FROM AsyncApexJob WHERE Id = :BC.getJobId()]
    }

My Schedulable Class:
global class SFParAccelIntegration1 implements Schedulable{

    global void execute(SchedulableContext ctx)
    {
        SFParAccelIntegration1.combineIdBusiness();

    }

    public Static Void combineIdBusiness(){
        //Match CombineID to Account records and populate fields in Business object Salesforce section
        List<Business__c> businesses = new List<Business__c>();
        Set<string> combineIds = new Set<string>();

        for(Business__c bus : [Select Combine__c from Business__c limit 50000]) {
            combineIds.add(bus.Combine__c);
        }

        Business__c[] busRec = New Business__c[]{};

        //Get Account Data and Assign Values to Business
        For(Account a: [SELECT ID, Combine__c,Name,Total_Seat_Count__c,                 Number_of_FTE__c FROM Account WHERE Combine__c IN :combineIds]){
            busRec.add(New Business__c(Combine__c = a.Combine__c,
             acctId__c = a.ID, SF_Total_Seat_Count__c = a.Total_Seat_Count__c,
             SF_Number_of_FTE__c = a.Number_of_FTE__c));

        }

        //system.debug(busRec);
        System.debug('combineIdBusiness1 Records Count - ' + busRec.size());

        //String query = 'SELECT Id,CreatedDate FROM Merchandise__c ';
        batchUpsertRecords c = new batchUpsertRecords(busRec);
        Database.executeBatch(c);

    }

}

A: Your issue is that your're not storing the array passed in to the constructor into the member variable you're using in the start method:
// member variable is a String which is not what you want
global final String query;

global batchUpsertRecords(Business__c[] busRec) {

    // this creates a new local variable called query which exists on the stack
    // and is removed when this constructor finishes
    Business__c[] query = busRec;
}

global Database.QueryLocator start(Database.BatchableContext BC){

    // this is referencing the String member variable, which is still null
    return Database.getQueryLocator(query);
}

You'll need to run the query to select records inside of the Start method, so what you can do is change your code so that you pass in a set of Ids, and use that in the query:
// doesn't need to be visible outside of the batch class
private Set<Id> records;

global batchUpsertRecords(Set<Id> records) {
   this.records = records;
}

global Database.QueryLocator start(Database.BatchableContext BC){
    return Database.getQueryLocator([select Id, Etc__c from Object__c
                                     where Id in : records]);
}


text:
Q: Unable to get mypy to accept code which works correctly; generics appear to be the problem The following program is self-documenting. It gives the correct results, but it fails typechecking with mypy --strict.
Maybe there's a bug in mypy. More likely, my type annotations are incorrect. Any ideas?
"""
This code shows a technique for creating user-defined infix operators.

The technique is not my invention. However, I would like to have an implementation that:
a) I understand
b) type-checks with mypy --strict.

This code allows any two-argument function to be called as an operator, using the syntax:
    leftArgument <<functionName>> rightArgument
... for the avoidance of doubt, << and >> are literally present in the code.
"""

from typing import Callable, Generic, TypeVar

T = TypeVar("T")
U = TypeVar("U")
V = TypeVar("V")

class WithLeft(Generic[T, U, V]):
    def __init__(self, func, left: T) -> None:
        self.func = func
        self.left = left
    def __rshift__(self, right: U) -> V:
        return self.func(self.left, right)
class WithRight(Generic[T, U, V]):
    def __init__(self, func, right: U) -> None:
        self.func = func
        self.right = right
    def __rlshift__(self, left: T) -> V:
        return self.func(left, self.right)
class Op(Generic[T, U, V]):
    def __init__(self, func) -> None:
        self.func = func
    def __rlshift__(self, left: T) -> WithLeft[T, U, V]:
        return WithLeft(self.func, left)
    def __rshift__(self, right: U) -> WithRight[T, U, V]:
        return WithRight(self.func, right)

if __name__ == "__main__":

    print("Define the operator <<add>>, which adds two ints.")
    @Op
    def add(a: int, b: int) -> int:
        return a + b
    print("Demonstrate that it works.")
    print(f"{12 <<add>> 44} correctly prints {12 + 44}")
    print('Previous line gives error from mypy:')
    print('\tUnsupported operand types for << ("int" and "Op[<nothing>, <nothing>, <nothing>]")')
    print()
    print("Define the operator <<compose>>, which composes two functions.")
    P = TypeVar("P")
    Q = TypeVar("Q")
    R = TypeVar("R")
    @Op
    def compose(left: Callable[[Q], P], right: Callable[[R], Q]) -> Callable[[R], P]:
        return lambda x: left(right(x))
    print("Demonstrate that it works.")
    from math import (
        cos, # angle in radians, not degrees
        log # base e, not base 10
    )
    logcos: Callable[[float], float] = log <<compose>> cos
    print('Previous line gives two errors from mypy:')
    print('\tUnsupported operand types for << ("Callable[[SupportsFloat, SupportsFloat], float]" and "Op[<nothing>, <nothing>, <nothing>]")')
    print('\tUnsupported operand types for >> ("WithLeft[<nothing>, <nothing>, <nothing>]" and "Callable[[SupportsFloat], float]")')
    print()
    print(f"{logcos(1)} correctly prints {log(cos(1))}")

Stackoverflow doesn't like this post because it is mostly code.
So I'll repeat the explanation from the code. No need to read this again!
This code shows a technique for creating user-defined infix operators.
The technique is not my invention. However, I would like to have an implementation that:
a) I understand
b) type-checks with mypy --strict.
This code allows any two-argument function to be called as an operator, using the syntax:
leftArgument <> rightArgument
... for the avoidance of doubt, << and >> are literally present in the code.


text:
Q: Tizen Studio "repository configutation cannot be downloaded" I'm trying to install the Samsung TV extension packages in Tizen Package Manager. When I go to the "Extension SDK" page I should see the tools to download but nothing is there. When I check in settings I see that the package repo url isn't working:
http://download.tizen.org/sdk/tizenstudio
"The repository configutation cannot be downloaded"
What can I do? I tried installing the package manually but  I just get "Installation failed" :S

A: I can download tv extension.

*

*I downloaded TizenStudio 4.5.1 version from https://developer.tizen.org/

*I used https://download.tizen.org/sdk/tizenstudio URL on the package-manger instead of http://download.tizen.org/sdk/tizenstudio

*I installed tv extension


text:
Q: Android bluetooth scan, connection performance vary from phone type I'm implementing a bluetooth client to connect to a bluetooth server module.
It worked good in my LG G3(M) but I figured out that it doesn't work as expected on Samsung devices. The Galaxy S7(M), despite using the same version of android, fails to scan devices, and the connection is very unstable.
For now, I think the performance of the bluetooth code depends hardly on the maker or the hardware I'm testing on. Am I clear about this? If not, how can I make the performance uniform in all devices?

A: You may need to run on the UIThread using a Runnable and a Handler.
Runnable connectSamsung = new Runnable() {
    public void run() {
        mBluetoothGatt = device.connectGatt(mContext, false,
                                            mGattCallback);
    }
};

mHandler.post(connectSamsung);

See this question:
GATT callback fails to register


text:
Q: Getting autoincremented Id from JDBC Facing some exception without any clue message.
Here is my JDBC
            statement = con
                    .getConnection()
                    .prepareStatement(
                            "insert into  p3triplets set source_material= ? , process= ? ,target_material= ? , user_id = ?",
                            statement.RETURN_GENERATED_KEYS);
            statement.setString(1, pTriplet.getSource_Name());
            statement.setString(2, pTriplet.getProcessName());
            statement.setString(3, pTriplet.getTargetName());
            statement.setLong(4, user.getId());
            int i = statement.executeUpdate();
            generatedKeys=statement.getGeneratedKeys();
            long genId = generatedKeys.getLong(1);  //Exception
            for (p3TripleChild p3childTriple : childsDummyList) {
                if (p3childTriple.getId() == 0) {
                    p3childTriple.setId(genId);
                }
            }

And the exception is
java.sql.SQLException
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
    at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:815)
    at com.mysql.jdbc.ResultSetImpl.getLong(ResultSetImpl.java:2835)
    at com.mysql.jdbc.ResultSetImpl.getLong(ResultSetImpl.java:2830)
    at com.mtc.server.TripleServiceImpl.saveTriplet(TripleServiceImpl.java:161)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
    at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:324)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)

What I am missing ?
Id generated in database, but unable to get it back.

A: Your exception is occurring not when you call getGeneratedKeys(), but when you call getLong(1).  It is occurring because getGeneratedKeys return a ResultSet, and like any ResultSet, you need to call generatedKeys.next() to point to a row of the ResultSet before accessing data.  That is why the exception is generated by the driver's internal checkRowPos method.

A: long genId = 0;
ResultSet keys = stmt.getGeneratedKeys();
if (keys.next()) {
    genId = keys.getLong(1);
}

JDBC returns a ResultSet as you could have inserted several records.
And then you could have several generated keys per record.
So in the circumstantial tradition of JDBC, you need two steps further.


text:
Q: How can I print the sum to the screen in assembly in this code? How can i write the output to the screen?
 SECTION .data
 x:
   dd 1
   dd 5
   dd 2
   dd 18
 sum:
   dd 0
 SECTION .text
  mov eax,4 ; EAX will serve as a counter
  mov ebx,0 ; EBX will store the sum
  mov ecx, x ; ECX will point to the current
 top:
  add ebx, [ecx]
  add ecx,4 ; move pointer to next element
  dec eax ; decrement counter
  jnz top ; if counter not 0, then loop again
 done:
  mov [sum],ebx ; done, store result in "sum"


text:
Q: How to make a controller accept post data from the body as well as URL in MVC 6 ASP.NET 5 Currently I am trying to write a controller in MVC 6 that is capable of accepting data from a post request. The issue is that depending on the client (which is not always a web browser), the data can come in as either key value pairs in the request URL, or as JSON in the request body.
Currently this method works for accepting the data from the URL:
[HttpPost]
public async Task<CaptureResponse> CaptureData(CaptureInfo capture) {
    ...
}

After a lot of trial and error (and stack overflow answers), I figured out that the [FromBody] attribute tells the model binder to look in the request body, which is required now because MVC 6 combines WebApi and standard MVC together. The following code parses data from JSON in the form body:
[HttpPost]
public async Task<CaptureResponse> CaptureData([FromBody] CaptureInfo capture) {
   ...
}

For simplicity, I would like to combine the two together somehow, so the model binder gives me the data in the same parameter variable. So far, the only way I can get the data into the same Action is to specify two parameters, one for the URL and one for the body, and do some null checking on each like so:
[HttpPost]
public async Task<CaptureResponse> CaptureData(CaptureInfo capture, [FromBody] CaptureInfo bodyCapture) {
    if (bodyCapture != null) {
        if (bodyCapture.RequiredProperty1!= null
        && bodyCapture.RequiredProperty2!= null) {
            capture = bodyCapture;
        }
    }
    ...
}

I have tried specifying multiple properties before the input attribute like this:
[HttpPost]
public async Task<CaptureResponse> CaptureData(CaptureInfo [FromQuery][FromRoute][FromForm][FromBody] capture) {
    ...
}

But it does not work. Any ideas if something like this is possible?

A: As far as I know, it is just not possible. Of course you can try using workarounds, basically doing all request parsing yourself. It doesn't sound good, does it?
If you really want the things your way, I believe the best approach is to have two distinct endpoints in the controller and the private method for actual processing. Or, perhaps, even extract that method into an additional abstraction layer with BlaBlaService (CaptureService in your case, probably) class(es) responsible for all the dirty work. Sometimes it makes sense to separate your controllers layer from business logic - for example, for testing purposes.
PS: Your idea is quite similar to what was the approach in good old .NET & PHP times, and believe me, this particular idea is not the one that made those times good. You know, the MVC is much about the REST-like approach, so each endpoint of your controller is supposed to be dedicated to its own single function and obey to a single and uniform "intuitive" protocol.
The "intuitive" way to submit data to POST request for developers acquainted with REST is through the request body. I suggest you to consider going with this approach as the only one.

A: You need use Request.Form
like:
   string username = HttpContext.Current.Request.Form.GetValues("key1")[0].ToString();
    string password = HttpContext.Current.Request.Form.GetValues("key2")[0].ToString();
    string something = HttpContext.Current.Request.Form.GetValues("key3")[0].ToString();


text:
Q: How to remove parameters in a url string I have a string that looks like this, like a URL that has parameters.
folder/tested/file.js?p1=v1&p2=v2

How can I manipulate this string so as to remove all params, so that it ends up looking like this
folder/tested/file.js

A: Check out parse_url() - http://php.net/function.parse-url
$path = parse_url($url, PHP_URL_PATH);

A: $array = explode("?", "folder/tested/file.js?p1=v1&p2=v2");
$array[0];

A: There's no need for the explode workaround in this case:
$path = strtok($url, "?");

A: Here is another method that is somewhat 'dirty':
$tmp = 'folder/tested/file.js?p1=v1&p2=v2';
$pos = strpos($tmp, '?');
$url = substr($tmp, 0, $pos);

A: Try splitting by a '/' then by a '?' into two parts, and just taking what you need from both operations:
http://php.net/function.explode


text:
Q: Please help debug C program Write a C program that prompts a user to input

*

*month

*day

*year

*student ID

*name

*birthday

Run the program and store the data entered in a doc file which named by student number.
Tip: use structure.
Problem: The program stops running after the output of month, date and year
#include <stdio.h>
#include<string.h>
struct StudentData {
    char name[50];
    int id;
    int birth;
    char location[20];
}student;

int main() {
FILE * fPtr;
  fPtr = fopen("data/file1.txt", "w");

    int month, day, year;
    strcpy(student.name,"Krystal");
    strcpy(student.location,"Peru");
    student.id=546738293;
    student.birth=150491;
    printf("Enter the № of month:\n");
    scanf("%d",&month);
    printf("Enter the day: ");
    scanf("%d",&day);
    printf("Enter the year: ");
    scanf("%d\n",&year);

    printf("The current date is: year-%d, month-%d, day-%d\n",year, month,day);
    printf("Student`s name is %s\n",student.name);
    printf("Student`s ID is %d\n",student.id);
    printf("Student`s birthday:%d\n",student.birth);
    printf("Student`s location is %s\n",student.location);

    return 0;
}

A: You have to print output to a file using fprintf. Remove the \n character in last scanf statement. In fopen statement remove the folder name. Automatically output file will get stored in your current code directory.
PFA code.
#include <stdio.h>
#include<string.h>
struct StudentData {
    char name[50];
    int id;
    int birth;
    char location[20];
}student;

int main() {
FILE * fptr;
  fptr = fopen("file1.txt", "w");

    int month, day, year;
    strcpy(student.name,"Krystal");
    strcpy(student.location,"Peru");
    student.id=7862393;
    student.birth=150491;
    printf("Enter the № of month:\n");
    scanf("%d",&month);
    printf("Enter the day: ");
    scanf("%d",&day);
    printf("Enter the year: ");
    scanf("%d",&year);

    fprintf(fptr,"The current date is: year-%d, month-%d, day-%d\n",year, month,day);
    fprintf(fptr,"Student`s name is %s\n",student.name);
    fprintf(fptr,"Student`s ID is %d\n",student.id);
    fprintf(fptr,"Student`s birthday:%d\n",student.birth);
    fprintf(fptr,"Student`s location is %s\n",student.location);

    fclose(fptr);

    return 0;
}

A: I think you mean that the program seems to stop after the input (not output) of the year value.
This is because of the trailing newline in the scanf call:
scanf("%d\n",&year);

This will cause scanf to read and ignore any trailing space. But to know when the spaces ends, there must be some non-space input, which you do not input (I guess).
The solution is simple: Never use trailing space characters (and newline is a space character) in a scanf format string:
scanf("%d", &year);  // Note lack of newline at the end of the string


text:
Q: In hibernate, wrong value used as parameter for fetching set I have to hibernate entities and tables with a one to many relationship.  One is a user and the other is a car object.  I believe where the discrepancy is, is that I am attempting to join on field other than the primary key of the parent table and foreign key of the child.
For example, my tables look like so:
CREATE TABLE `User` (
  `userId` int(32) NOT NULL,
  `serial` varchar(32) NOT NULL,
  PRIMARY KEY (`userId`) USING BTREE,
  UNIQUE KEY `serial` (`serial`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 CREATE TABLE `Car` (
      `carId` int(32) NOT NULL,
      `serial` varchar(32) NOT NULL,
      PRIMARY KEY (`carId`) USING BTREE,
      KEY `FK_USER_serial` (`serial`),
      CONSTRAINT `FK_USER_serial` FOREIGN KEY (`serial`) REFERENCES `User` (`serial`) ON DELETE CASCADE ON UPDATE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

My mappings like so:
The User Mapping:
<hibernate-mapping>
    <class name="User" table="User">
        <id name="userId" type="int">
            <generator class="native" />
        </id>
        <property name="serial" type="string"></property>
          <set name="cars" table="Car"
                inverse="true" lazy="true" fetch="select">
            <key>
                <column name="serial" not-null="true" />
            </key>
            <one-to-many class="Car" />
        </set>
    </class>
</hibernate-mapping>

The Car Mapping:
<hibernate-mapping>
    <class name="Car" table="Car">
        <id name="id" type="int">
            <generator class="native" />
        </id>
        <property name="serial" type="string"></property>
    </class>
</hibernate-mapping>

The values I have in those tables are as follows:
User:
userId=172
serial=1
Car:
carId=159
serial=1
carId=160
serial=1
I enabled trace level logging in log4j and discovered that the hibernate is trying to retrieve the cars by the "serial" field but is using the "userId" in the where clause of 172 as opposed to the 1 which would actually bring back children.
What can I change in either my table or in my mapping to have hibernate use the serial foreign key and not the userId which the Car table doesn't even have.

A: JB Nizet's comment is the right solution.  I changed the primary key to serial.  It was already the unique index and is better suited to be the primary key.


text:
Q: Is there any reason a domain would fail to resolve other then the DNS server being the issue? I've got a site I'm having monitored by pingdom and another service, and both have reported outages. One report specifies the IP address could not be resolved -- however, our DNS is handled by theplanet's DNS servers (ns1.theplanet.com, ns2.theplanet.com) and I can only imagine they have tens of thousands of domains -- I can't imagine this woudl be going on for weeks without it being fixed.
Is there something that could cause the IP address to not resolve other then the DNS servers?

A: If the problem is failure to resolve, then it pretty much has to be a problem with the DNS servers or configuration.  It's possible, albeit unlikely, that Pingdom and the unnamed other service have broken caching resolvers.  It's also possible, ableit unlikely, that theplanet has broken DNS servers.
It seems more likely that the DNS zone for your domain might be mis-configured, resulting in random failures.  Lame delegation from the GTLD servers, for example, can result in intermittent failure.  If you post the actual domain, we could tell you quite a bit more.
Some things to check:
dig ns example.com @f.root-servers.net

This will return a list of additional DNS servers that have been delegated to handle DNS for your TLD.  Pick one and send the same query to it.  For example:
dig ns example.com @f.gtld-servers.net

This should return a list of the servers that handle the DNS for your actual domain.  Hopefully it will be ns1.theplanet.com and ns2.theplanet.com.
Next, move on to sending an A request to each of the listed servers:
dig a example.com @ns1.theplanet.com
dig a example.com @ns2.theplanet.com

(Assuming that the GTLD server listed those servers.)
They should both return the same results, differing only in minor details like TTL.


text:
Q: Getting 438 error while entering data on textbox on IE. This text box is on another TAB I am doing some automation on IE browser. On this i am logging into the web application and after logging when i am clicking on botton the web opens a new tab where i need to enter the data onto the textbox but here i am getting an error 438. below is my code. please help me out. i highlighted the line in bold where i am getting an error. The last one i am clicking on end tab and i am getting an error on that
Sub upload()
Dim myValue As Variant
Dim IETab1Number As Integer
Dim IETab2Number  As Integer
Dim IETab3Number As Integer
' open IE, navigate to the desired page and loop until fully loaded
    Set IE = CreateObject("InternetExplorer.Application")
    my_url = "http://englogin.sbc.com/ELP/"
    With IE
        .Visible = True
        .Navigate my_url
        .Top = 50
        .Left = 530
        .Height = 400
        .Width = 400
    Do Until Not IE.Busy And IE.readyState = 4
        DoEvents
    Loop
    End With
    ' Input the userid and password
    IE.document.getElementById("GloATTUID").Value = "Zf9775"
    IE.document.getElementById("GloPassword").Value = "MrsCooper$99"
    ' Click the "Login" button
    IE.document.getElementById("GloPasswordSubmit").Click
    Do Until Not IE.Busy And IE.readyState = 4
        DoEvents
    Loop
     ' Click the "Continue" button
     IE.document.getElementById("successButtonId").Click
    Do Until Not IE.Busy And IE.readyState = 4
        DoEvents
    Loop
    ' Click the "MIC" button
    IE.document.getElementById("btnMechanizedInventoryCreation").Click
    Do Until Not IE.Busy And IE.readyState = 4
        DoEvents
    Loop

    Set html = IE.document
    html.querySelector("a[href='#MIC']").Click
    IE.document.querySelector("[name=telco11iProjectNumber]").Value = "123456"
    ' Enter JOB Number" button
    'myValue = InputBox("Give me some input")

End Sub


text:
Q: Python Function - Looping through dictionary and updating value I'm having an issue wherein i'm trying to loop through a dictionary to update all the values based on a specific input from a user.
I've posted my code below, basically, the user inputs a number into the different lanes played input boxes, and the function should update the dictionary to contain the values input by the user.
the loop doesn't seem to be going through every key in my dictionary, only returning the first value and then seemingly skipping the rest.
I am only 3 weeks deep into a python tutorial and I'm  not really sure what i am doing wrong here.
please see code below :
def lane_input():

lanes_played = {"Top":0, "Middle":0, "Jungle":0, "Support":0, "ADC":0}

top_played = input("insert the number of times top played")
top_played = int(top_played)

mid_played = input("insert the number of times Middle played")
mid_played = int(mid_played)

Jungle_played = input("insert the number of times Jungle played")
Jungle_played = int(Jungle_played)

Support_played = input("insert the number of times Support played")
Support_played = int(Support_played)

ADC_played = input("insert the number of times ADC played")
ADC_played = int(ADC_played)

for p, n in lanes_played.items():
    if p == 'Top':
        lanes_played[p] = top_played

    if p == 'Middle':
        lanes_played[p] = mid_played

    if p == 'Jungle':
        lanes_played[p] = Jungle_played

    if p == 'Support':
        lanes_played[p] = Support_played

    if p == 'ADC':
        lanes_played[p] = ADC_played

    return(lanes_played)

print(lanes_played)
print(lanes_played[p])
print(lanes_played[n])

enter code here`enter code here`total = lane_input()
enter code here`print(total)

Code output below :
insert the number of times top played1
insert the number of times Middle played2
insert the number of times Jungle played3
insert the number of times Support played4
insert the number of times ADC played5

{'Top': 1, 'Middle': 0, 'Jungle': 0, 'Support': 0, 'ADC': 0}

A: It's because of bad indentation in your code. The return keyword is hit at the first iteration of the for loop, which makes your function stop.
This works, since return happens after the whole for loop:
def lane_input():

        lanes_played = {"Top":0, "Middle":0, "Jungle":0, "Support":0, "ADC":0}

        top_played = input("insert the number of times top played")
        top_played = int(top_played)

        mid_played = input("insert the number of times Middle played")
        mid_played = int(mid_played)

        Jungle_played = input("insert the number of times Jungle played")
        Jungle_played = int(Jungle_played)

        Support_played = input("insert the number of times Support played")
        Support_played = int(Support_played)

        ADC_played = input("insert the number of times ADC played")
        ADC_played = int(ADC_played)

        for p, n in lanes_played.items():
                if p == 'Top':
                        lanes_played[p] = top_played

                if p == 'Middle':
                        lanes_played[p] = mid_played

                if p == 'Jungle':
                        lanes_played[p] = Jungle_played

                if p == 'Support':
                        lanes_played[p] = Support_played

                if p == 'ADC':
                        lanes_played[p] = ADC_played

        return(lanes_played)

A: The return is inside the for-loop, thus the iteration stops after the first round only. This is what you meant to do:
def lane_input():
    lanes_played = {"Top":0, "Middle":0, "Jungle":0, "Support":0, "ADC":0}

    top_played = input("insert the number of times top played")
    top_played = int(top_played)

    mid_played = input("insert the number of times Middle played")
    mid_played = int(mid_played)

    Jungle_played = input("insert the number of times Jungle played")
    Jungle_played = int(Jungle_played)

    Support_played = input("insert the number of times Support played")
    Support_played = int(Support_played)

    ADC_played = input("insert the number of times ADC played")
    ADC_played = int(ADC_played)

    for p, n in lanes_played.items():
        if p == 'Top':
            lanes_played[p] = top_played

        if p == 'Middle':
            lanes_played[p] = mid_played

        if p == 'Jungle':
            lanes_played[p] = Jungle_played

        if p == 'Support':
            lanes_played[p] = Support_played

        if p == 'ADC':
            lanes_played[p] = ADC_played

    return(lanes_played)

total = lane_input()
print(total)

Output
insert the number of times top played 1
insert the number of times Middle played 2
insert the number of times Jungle played 3
insert the number of times Support played 4
insert the number of times ADC played 5
{'Top': 1, 'Middle': 2, 'Jungle': 3, 'Support': 4, 'ADC': 5}

And there is no need to iterate through a dictionary, so you could refactor your code to this (with the same output)
def lane_input():
    lanes_played = {"Top":0, "Middle":0, "Jungle":0, "Support":0, "ADC":0}

    top_played = int(input("insert the number of times top played"))
    lanes_played['Top'] = top_played

    mid_played = int(input("insert the number of times Middle played"))
    lanes_played['Middle'] = mid_played

    Jungle_played = int(input("insert the number of times Jungle played"))
    lanes_played['Jungle'] = Jungle_played

    Support_played = int(input("insert the number of times Support played"))
    lanes_played['Support'] = Support_played

    ADC_played = int(input("insert the number of times ADC played"))
    lanes_played['ADC'] = ADC_played

    return(lanes_played)

total = lane_input()
print(total)

A: Your question has been answered. This answer just gives a better alternative for your code.
def lane_input():

        top_played      =   int(input("insert the number of times top played"))
        mid_played      =   int(input("insert the number of times Middle played"))
        Jungle_played   =   int(input("insert the number of times Jungle played"))
        Support_played  =   int(input("insert the number of times Support played"))
        ADC_played      =   int(input("insert the number of times ADC played"))

        return {
            "Top"       :   top_played,
            "Middle"    :   mid_played,
            "Jungle"    :   Jungle_played,
            "Support"   :   Support_played,
            "ADC"       :   ADC_played
        }


text:
Q: Getting java.lang.NoSuchFieldError: INT_8 error while running spark job through oozie I am Getting java.lang.NoSuchFieldError: INT_8 error when I am trying to execute a spark job using OOzie on Cloudera 5.5.1 version.
Any help on this will be appreciated.
Please find the error stackstrace below.
16/01/28 11:21:17 WARN TaskSetManager: Lost task 0.2 in stage 20.0 (TID 40, Zlab-physrv1): java.lang.NoSuchFieldError: INT_8
    at org.apache.spark.sql.execution.datasources.parquet.CatalystSchemaConverter.convertField(CatalystSchemaConverter.scala:327)
    at org.apache.spark.sql.execution.datasources.parquet.CatalystSchemaConverter.convertField(CatalystSchemaConverter.scala:312)
    at org.apache.spark.sql.execution.datasources.parquet.CatalystSchemaConverter$$anonfun$convertField$1.apply(CatalystSchemaConverter.scala:517)
    at org.apache.spark.sql.execution.datasources.parquet.CatalystSchemaConverter$$anonfun$convertField$1.apply(CatalystSchemaConverter.scala:516)
    at scala.collection.IndexedSeqOptimized$class.foldl(IndexedSeqOptimized.scala:51)
    at scala.collection.IndexedSeqOptimized$class.foldLeft(IndexedSeqOptimized.scala:60)
    at scala.collection.mutable.ArrayOps$ofRef.foldLeft(ArrayOps.scala:108)
    at org.apache.spark.sql.execution.datasources.parquet.CatalystSchemaConverter.convertField(CatalystSchemaConverter.scala:516)
    at org.apache.spark.sql.execution.datasources.parquet.CatalystSchemaConverter.convertField(CatalystSchemaConverter.scala:312)
    at org.apache.spark.sql.execution.datasources.parquet.CatalystSchemaConverter.convertField(CatalystSchemaConverter.scala:521)
    at org.apache.spark.sql.execution.datasources.parquet.CatalystSchemaConverter.convertField(CatalystSchemaConverter.scala:312)
    at org.apache.spark.sql.execution.datasources.parquet.CatalystSchemaConverter$$anonfun$convert$1.apply(CatalystSchemaConverter.scala:305)
    at org.apache.spark.sql.execution.datasources.parquet.CatalystSchemaConverter$$anonfun$convert$1.apply(CatalystSchemaConverter.scala:305)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.Iterator$class.foreach(Iterator.scala:727)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
    at scala.collection.IterableLike$class.foreach(IterableLike.scala:72)
    at org.apache.spark.sql.types.StructType.foreach(StructType.scala:92)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
    at org.apache.spark.sql.types.StructType.map(StructType.scala:92)
    at org.apache.spark.sql.execution.datasources.parquet.CatalystSchemaConverter.convert(CatalystSchemaConverter.scala:305)
    at org.apache.spark.sql.execution.datasources.parquet.ParquetTypesConverter$.convertFromAttributes(ParquetTypesConverter.scala:58)
    at org.apache.spark.sql.execution.datasources.parquet.RowWriteSupport.init(ParquetTableSupport.scala:55)
    at parquet.hadoop.ParquetOutputFormat.getRecordWriter(ParquetOutputFormat.java:277)
    at parquet.hadoop.ParquetOutputFormat.getRecordWriter(ParquetOutputFormat.java:251)
    at org.apache.spark.sql.execution.datasources.parquet.ParquetOutputWriter.<init>(ParquetRelation.scala:94)
    at org.apache.spark.sql.execution.datasources.parquet.ParquetRelation$$anon$3.newInstance(ParquetRelation.scala:272)
    at org.apache.spark.sql.execution.datasources.DefaultWriterContainer.writeRows(WriterContainer.scala:233)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelation$$anonfun$run$1$$anonfun$apply$mcV$sp$3.apply(InsertIntoHadoopFsRelation.scala:150)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelation$$anonfun$run$1$$anonfun$apply$mcV$sp$3.apply(InsertIntoHadoopFsRelation.scala:150)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:88)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

As per My idea normally we used to get this error when ever there is some difference on the jars you have used to generate the code and the jars you have used currently.
Note: When I am trying to submit the Same one using spark-submit command it's running fine.
Regards
Nisith

A: Finally Able to debug and fix the issue. The Issue was with the installation as one of the data nodes are having older version of parquet Jars(5.2 cdh distribution). After replacing the jars with the current version jars it was working fine.


text:
Q: Book About Survival Test on Another Planet I remember picking up a book a while ago (4-5 years ago?), managed to read the first few chapters.
It seems similar to "Tunnel in the Sky" but the details don't match up. I remember the main character coming to school and seeing on the blackboard that a survival test is coming up. Earth is definitely an interstellar civilization by this point, because I remember on his way home he mentions a bus "full of chlorine-breathers." At home, his parents explain that the test was taken by everyone once of age. I think his father then gives him a knife that he used in his test?
When he arrives at the spaceport or whatever its called, he and his class go through a door (which is some sort of portal/wormhole), and he remarks about the sudden feeling of less weight. They go through another door and are back on 1 G gravity. I think he had to spend the night in a tree due to a predatory animal.
Next day he meets up with another classmate and the main character declares his opinion that they are in fact on Earth, and that "we took the Moon step/bounce/whatever back to Johannesburg." The other classmate then says that he/she saw a pentagonal constellation, and that there are no such constellations in the Southern Hemisphere. That night they see another star in the middle of the pentagon that was not there before, and I think he claims that they saw the first supernova from another planet. The next day they find the body of a classmate who was overconfident, mauled up by the same beast the main character had to run away from. I did not read any further, so I do not know how it ends.

A: I think this has to be Tunnel in the Sky; the bit about a pentagon of stars is so spot on:

"I knew the Southern Cross before I could read. These aren't our stars, Rod; I know. There is a pentagon of bright stars above where the sun sets; there is nothing like that to be seen from Earth. And besides, anybody would recognise Luna, if it was there."

Posted notice of the upcoming test:

The bulletin board outside lecture hall 1712-A of Patrick Henry High School showed a flashing red light. Rod Walker pushed his way into a knot of students and tried to see what the special notice had to say. He received an elbow in the stomach, accompanied by: "Hey! Quit shoving!"
"Sorry. Take it easy, Jimmy." Rod locked the elbow in a bone breaker but put no pressure on, craned his neck to look over Jimmy Throxton's head. "What's on the board?"
[...]
Twenty-Four Hour Notice is hereby given of final examination in Solo Survival. Students will present themselves for physical check at 0900 Saturday in the dispensary of Templeton Gate and will start passing through the gate at 1000, using three-minute intervals by lot.

The bit about the chlorine-breathers:

While he watched, the red light flickered out and a blue light replaced it; the door slowly opened and a traveling capsule for a chlorine-breather crawled out.

Rod's sister Helen gives him the blade she used in her test:

She retrieved both knives, stood balancing them, one on each hand. She flipped her own so that the grip was toward Rod. "This is my pet, 'Lady Macbeth.' I carried her on my own solo, Buddy. I want you to carry her on yours."

Chased up a tree by a predator:

Having picked his route, he straightened up and at a fast dogtrot headed for the nearest tree. He went past it, cut left for another tree, passed it and cut right toward the tree he wanted. He was about fifteen meters from it when something charged him.
He closed the gap with instantaneous apportation which would have done credit to a Ramsbotham hyperfold. He reached the first branch, ten meters above ground, in what amounted to levitation. From there on he climbed more conventionally, digging the spurs into the tree's smooth bark and setting his feet more comfortably on branches when they began to be close enough together to form a ladder.
About twenty meters above ground he stopped and looked down. The branches interfered and it was darker under the trees than it had been out in the open; nevertheless he could see, prowling around the tree, the denizen that had favored him with attention.
Rod tried to get a better view, but the light was failing rapidly. But it looked like... well, if he had not been certain that he was on some uncolonized planet 'way out behind and beyond, he would have said that it was a lion.
Except that it looked eight times as big as any lion ought to look.

Jack (not Rod) found the deceased classmate, who had previously stolen Rod's stuff:

"Do you want to hear this? I ran across this hombre in the bush, just as the jackals were getting to him. I don't know what got him—stobor, maybe; he was pretty well clawed and half eaten. He wasn't one of my class, for his face wasn't marked and I could tell. He was carrying a Thunderbolt and—"
"Wait a minute. A Thunderbolt gun?"
"I said so, didn't I? I guess he tried to use it and had no luck. Anyhow, I took what I could use—this knife and a couple of other things; I'll show you. I left the Thunderbolt; the power pack was exhausted and it was junk."

Linking from the Moon to Johannesburg:

"It's a good one. What the Deacon forgot is that any environment is as unknown as any other if you don't have the slightest idea where you are. So they rigged it so that we could not know. First they shot us to Luna; the Moon gates are always open and that doesn't cost anything extra. Of course that made us think we were in for a long jump. Besides, it confused us; we wouldn't know we were being dumped back into the gravity field we had left- for that was what they did next; they shoved us back on Earth. Where? Africa, I'd say. I think they used the Luna Link to jump us to Witwatersrand Gate outside Johannesburg and there they were all set with a matched-in temporary link to drop us into the bush. Tshaka Memorial Park or some other primitive preserve, on a guess. Everything matches. A wide variety of antelope-type game, carnivores to feed on them—I've seen a couple of lions and—"

A new star in the pentagon:

Framed by the ledge above him and by tree tops across the stream was a pattern of six stars, a lopsided pentagon with a star in its center. The six stars were as bright and unmistakable as the seven stars of Earth's Big Dipper... nor did it take a degree in astrography to know that this constellation had never been seen from Terra.
Rod stared while the hard convictions he had formed fell in ruins. He felt lost and alone. The trees across the way seemed frightening. He turned to Jack, his cocky sophistication gone. "You've convinced me," he said dully. "What do we do now?"
Jack did not answer.
"Well?" Rod insisted. "No good standing here."
"Rod," Jack answered, "that star in the middle of the Pentagon-it wasn't there before."
"Huh? You probably don't remember."
"No, no, I'm sure! Rod, you know what? We're seeing a nova."


text:
Q: Is there any crowded countable Hausdorff compact space? I have search this question but just found at most some models that it is consistent without any especial example for its existence.

A: If $X$ is (locally) compact Hausdorff it is a Baire space and if it is crowded, it cannot be countable as otherwise $X \setminus \{x\}$, $x \in X$ would be a countable family of open and dense subsets with empty (and not dense) intersection. This uses a mild form of choice (DC ((countable) dependent choice) I think), but that's not a problem IMHO.
If you don't wat to invoke Baire-ness, just mimick its proof: let $f:\mathbb{N} \to X$ be any function and pick (by DC again) for each $n$ some non-empty open set with compact closure (automatic for compact $X$) $O_n$ such that $f(n) \notin \overline{O_n}$ and the $O_n$ are nested. Then $\bigcap_n \overline{O_n} \neq \emptyset$ by compactness and contains a point not in $f[\mathbb{N}]$, implying $X$ cannot be countable. This is in essence Cantor's original proof for the fact that $[0,1]$ is not countable, although he used shrinking balls and Cauchy sequences.
So if you accept a mild form of choice (or full-blown ZFC, as I tend to do) no compact crowded Hausdorff space can be countable, and with some more effort we can even show $|X| \ge 2^{\aleph_0}$, but in ZF, without any choice assumed, I believe countable such spaces can exist IIRC, but I'm no specialist.


text:
Q: amazon ec2 instances lost boot drive? This is driving me crazy since hours now. I have done the setup of 5 instances in AWS (some micro, some large) and after a while when i stopped them and rebooted them many times one of them won't boot.
I digged the problem to the point where when dracut start and try to switch the root filesystem there is some errors with the disk mapping and the /dev/xvd* devices.
Logs from a working one :
udev: starting version 147 dracut: Starting plymouth daemon xlblk_init: register_blkdev major: 202 blkfront: xvde1: barriers disabled Changing capacity of (202, 65) to 14680064 sectors xvde1: detected capacity change from 0 to 7516192768 EXT4-fs (xvde1): mounted filesystem with ordered data mode. Opts: dracut: Mounted root filesystem /dev/xvde1 dracut: Loading SELinux policy
Logs from a non working one :
udev: starting version 147 dracut: Starting plymouth daemon xlblk_init: register_blkdev major: 202 blkfront: xvde1: barriers disabled EXT4-fs (xvde1): mounted filesystem with ordered data mode. Opts: dracut: Mounted root filesystem /dev/xvde1 dracut: Loading SELinux policy
I have tried to delete /etc/blkid/* but without luck.
If someone could help me on this i would be very thankfull

A: If you mix EBS and instance store volumes, instance store data will be lost after reboot. For long term instances you should go 100% of times for EBS volumes, and leave instance storage class for "burst" applications that you only require to be online on demand; ASGs are the typical use case for instance storage.
The other possibility could be that you or your configuration management system mangled in some way your fstab file. If AWS volumes are not mounted in exactly the same path as detailed in the fstab file, instance boot will fail miserably. Also, do not forget that in EC2 boot volumes must be mounted to /dev/sda1.


text:
Q: 'Access is denied' on wrong port select could not open port 'COM#': PermissionError(13, 'Access is denied.', None, 5)
actually this is not a mistake, I want to show window alert message when someone select wrong port
if anyone knows please help
def add_charger_view(request):
    if request.method == 'POST':
        port = request.POST['port']
        port = port.split().pop(0)
        baud_rate = request.POST['baud_rate']
        serial.Serial(port, baud_rate)
return render(request, "charger.html")

all things good, connection is ok but shows this error in not ok


text:
Q: Deployment to Azure web app display Error: fatal: Authentication failed for 'https://xxx.scm.azurewebsites.net:443/xxx.git/' I am trying to deploy my node.js application to azure web app using Azure App Service management extension via vs code.
I succeeded to deploy this application many times until two days ago.
Since then I am getting the error log:
WARNING: Ignoring deploySubPath "." for non-zip deploy.
xxx: Starting deployment...
xxx: Deploying Local Git repository to "xxx"...
Error: fatal: Authentication failed for 'https://xxx.scm.azurewebsites.net:443/xxx.git/'
At the Azure portal under the Activity log I am getting:
Operation name: Publish Web App
Status: Succeeded
However, At the Deployment center -> Logs:
I cannot see the new deployment.
Any ideas for what should I do?
Note:
Authentication failed for Azure Git
I able to clone an Azure git repository without any problem.
The problem appears when I am trying to deploy my node.js project to Azure App Services using LocalGit in vs code.
When I am looking at the Azure portal -> Deployment Center -> Logs: I cant see the new branch appears on the deployment history


text:
Q: table fixed header not working I have a table with large number of rows, i want to set fixed header while scrolling.
I am trying with the below code, but it is not working.

 (function ($) {
    $.fn.fixedHeader = function () {
        return this.each(function () {
            var $this = $(this),
               $t_fixed;

            function init() {
                $this.wrap('
');
                $t_fixed = $this.clone();
                $t_fixed.find("tbody").remove().end().addClass("floatingHeader").insertBefore($this);
                resizeFixed();
            }
            function resizeFixed() {
                $t_fixed.find("th").each(function (index) {
                    $(this).css("width", $this.find("th").eq(index).outerWidth() + "px");
                });
            }
            function scrollFixed() {

                var offset = $(this).scrollTop(),
                tableOffsetTop = $this.offset().top,
                tableOffsetBottom = tableOffsetTop + $this.height() - $this.find("thead").height();
                if (offset < tableOffsetTop || offset > tableOffsetBottom) {
                    $t_fixed.hide();

                }
                else if (offset >= tableOffsetTop && offset <= tableOffsetBottom && $t_fixed.is(":hidden")) {
                    $t_fixed.show();
                }
                resizeFixed();
                init();
            }
            $(window).resize(resizeFixed);
            $(window).scroll(scrollFixed);
            init();
        });
        // $.fn.fixMe = function(){}; // prevent the function from a second firing
    };
})(jQuery);

$(window).load(function () {
    $(".stickyHeader").fixedHeader();
});

            Firstname
            Lastname
            Points

            Eve
            Jackson
            94

            Eve
            Jackson
            94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

            Eve
            Jackson
            94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

    Eve
    Jackson
    94

I know this can be done using CSS but I want to do this using javascript/jquery only,


text:
Q: .AsNoTracking() not working entity framework core 5 I am using entity framework with this configuration on the Startup:
 services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                   Configuration.GetConnectionString("DefaultConnection"),
                     //b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)
                     b => b.MigrationsAssembly("ThreeTasty.Infrastructure")
           )
           .UseLazyLoadingProxies()
            );

and in my Entity framework query I am trying to get the entity without tracking:
 query = query.Include(x => x.OrderProducts.Where(x => x.Active == true))
                        .ThenInclude(x => x.Product)
                        .ThenInclude(x => x.ProductImages).AsNoTracking()

                        //order product with images
                        .Include(x => x.OrderProducts.Where(x => x.Active == true))
                        .ThenInclude(x => x.Product)
                        .ThenInclude(x => x.ProductVendors)
                        .ThenInclude(x => x.VendorProductSizeUnit).AsNoTracking();

Even after doing the .AsNoTracking() on the last entity VendorProductSizeUnit in the .ThenInclude() I get the following error while updating entity in a separate table:
The instance of entity type 'VendorProductSizeUnit' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.


text:
Q: Widget with random posts from a blog for external sites How can I create a customizable widget with random posts from my blog that can be published on another site as js, iframe or div.
Is there any Wordpress plugin for that?

A: To create a special output of random posts:

*

*Register an endpoint to the root of your blog. See A (Mostly) Complete Guide to the WordPress Rewrite API for details.

*Refresh the permalink settings. I would do this on (de)activation only.

*Hook into 'template_redirect' and return your output depending on the details of the requested endpoint. Then exit.

That's all.
Well … some code may help to understand the details. :)
Let's build a small plugin for HTML and JSON output.
I have named it T5 Random Posts Endpoint; all code goes into a class with static methods to keep the global namespace clean.
add_action( 'init', array ( 'T5_Random_Posts_Endpoint', 'init' ) );

/**
 * Build a root endpoint.
 */
class T5_Random_Posts_Endpoint
{
    /**
     * Register endpoint and actions.
     *
     * @wp-hook 'init'
     * @return  void
     */
    public static function init()
    {
        add_rewrite_endpoint( 'randomposts', EP_ROOT );
        add_filter( 'request', array ( __CLASS__, 'filter_request' ) );
        add_action( 'template_redirect', array ( __CLASS__, 'render' ) );
    }
}

As you can see, we call a central init method on 'init' to … initialize our plugin. Creative naming, huh?
The endpoint is named randomposts and attached to the root. So after activation you can get the out put on example.com/randomposts/ or example.com/randomposts/json/.
But … if you call the first URL the endpoint works and the request variable randomposts is set – but it is empty. That's why we hook into 'request' and give the variable a default value we can work with later. Let's use html as default:
    /**
     * Prepare the endpoint variable so it has always a value.
     *
     * @wp-hook 'request'
     * @param   array $request
     * @return  array
     */
    public static function filter_request( $request )
    {
        if ( isset ( $request['randomposts'] )
            and empty ( $request['randomposts'] )
        )
        {
            $request['randomposts'] = 'html';
        }

        return $request;
    }

Now we hook into 'template_redirect' so WordPress will not use the default template index.php but our own output.
    /**
     * Create output.
     *
     * @wp-hook 'template_redirect'
     * @return  void
     */
    public static function render()
    {
        // This is not our endpoint.
        if ( '' === $type = get_query_var( 'randomposts' ) )
        {
            return;
        }

        // Someone is poking around.
        // You can extend this and build different output variants.
        if ( ! in_array( $type, array ( 'html', 'json' ) ) )
        {
            status_header( 414 );
            print 'Unsupported Media Type. Use "html" or "json" only.';
            exit;
        }

        // Empty blog?
        if ( ! $posts = get_posts( array ( 'numberposts' => 10, 'orderby' => 'rand' ) ) )
        {
            status_header( 404 );
            print 'No posts found.';
            exit;
        }

        self::$type( self::prepare_post_data( $posts ) );
        exit;
    }

First we check if we are really on our endpoint by looking into get_query_var( 'randomposts' ). We filled this variable in our request filter, so if it is still empty, we know for sure that is not our business and we return quickly.
Then we test if the request was for one of our predefined output variants html or json. If someone is calling /randomposts/css or /randomposts/lala we raise a 414 error with a helpful message. And exit.
Then we get finally our posts with get_posts() and remove all the data we don't need in a dedicated method named prepare_post_data():
    /**
     * Build a simple array with just titles and permalinks.
     *
     * @wp-hook 'template_redirect'
     * @param   array $posts
     * @return void
     */
    protected static function prepare_post_data( $posts )
    {
        $data = array ();

        foreach ( $posts as $post )
        {
            if ( empty ( $post->post_title) )
            {
                continue;
            }

            $data[ $post->ID ] = array (
                'title' => strip_tags( $post->post_title ),
                'url'   => get_permalink( $post->ID )
            );
        }

        return $data;
    }

We pass this simple array to a method named exactly like our output: html() or json().
Let's start with json(); that's the easy part. See How to encode post content as JSON? for some background.
    /**
     * Render JSON output
     *
     * @wp-hook 'template_redirect'
     * @param  array $data
     * @return void
     */
    protected static function json( array $data )
    {
        header( 'Content-type: application/json' );
        print json_encode( $data );
    }

Easy, isn't it? The html() is not that much harder, just longer:
        /**
         * Render HTML output
         *
         * @wp-hook 'template_redirect'
         * @param  array $data
         * @return void
         */
        protected static function html( array $data )
        {
            ?>
<!doctype html>
<title><?php bloginfo( 'name' ); ?></title>
<meta name="viewport" content="width=device-width; initial-scale=1.0">
<?php
// Just a sample style. Be creative! :)
?>

<a href="<?php bloginfo( 'url' ); ?>"><?php bloginfo( 'name' ); ?>

<?php
foreach ( $data as $post )
{
    print '
' . $post['title'] . '
';
}
?>

<?php
        }

This is how it looks with the theme test data:

Now our output is finished – we are still in render() – and we call exit because otherwise WordPress would include the index.php from the active theme.
Now we need just a method to refresh the permalink settings:
    /**
     * Reset permalinks.
     *
     * @wp-hook 'activate_' . __FILE__
     * @wp-hook 'deactivate_' . __FILE__
     * @return  void
     */
    public static function flush_rewrite_rules()
    {
        remove_action( 'init', array ( __CLASS__, 'init' ) );
        add_action( 'init', 'flush_rewrite_rules', 11 );
    }

We prevent our default init hook here because on activation we are on the plugin list where we don't need the endpoint, and on deactivation we do not want to re-register the now unused permalink.
We attach this method to (de)activation with:
// refresh permalink settings
register_activation_hook(
    __FILE__ ,
    array ( 'T5_Random_Posts_Endpoint', 'flush_rewrite_rules' )
);
register_deactivation_hook(
    __FILE__ ,
    array ( 'T5_Random_Posts_Endpoint', 'flush_rewrite_rules' )
);

And now we can say: That's all. Really.
If you made it this far grab the complete plugin from GitHub.

A: I think in essence what you're talking about is a Custom Widget that will parse and display RSS Feed of your Blog. Here, you can build a Custom Widget of your own and hard-code the RSS Feed URL of your Blog in your Widget PHP itself to make sure Widget User doesn't change the URL; so your widget will show RSS of your Blog only.
Now, once you finalize to use RSS to fork your Blog, you've several options open in front of you. Either you can use Wordpress's own RSS Feed abilities to save you time (but this will impose many limitations) OR write your own RSS Feed maker code as Web Service installed on your Server/Web Hosting that will interact with your Widget. So, make your Widget PHP to send request to your Blog's RSS Feed Publishing Web Service; then parse the results returned by your Server and display RSS Feed items.
If you've time to invest and serious about this Widget, then better you implement your own Web Service. I don't think it'll be too hard for you... just play with WP_Query and return the results in proper RSS Feed XML Format. This way you will also be able to offer Category list in Drop-down to your Widget User to choose from and make your Widget PHP to request RSS of Posts only from selected Category of your Blog. Plus, you'll have better control over how many Posts to return in RSS Feed requested by your Widget.
I hope this helps.
Cheers,
Ruturaaj.


text:
Q: In prestashop how to use header and footer in custom php page I want to display php pages into Prestahop body part. How can i include header and footer into my php file. Is it possible to use external page in prestashop.

A: Add following to your PHP file;
<?php
require(dirname(__FILE__).'/config/config.inc.php');
include(dirname(__FILE__).'/header.php');

ControllerFactory::getController('YourController')->run();

include(dirname(__FILE__).'/footer.php');
?>


text:
Q: How to embed mullitple NavigationLinks into a single List row? I'm trying to replicate something like Apple's Reminders app where there are some "blocks" (Today, Scheduled, All and Flagged), but all my attempts end in XCode telling me its encountering navigation issues. I'm using XCode 13.2.1 and iOS 15.2 right now.
How can I get each bock to navigation to its own destination and stop the app from choking on the NavigationLink errors?
Here is my code:
struct ContentView: View {
    var body: some View {
        NavigationView {
            List {
                Section(header: Text("Primary Section")) {
                    NavigationLink(destination: Text("First")) {
                        Label("First", systemImage: "1.circle")
                    }
                    Label("Second", systemImage: "2.circle")
                    Label("Third", systemImage: "3.circle")
                }
                Section(header: Text("Block Section")) {
                    VStack (spacing: 20) {
                        HStack (spacing: 20) {
                            Blocks(title: "1")
                            Blocks(title: "2")
                        }
                        HStack (spacing: 20) {
                            Blocks(title: "3")
                            Blocks(title: "4")
                        }
                    }
                    .foregroundColor(Color.blue)
                    .frame(height: 160)
                    .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
                    .listRowBackground(Color.clear)
                }
                Section(header: Text("Lower Section")) {
                    NavigationLink(destination: Text("Lower First")) {
                        Label("First", systemImage: "1.circle")
                    }
                    Label("Second", systemImage: "2.circle")
                    Label("Third", systemImage: "3.circle")
                    NavigationLink(destination: Text("Lower Fourth")){
                        Label("Fourth", systemImage: "4.circle")
                    }
                }
            }
            .listStyle(InsetGroupedListStyle())
            .navigationBarTitle(Text("Catalogue"), displayMode: .large)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct Blocks: View {
    let title: String
    var body: some View {
        ZStack {
            NavigationLink(
                destination: Text(title)) {
                EmptyView()
            }
            .opacity(0)
            RoundedRectangle(cornerRadius: 12, style: .continuous)
            Image(systemName: "\(title).circle.fill")
                .foregroundColor(.white)
                .imageScale(.large)
        }
    }
}```


text:
Q: Lexmark Z715 Ink Jet printer program for Windows 8 Where can I get a driver for a Lexmark Z715 ink jet printer? Lexmark can't help me.  What I don't understand is that I've been using this printer in this computer for 7-8 months, but for some reason I lost it and now can't get it back.

A: Use the Windows Vista 64-Bit Driver from here - You may have to install and use it in Compatibility Mode -
http://support.lexmark.com/index?page=product&linkSelected=node0&locale=EN&userlocale=EN_US#1

A: I have E250d which is really old and I use it with Win 8.1 Pro 64-bit. I downloaded Lexmark universal print driver installation package. Try it and let me know if it help you.
Try this: http://support.lexmark.com/index?docLocale=fr_FR&page=content&id=DR22598&locale=EN&userlocale=EN_US


text:
Q: Need to wipe hard drive Ubuntu 12.10 to put Windows My dad had a blank hard drive on which I installed Ubuntu because it was easier than getting windows. Some WiFi drivers will not install. My dad only uses it for email, Craiglist, and chat on Facebook, so he doesn't care what OS he has as long as he can go online. I have the XP disk.
When I type sudo fdisk -l in the terminal i get
/dev/sda1   *        2048   114300927    57149440   83  Linux
/dev/sda2       114302974   117229567     1463297    5  Extended
/dev/sda5       114302976   117229567     1463296   82  Linux swap / Solaris
Then i type sudo dd if=/dev/zero of=device bs=1M and nothing happens. How do I wipe the whole hard drive?

A: This is not really an Ubuntu question per se. Nevertheless when you install XP, it should give you an option to completely overwrite what is currently on it. You don't have to remove Ubuntu first.

A: If I understand you correctly, then you have a HDD which has a corrupted OS. Plug it into some other computer which is working correctly and format it. Then you will be able to do anything.


text:
Q: any tips for upgrade postgres 8.2 to 8.4? i have to migrate a 80GB database from pg8.2 to pg8.4. that database has a lot of stock procedures, and i need tips to migrate it sucesfully ( and painless ;) )  any tips are welcome :)

A: Testing is ABSOLUTELY REQUIRED.  Since you skipped it, as of 8.3:

Non-character data types are no longer automatically cast to TEXT (Peter, Tom)

It took us quite a bit of work to go through and find all the places we had trusted the automatic casting (for instance, we had WHERE dob LIKE '%-09-%' to send birthday emails, which trusted not only that dob was automatically typecast, but also that Postgres would pick the yyyy-mm-dd format for its output).

A: The best possible advice here is to follow the instructions for upgrading provided in the Postgres manual (also see this section)  - This will involve a database dump and restore in your case.
You should probably set up the new database on a development machine and test the restore (& DB functionality) before doing this on production hardware.
You should DEFINITELY back up the PGDATA directory from your old installation when you make the switch (or give the new installation a new path for its data directory) so that you can go back to the old system in the event of an unforeseen catastrophic failure in the migration process.

A: Testing testing and more testing. Get it installed on a new machine/server if possible before the move, and do a test run, check what runs- and more importantly, what doesn't. Draw up a test plan of everything which needs to work.

A: Aside from the valuable specific advice given in other answers, the canonical answer to this sort of question is to read the release notes.  For example, in an upgrade from 8.2 to 8.4 you should read the release notes

*

*of 8.3: http://www.postgresql.org/docs/8.3/static/release-8-3.html

*of 8.4: http://www.postgresql.org/docs/8.4/static/release-8-4.html
in particular the Migration sections that list the known incompatibilities.


text:
Q: Is there a way to get directory's actual path in wix? I want to bind a property to a directory's id path. Is there a way to get the directory's actual path from a directory id or somehow ?

A: The Directory element  Id attribute in WiX becomes the Directory Table Directory column in the build Windows Installer MSI database.   During installation, directory resolution is performed by the CostFinalize Action.  After this point you can Using a Directory Property in a Path.

The directories in the Directory table specify the layout of an
  installation. When the Windows Installer resolves these directories
  during the CostFinalize action, the keys in the Directory table become
  properties set to directory paths. The installer also always sets a
  number of standard System Folder Properties to system folder paths.

For example in a RegistryValue element you could give a value of  [INSTALLLOCATION].


text:
Q: Performance implications setting readonly/writeonly on image units in GLSL In glBindImageTexture(),  access can be GL_READ_ONLY, GL_WRITE_ONLY, or GL_READ_WRITE.
I assume that these should match the readonly and writeonly qualifiers on image units (eg. image2D or imageBuffer) in GLSL.
I haven't noticed any difference when setting readonly or writeonly (2013, NVIDIA 319.49 drivers). Granted, I might not be doing anything that would otherwise cause a slowdown and hence don't see any improvement. These qualifiers may also simply be ignored by current GL implementations.

*

*In what cases could a GL implementation make use of readonly/writeonly, why do they exist?
Cache coherency comes to mind, but don't the coherent/volatile qualifiers cover this already? I've used these and they appear to work.

*

*Has anyone experienced a difference in performance or results when using readonly/writeonly, how important are they?
Don't be afraid to reply if it's been years, I'm interested to know and I'm sure others are too.

A: It only tells a hint to the driver of how the memory is supposed to be used. It's up to the driver to do optimizations or not. I have not seen any difference on NVidia drivers. One thing is certain, if you write in a read only image, the result is undefined. Same for reading a write only image. But even if it does not make a difference on today's drivers, you should still use them coherently with what you are actually doing with these images: future drivers may use these hints to optimize the memory access.

A: See, the thing is there is no actual enforcement of these access policies. OpenGL intentionally leaves the behavior of writing to a read-only image undefined for reasons that will be explained below. Among other things, this allows a lot of flexibility on the end of the implementation to use the read-only attribute for a number of different optimization strategies (think of it more like a hint than a strict rule). Because the behavior is undefined, you are right, they could be ignored by the implementation, but should not be ignored by the application developer. Invoking undefined behavior is a ticking time bomb.
To that end, there exists no mechanism in GLSL (or shaders in general) to emit an error when you try to store something in a read-only image, making enforcing this policy significantly more difficult. The best you could hope for is some kind of static analysis at compile-time that is later verified against the access policies of the bound image texture at runtime. That is not to say it may not happen in the future, but at present no such feature exists. The only thing that GLSL provides is a compile-time guarantee that readonly variables cannot be used in conjunction with imageStore (...) in the shader. In short, the GLSL qualifier is enforced at compile-time, but the access policy of the bound image is not at run-time.
The fact that you are not seeing any performance improvement is not surprising. This is a pretty new feature, you will have to give it years before drivers do anything profound with the access policy. It does not hurt anything to provide the hint, so long as you yourself do not violate it.


text:
Q: Gunicorn NameError: global name 'fileno' is not defined I'm working on a Django app with gunicorn right now.  Everything has been working for the past couple months but today, when I tried to deploy my latest changes to my dev server, I got this error when I tried to access it:
Traceback (most recent call last):
  File "/Users/ctaylor/.virtualenvs/seniordating/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 130, in handle
    self.handle_request(listener, req, client, addr)
  File "/Users/ctaylor/.virtualenvs/seniordating/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 174, in handle_request
    resp.write_file(respiter)
  File "/Users/ctaylor/.virtualenvs/seniordating/lib/python2.7/site-packages/gunicorn/http/wsgi.py", line 396, in write_file
    if not self.sendfile(respiter):
  File "/Users/ctaylor/.virtualenvs/seniordating/lib/python2.7/site-packages/gunicorn/http/wsgi.py", line 360, in sendfile
    offset = os.lseek(fileno, 0, os.SEEK_CUR)
NameError: global name 'fileno' is not defined

Gunicorn command:
gunicorn --bind 0.0.0.0:8000 --pythonpath server base.wsgi_django:application

I have been unable to find anything about this online and have absolutely no idea what I did to cause this error. If anyone has any ideas, please let me know!
UPDATE
When running my server in debug mode, I get this error instead, and it shows up many more times:
Traceback (most recent call last):
  File "/Users/ctaylor/.virtualenvs/seniordating/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/ctaylor/.virtualenvs/seniordating/lib/python2.7/site-packages/django/views/static.py", line 54, in serve
    fullpath = os.path.join(document_root, newpath)
  File "/Users/ctaylor/.virtualenvs/seniordating/lib/python2.7/posixpath.py", line 77, in join
    elif path == '' or path.endswith('/'):
AttributeError: 'NoneType' object has no attribute 'endswith'

A: I'm having the exact same issue with a Flask app. Turns out it is a bug in Gunicorn 19.4.4. Downgrading to 19.4.3 solves the problem for me.
Reporting it upstream.


text:
Q: Filtering Array with NSPredicate I am trying to filter an array with NSPredicate, but it always returns an empty array.
Code:
_contentFilteredArray = [_contentArray mutableCopy];
[_contentFilteredArray filterUsingPredicate:[NSPredicate predicateWithFormat:@"special == 1"]]; // Always return an empty array.

Original _contentArray:
(
    {
    id = 1;
    special = 0;
},
    {
    id = 2;
    special = 1;
},
    {
    id = 3;
    special = 1;
},
    {
    id = 4;
    special = 0;
    }
)

What I Expect to _contentFilteredArray:
(
    {
    id = 2;
    special = 1;
},
    {
    id = 3;
    special = 1;
},
)

A: Make sure that the items in the array are key-value coding compliant for the key special.  Does
   [item valueforKey: @"special"]

return the expected numeric value?

A: Try this, more following the traditional withFormat methods.
[NSPredicate predicateWithFormat:@"special == %@", @1]


text:
Q: How to remove commas from printed result? I need to print this list without the commas, but I can't seem to figure out how.
data = (
    ('Sabrina Bryan,1/3/98,ss9387,f9;s1;m1,99km'),
    ('Fergus Connon Archer,11/21/89,ss5246,f1;s3,102km'),
    ('Adrian Harvey,3/3/78,ss1654,m5;s2,72km'),
    ('Patricia Abigail Wolf,9/5/00,ss0936,f3;s4;m8,134km'),
    ('Georgina Kramer,6/15/95,ss4837,f5;s2;m1,55km'),
    ('Glenn Julian Ayala,3/19/90,ss3689,s4;f3,152km'),
    ('Anita Davila,6/27/91,ss9367,f8,203km'),
    ('Gertrude Nunez,1/12/97,ss3948,s3;m1,34km'),
    ('Solomon Burton,8/5/88,ss7364,s2;f1,23km'),
    ('Rafael John Murray,10/19/01,ss9105,s9;f3,78km')
)

info = input("What would you like to do? ")
if info == 'b':
    for line in data:
        fname0 = data[0].split(' ')
        lname0 = fname0[1].split(',')
        bday0 = lname0[1].split('/')

        def Sabrina(fname0, bday0):
            print(fname0[0], *bday0[0:2], sep = ', ')
        print(Sabrina(fname0, bday0))

It is printing "Sabrina, 1, 3" when I want it to print "Sabrina 1 3". I have tried using the .replace command, *bday0[0:2].replace(',', ' '), but it just gives me an error. Any tips?

A: You don't need .replace().

print(fname0[0], *bday0[0:2])

or
print(fname0[0], *bday0[0:2], sep = ' ')

will give you the desired output.

A: I figured out a quick solution for your problem:
It is based on the use of F-Strings. With this formatting-solution, you can quickly format your strings by implementing your variables without losing sight of the format of your output, also adding a return to the function.
Function Code Snippet
 def Sabrina(fname0, bday0):
        return f"{fname0[0]}, {bday0[0]} {bday0[1]}"

Here is more information related to the f-strings formatting explained.
It would be a great improvement if you could work around the issue that the values are hardcoded. But for a quick implementation this should help.
Let me know if this answers your question.
Cheers!
Full Working Code-Snippet
data = (
('Sabrina Bryan,1/3/98,ss9387,f9;s1;m1,99km'),
('Fergus Connon Archer,11/21/89,ss5246,f1;s3,102km'),
('Adrian Harvey,3/3/78,ss1654,m5;s2,72km'),
('Patricia Abigail Wolf,9/5/00,ss0936,f3;s4;m8,134km'),
('Georgina Kramer,6/15/95,ss4837,f5;s2;m1,55km'),
('Glenn Julian Ayala,3/19/90,ss3689,s4;f3,152km'),
('Anita Davila,6/27/91,ss9367,f8,203km'),
('Gertrude Nunez,1/12/97,ss3948,s3;m1,34km'),
('Solomon Burton,8/5/88,ss7364,s2;f1,23km'),
('Rafael John Murray,10/19/01,ss9105,s9;f3,78km'))

 info = input("What would you like to do? ")
 if info == 'b':
 for line in data:
      fname0 = data[0].split(' ')
      lname0 = fname0[1].split(',')
      bday0 = lname0[1].split('/')

    def Sabrina(fname0, bday0):
        return f"{fname0[0]} {bday0[0]} {bday0[1]}"

    print(Sabrina(fname0, bday0))


text:
Q: Linked "Combos" not working correctly Fiddle: https://jsfiddle.net/Mrbaseball34/kuj2cz5g/
In the code, I call GetYears to fill a
 with data. When a year is clicked on, it is supposed to append the selected year to the text of the flyout then load the makes

But, what is happening is it is "looping" through the years and calling yearClick for each year in the list after the that is clicked. Yes, it fills the makes
 but then begins looping yearClick() again.
Can anyone help out here? I can't see the forest for the trees, I guess...;-)
var year;
var make;
var model;
var ic;
GetYears();
$("#year-flyout").css("top", $(".m-assisted-decode").position().top);
$("#make-flyout").css("top", $(".m-assisted-decode").position().top  +  40).hide();
$("#model-flyout").css("top", $(".m-assisted-decode").position().top +  75).hide();
$("#parts-flyout").css("top", $(".m-assisted-decode").position().top + 112).hide();

function GetYears() {
    var data =
[{"year":"2017"},{"year":"2016"},{"year":"2015"},{"year":"2014"},{"year":"2013"},{"year":"2012"},{"year":"2011"},{"year":"2010"},{"year":"2009"}];

    $.each(data, function(i, item) {
        $("#years").append("
" + item.year + "
");
        $(".year").on("click", yearClick);
    });
    $("#fa_year").hide();
    $("#year-flyout").show();
}
function yearClick(event) {
    year = $(this).text();
    $("#year_value").attr("placeholder", $("#year_value").attr("placeholder") + ":" + year);
    $("#year-flyout").hide();
    // Get the Makes and populate the Makes Flyout
    GetMakes();
}
function GetMakes() {
   var data =
[{"make":"ACURA"},{"make":"AUDI"},{"make":"BMW"},{"make":"BUICK"},{"make":"CADILLAC"},{"make":"CHEVROLET"},{"make":"CHRYSLER"},{"make":"DODGE"},{"make":"FORD"},{"make":"GMC"},{"make":"HONDA"},{"make":"HUMMER"},{"make":"HYUNDAI"},{"make":"INFINITI"},{"make":"JAGUAR"},{"make":"JEEP"},{"make":"KIA"},{"make":"LAND ROVER"},{"make":"LEXUS"},{"make":"LINCOLN"},{"make":"MAZDA"},{"make":"MERCEDES-BENZ"},{"make":"MERCURY"},{"make":"MINI"},{"make":"NISSAN\/DATSUN"},{"make":"PONTIAC"},{"make":"PORSCHE"},{"make":"RAM"},{"make":"SAAB"},{"make":"SATURN"},{"make":"SCION"},{"make":"SMART"},{"make":"SUBARU"},{"make":"SUZUKI"},{"make":"TOYOTA"},{"make":"VOLKSWAGEN"},{"make":"VOLVO"}];
    $.each(data, function(i, item) {
        $("#makes").append("
" + item.make + "
");
        $(".make").on("click", makeClick);
    });
    $("#make-flyout").show();
}
function makeClick(event) {
    make = $(this).text();
    $("#make_value").attr("placeholder", $("#make_value").attr("placeholder") + ":" + make);
    $("#make-flyout").hide();
    // Get the Models and populate the Models Flyout
    // GetModels();
}

A: There's no need to attach the event listener after each added
 since you're using the class. Just move it out of the each loop
$.each(data, function(i, item) {
    $("#years").append("
" + item.year + "
");
});
$(".year").on("click", yearClick);

If you inspect your year element in Chrome inspector, you can see all the attached events on click, and see that it was firing the same event several times.


text:
Q: wordpress mega menu items, iterating all items on each level of a menu tree (dropdowns) I've been re-writing a portion of this mega menu code to better serve menus where we have 3 levels of items. In this case the main menu has a dropdown called "Sports" which then has "basketball" and "football" each of which are dropdowns with their own respective teams so the menu tree looks like this:
-sports
--basketball
---commanders
---chargers
--football
---sharks
---bears

The issue is that this "sports" dropdown then shows everything in a single list and I want to display a column for each sport. My problem lies in the loop where I'm getting li elements because it iterates one by one and gives the football and basketball options the has-children class, which is fine, but I want to iterate on all 2nd level items first (i.e. the football and basketball items) so that I can make those into columns and then just use CSS for the rest.
How can I restructure the list items in order to achieve that properlY?
<?php
/**
 * Mega Menu Category - Display recent posts from a parent category.
 */

// Walker to create the left part of mega menu
$sub_walker    = new Walker_Nav_Menu;
$have_sub_menu = !empty($sub_items) ? true : false;

if (!isset($sub_items)) {
    $sub_items = array();
}

?>

    <?php if ($have_sub_menu): ?>

            <?php foreach ($sub_items as $nav_item): ?>
                <?php

                    ob_start();

                    // Simulate a simpler walk - $escaped_output is passed-by-ref
                    $escaped_output = '';
                    $sub_walker->start_el($escaped_output, $nav_item, 0, $args);
                    $sub_walker->end_el($escaped_output, $nav_item, $args);

                    ob_end_clean();

                    echo $escaped_output; // phpcs:ignore WordPress.Security.EscapeOutput -- Safe markup generated via WordPress default Walker_Nav_Menu::start_el()
                ?>
            <?php endforeach; ?>

            <li class="menu-item view-all menu-cat-<?php echo esc_attr($item->object_id); ?>"><a href="<?php echo esc_url($item->url); ?>"><?php
                esc_html_e('View All', 'bunyad'); ?>

    <?php endif; ?>

    <?php
        // Add main item (view all) as default
        array_push($sub_items, $item);
        $columns = $have_sub_menu ? 4 : 5;
    ?>

    <section class="column recent-posts" data-columns="<?php echo intval($columns); ?>">
        <?php foreach ($sub_items as $item): ?>
            <div class="posts" data-id="<?php echo esc_attr($item->object_id); ?>">

                <?php

                echo Bunyad::blocks()->load(
                    'Loops\Grid',
                    [
                        'query_type'         => 'custom',
                        'posts'              => $columns,
                        'cat'                => $item->object_id,
                        'columns'            => $columns,
                        'meta_items_default' => false,
                        'meta_above'         => [],
                        'meta_below'         => ['date'],
                        'heading_type'       => 'none',
                        'excerpts'           => false,
                        'style'              => 'sm',
                        'space_below'        => 'none',
                        'pagination'         => false,
                        'cat_labels'         => false
                    ]
                );
                ?>

        <?php endforeach; ?>


text:
Q: monitoring zookeeper on znode child add and delete I am looking for a Zookeeper Recipe to monitor operations performed in a parent node (add child, delete child, etc)
I am unable to figure out how to use the watcher to get the events. Any help is appreciated.
import org.apache.zookeeper.*;
import java.io.IOException;

public class ZookeeperMonitor {
    private static ZooKeeper zookeeper;

    public ZooKeeper connect(String connectionString, int port) throws IOException, InterruptedException {
        ZookeeperWatcher watcher = new ZookeeperWatcher();
        zookeeper = new ZooKeeper(connectionString, port, watcher);

        return zookeeper;
    }

    public void checkForChanges() throws KeeperException, InterruptedException {
        zookeeper.getChildren("/parent",new ChildChangeWatcher());
    }
}

class ZookeeperWatcher implements Watcher {

    public void process(WatchedEvent watchedEvent) {
    }
}

class ChildChangeWatcher implements  Watcher {
    public void process(WatchedEvent e) {
        if(e.getType() == Event.EventType.NodeChildrenChanged){
            System.out.println("change in children");
        }
    }
}

how do I run this as a long-running daemon?
Also is watcher alone enough or should I use a callback. I did not understand the purpose of callback here.

A: you don't need children watcher, make the parentNode implement watcher
public void checkForChanges() throws KeeperException, InterruptedException { zookeeper.getChildren("/parent",this); }


text:
Q: How HTTP.sys forward request to worker process I wanted to get an overview of the way HTTP.sys forwards request to work process in IIS 7.0 and above. For that purpose I read the post at http://www.iis.net/learn/get-started/introduction-to-iis/introduction-to-iis-architecture. However, there are two points in this post that seem to be contradicting and is confusing me.
Point 1: 2nd bullet point mentioned under section "Hypertext Transfer Protocol Stack (HTTP.sys)" is as follows.
Kernel-mode request queuing. Requests cause less overhead in context switching because the kernel forwards requests directly to the correct worker process. If no worker process is available to accept a request, the kernel-mode request queue holds the request until a worker process picks it up.
My conclusion according to this point is as follows:
HTTP.sys forwards request "directly" to worker process bypassing the WWW service. In case no worker process is available, HTTP.sys queues the request in kernel-mode request queue while WAS service starts a new worker process. This worker process then picks up requests from the kernel-mode queue on its own.
Point 2: Process Management subsection under the section "Windows Process Activation Service(WAS)" is as follows.
WAS manages application pools and worker processes for both HTTP and non-HTTP requests. When a protocol listener picks up a client request, WAS determines if a worker process is running or not. If an application pool already has a worker process that is servicing requests, the listener adapter passes the request onto the worker process for processing. If there is no worker process in the application pool, WAS will start a worker process so that the listener adapter can pass the request to it for processing.
My conclusion according to this point is as follows:
HTTP.sys forwards request to the worker process "through WWW service" as that is the listener adapter. In case no worker process is available, HTTP.sys queues the request in kernel-mode request queue while WAS service starts a new worker process. The request from the kernel-mode queue is then picked up by WWW service and forwarded to the worker process.
Could anyone please let me know which of my above two conclusions is correct? If both are incorrect, please let me know the right flow.

A: I dont think either is correct. I was also trying to figure out the exact workings and finally found the HTTP Server API, https://learn.microsoft.com/en-us/windows/desktop/http/http-version-2-0-architecture.
"HTTP.sys forwards request to the worker process "through WWW service" as that is the listener adapter." From the documentation above, and here https://learn.microsoft.com/en-us/windows/desktop/http/process-isolation, you can seen the HTTP Kernel Mode(http.sys) routes requests to queues that are associated with urls. The queue would have been configured when the app pool was created in iis mgr and the urls would have been associated with the queue when you create a website in IIS mgr and tie the website to a pool. http.sys puts stuff in queues. The app pool process processes stuff from the queues. No direct interaction between http.sys and worker process.
"In case no worker process is available,..." this is not true either from the Process Isolation documentation above:
Creator or controller process: The controller process can run with, or without, administrative privileges to monitor the health and configure the service. The controller process typically creates a single server session for the service and defines the URL groups under the server session. The URL group that a particular URL is associated with determines which request queue services the namespace denoted by the particular URL. The controller process also creates the request queue and launches the worker processes that can access the request queue.
Worker Process: The worker processes, launched by the controller process, perform IO on the request queue that is associated with the URLs they service. The web application is granted access to the request queue by the controller process in the ACL when the request queue is created. Unless the web application is also the creator process, it does not manage the service or configure the request queue. The controller process communicates the name of the request queue to the worker process and the worker process opens the request queue by name. Worker processes can load third party web applications without introducing security vulnerabilities in other parts of the application.
So the controller process would create the workers. This is without a doubt the WAS, exactly how it detects when to create a process is not defined, but its definitely the "controller process" spoken about above.
Interesting, in asp.net core you can run your app on top of http.sys, Microsoft.AspNetCore.Server.HttpSys. Interntally it uses this api to configure things. https://github.com/aspnet/HttpSysServer/blob/master/src/Microsoft.AspNetCore.Server.HttpSys/NativeInterop/HttpApi.cs.
This documentation cleared up a lot of confusion for me. I hope it helps.