text:
Q: upsampling convolution has no parameters I have read many papers where convolutional neuronal networks are used for super-resolution or for image segmentation or autoencoder and so on. They use different kinds of upsampling aka deconvolutions and a discussion over here in a different question.
Here in Tensorflow there is a function
Here in Keras there are some
I implemented the Keras one:
 x = tf.keras.layers.UpSampling1D(size=2)(x)

and I used this one stolen from an super-resolution repo here:
class SubPixel1D(tf.keras.layers.Layer):
  def __init__(self, r):
      super(SubPixel1D, self).__init__()
      self.r = r

  def call(self, inputs):
      with tf.name_scope('subpixel'):
          X = tf.transpose(inputs, [2,1,0]) # (r, w, b)
          X = tf.compat.v1.batch_to_space_nd(X, [self.r], [[0,0]]) # (1, r*w, b)
          X = tf.transpose(X, [2,1,0])
      return X

But I realized that both don't have parameters in my model summary. Is this not necessary for those functions to have parameters so they can learn the upsampling??

A: In Keras Upsampling simply copies your input to the size provided. you can find the documentation here, So there is no need to have parameters for these layers.
I think you have confused upsampling with Transposed Convolution/ Deconvolution.

A: In UpSampling1D, if you look at the actual source code on github, the up-sampling involved is either nearest neighbor or bi-linear. And both these interpolation schemes have no learning parameters, like any weight or biases, unless and until they are followed by a convolution layer.
Since in Subpixel1D also no convolution layer or learnable layers is used, hence no training parameters


text:
Q: GCD - does a serial queue require an `NSLock` or a memory barrier to synchronize work? I read the Apple documentation on GCD queues and started to wonder what happens if I lets say modify an instance member of type NSMutableArray which is not thread safe in a serial queue? The serial queue would guarantee me that I execute the operations serially, but I still feel that I need to either do an @syncrhonized block or other technique to force a memory barrier, since as far as I understand the tasks on my serial queue can be invoked on different threads. Is that correct? Here is a simple example:
@interface Foo : NSObject

-(void)addNumber:(NSNumber*)number;
-(void)printNumbers;
-(void)clearNumbers;

@end

@implementation Foo
{
   dispatch_queue_t _queue;
   NSMutableArray<NSNumber*>* _numbers;
}

-(instancetype)init
{
   if (self = [super init])
   {
       _queue = dispatch_queue_create(NULL, NULL);
       _numbers = [NSMutableArray array];
   }
   return self;
}

-(void)addNumber:(NSNumber*)number
{
   dispatch_async(_queue,
   ^{
       [_numbers addObject:number];
   });
}

-(void)printNumbers
{
   dispatch_async(_queue,
   ^{
       for (NSNumber* number in _numbers)
       {
           NSLog(@"%@", number);
       }
   });
}

-(void)clearNumbers
{
   dispatch_async(_queue,
   ^{
       _numbers = [NSMutableArray array];
   });
}
@end;

As far as I understand I could run into memory issues here if I call the member methods from arbitrary threads? Or GCD gives some guarantees under the hood, why I do not need to force memory barriers? Looking at the examples I did not find such constructs anywhere, but coming from C++ it would make sense to touch the member variable under a lock.

A: If your queue is a serial queue, it will only allow one operation at a time, no matter which thread it's running on. Therefore, if every access to a resource occurs on the queue, there's no need to further protect that resource with a lock or a semaphore. In fact, it's possible to use dispatch queues as a locking mechanism, and for some applications, it can work quite well.
Now if your queue is a concurrent queue, then that's a different story, since multiple operations can run at the same time on a concurrent queue. However, GCD provides the dispatch_barrier_sync and dispatch_barrier_async APIs. Operations that you start via these two function calls will cause the queue to wait until all other operations finish before executing your block, and then disallow any more operations from running until the block is finished. In this way, it can temporarily make the queue behave like a serial queue, allowing even a concurrent queue to be used as a sort of locking mechanism (for example, allowing reads to a resource via a normal dispatch_sync call, but doing writes via a dispatch_barrier_async. If the reads occur very frequently and the writes very infrequently, this can perform pretty well).

A: The serial queue is a data lock, so no further locking / synchronization is needed, at least as far as this code is concerned. The fact that the same queue may be executed using different threads is an implementation detail about which you should not be thinking; queues are the coin of the realm.
There may, of course, be issues in regard to sharing the array between this queue and the main queue, but that's a different matter.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как читать заключение переменных в фигурные скобки и функции ()()? Смотрел в интернете пример применения Redux и там увидел такой код:
function mapStateToProps(state) {
  const { value } = state.counter;

  return { value };
}

export default connect(mapStateToProps)(ReduxCounter);

ReduxCounter - это react-компонент.
Память подсказывает что в JS 2 строка записана в ECMA 6 и это эквивалент:
const value = state.counter.value;

но вопрос в возвращаемом результате, который тоже заключен в фигурные скобки return { value }; ??
И второй вопрос - как понять запись connect(mapStateToProps)(ReduxCounter)?
Интересует последовательность действий понятным языком.

A: return { value };  - это всё равно что return {value: value};
connect(mapStateToProps)(ReduxCounter):
Функциия connect(mapStateToProps) возвращает другую функцию, которая тут же вызывается с аргументами (ReduxCounter)

function a(){
  return function(value){
      return {value}
  }
}

console.log(
  a()(2)
)


text:
Q: pandas .loc slower after join than after merge I have 2 large dataframes which I have previously outlined in this question Faster method to join and filter two overlapping DataFrame with extra shared variable.
As a continuation to that question, I have been trying to use a join instead of a merge to speed up the operation. The join does indeed work much faster than the merge, but now it seems bogged down in the .loc operation despite the dataframes being sorted seem nearly identical, at least in terms of column names and df sizes.
Here is an example of the two different approaches I have taken:
df = pd.merge(df2,df1,how='left',left_on=['CP_ID','Con'], \
                      right_on=['CP_ID','Con'])
df = df.loc[(df.Timestamp>df.dStart)&(df.Timestamp<df.dEnd)]

and

df2_test = df2.copy()
df1_test = df1.copy()

df11 = df1_test.set_index(['CP_ID','Con'])
df22 = df2_test.set_index(['CP_ID','Con'])
df_test2 = df22.join(df11, how='left')
df_test2.reset_index(inplace=True)
df_test2 = df_test2.loc[(df_test2.Timestamp>df_test2.dStart)&(df_test2.Timestamp<df_test2.dEnd)]

I see a 3x speed improvement in the merge/join operation, but a 10x slow down in the .loc operation if I use the join instead of merge, which essentially cancels out any gains overall. Can anyone explain this? I have manually inspected the dataframes after the join/merge, and I can't really tell any difference that would be causing this huge slow down in the .loc


text:
Q: How can I compare two different fields in two collections? Is there a simple way that I can compare two collections?
What I have is the following:
ICollection<AnswerDetail> rfc; // Responses from Client
ICollection<AnswerDetail> afd; // Answer from Database

I would like to have a way to compare the two collections and check if
the value of the Response field in rfc matches the value of the Correct field in afd
Here's the AnswerDetail class:
public class AnswerDetail
{
    public int AnswerId { get; set; }
    public string Text { get; set; }
    public Nullable<bool> Correct { get; set; }
    public Nullable<bool> Response { get; set; }
}

A: If collections are already ordered you can implement a comparer:
    public class FancyComparer : IEqualityComparer<AnswerDetail>
    {
        public bool Equals(AnswerDetail x, AnswerDetail y)
        {
            return x.AnswerId == y.AnswerId && x.Correct == y.Response;
        }

        public int GetHashCode(AnswerDetail obj)
        {
            return obj.AnswerId;
        }
    }

And then use sequence equals:
var equlas = afd.SequenceEqual(rfc, new FancyComparer());

If they are not ordered, then you'll have to order them first (using OrderBy, for example)
var equals = afd.OrderBy(x => x.AnswerId)
                .SequenceEqual(rfc.OrderBy(x => x.AnswerId), new FancyComparer());

A: bool RfcEqualsAfd=rfc.All(q=>
                         afd.Any(a=>
                                q.Response==a.Correct &&
                                q.AnswerId==a.AnswerId
                                )
                         );


text:
Q: cannot push element to an array I'm trying to push elements to the end of the array called "toServiceSubCatNamesList"
this.toServiceSubCatNamesList.push(this.loadServiceTypes.serviceTypes[j]);

The structure of "loadServiceTypes" array is:
{
"serviceTypes": [
    {
        "service_type_id": 1,
        "service_type_name": "Cutting",
        "service_type_price": "3000.00",
        "created_at": null,
        "updated_at": null,
        "pivot": {
            "service_service_type_service_id": 1,
            "service_service_type_service_type_id": 1
        }
    }
  ]
}

The structure of "toServiceSubCatNamesList" array is:
toServiceSubCatNamesList > 0:Object
                                 created_at:null
                                 pivot:Object
                                 service_type_id:1
                                 service_type_name:"Washing"
                                 service_type_price:"3000.00"
                                 updated_at:null
                                 __proto__:Object
                                 length:1
                                 __proto__:Array(0)

When I'm doing this It will gives the error of "TypeError: Cannot read property 'service_type_name' of undefined".Any suggetions to overcome this!


text:
Q: bad quality of a surface content after scaling or as a result of Z-translate with perspective option var mainContext = Engine.createContext();
mainContext.setPerspective(500);

var surface = new Surface({
    content: 'im a content',
    size: [200, 200]
});
var modifier = new StateModifier();
mainContext.add(modifier).add(surface);

in onClick event the following code results in very bad quality of displayed content 'im a content':
1) modifier.setTransform(Transform.translate(0, 0, 300));
or
2) modifier.setTransform(Transform.scale(3, 3, 1));
What Im doing wrong here?
How to force famo.us to rerender content after transformations for better quality?

A: This is not so much an issue of Famo.us as it is the browser. See the issue here.
Windows Chrome browser?
I tested it using this code. Example jsBin

*

*Chrome (39.0.2171.95) Not Working

*Firefox (31) Working

*IE (11.0.15) Working
  var mainContext = Engine.createContext();
  mainContext.setPerspective(1000);

  var surface = new Surface({
    content: 'Famous Application',
    size: [200, 200],
    transform: Transform.scale(1, 1, 1),
    properties: {
      fontSize: '2em',
      backgroundColor: 'rgba(0, 0, 0, 0.4)'
    }
  });
  var modifier = new Modifier({
    origin: [0, 0],
    align: [0, 0]
  });
  mainContext.add(modifier).add(surface);

  surface.on('click', function() {
    console.log('clicked');
    if (!surface.clicked) {
      //modifier.setTransform(Transform.translate(0, 0, 300));
      modifier.setTransform(Transform.scale(3, 3, 1), {duration: 300}, function(){surface.setContent('');surface.setContent('
Scaled Now!
');});

    }
    else {
      modifier.setTransform(Transform.scale(1, 1, 1), {duration: 300}, function(){surface.setContent('');surface.setContent('Famous Application');});
    }
    surface.clicked = !surface.clicked;
  });


text:
Q: How to select count using sub-select in sql? I'm trying to get a count of an inner join. Should I use a sub-select?
const users = db.queryEntries(
  "SELECT username, created_at, email, phone FROM users WHERE contactme = 1 ORDER BY created_at DESC"
);

There's another table called searches that has a user_id attribute. I want to get the number of searches for each user returned in the first query.
Would be something like:
SELECT count(*) as total
FROM searches
WHERE searches.user_id = user.id

...such that the first query will return total for each user

A: if I understand correctly, you can try to use COUNT with GROUP BY in subquery, then do JOIN by userid
SELECT u.username, u.created_at, u.email, u.phone ,s.total
FROM users u
INNER JOIN (
    SELECT count(*) as total,user_id
    FROM searches
    GROUP BY user_id
) s ON s.user_id = u.id
WHERE u.contactme = 1
ORDER BY u.created_at DESC

A: This can be done done with the GROUP BY clause, COUNT and a LEFT JOIN. No need to use a sub-select.
SELECT users.username, users.created_at, users.email, users.phone, COUNT(searches.user_id) AS total
FROM users
LEFT JOIN searches on users.id = searches.user_id
GROUP BY users.id, users.username, users.created_at, users.email, users.phone

A: SELECT COUNT (*)
FROM
(SELECT *
FROM USERS U INNER JOIN SEARCHES S ON S.USER_ID = U.USER_ID ) d


text:
Q: Ignoring empty data in node selection I am trying to figure out how to ignore empty returns for Xslt.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" ><xsl:output indent="no" method="text"/>
 <xsl:strip-space elements="*" />
 <xsl:template match="/">
Famous Mountains of the World
<xsl:apply-templates />
</xsl:template><xsl:template match="mountain[string-length() !=0]">
Mountain Name:<xsl:value-of select="name[@language='English']"/>
Mountain Name:(<xsl:value-of select="name[@language='PigLatin'] "/>)</xsl:template>
</xsl:stylesheet>

As you can see, it has a selector for piglatin and I am trying to get it to not return blank data when the nodes doesn't have a piglatin option. Here is the xml I am formatting.
<?xml version="1.0" encoding="UTF-8"?>
<!-- Note: This is a comment-->
<?xml-stylesheet type="text/xsl" href="Asg08.xsl"?>
<FamousMountains>
  <mountain>
    <name language="English">Mount Everest</name>
    <name language="PigLatin">ountMa verestEa</name>
    <location>Nepal</location>
    <height units="feet">29035</height>
  </mountain>
  <mountain>
    <name language="English">Mount Ranier</name>
    <location>Washington</location>
    <height units="feet">14411</height>
  </mountain>
  <mountain>
    <name language="English">Mount St. Helens</name>
    <location>Washington</location>
    <height units="feet">8364</height>
  </mountain>
  <mountain>
    <name language="English">Mount Washington</name>
    <name language="PigLatin">ountMa ashingtonWa</name>
    <location>New Hampshire</location>
    <height units="feet">6288</height>
  </mountain>
  <mountain>
    <name language="English">Mount Bonnell</name>
    <name language="PigLatin">ountMa onnellBa</name>
    <location>Austin</location>
    <height units="feet">800</height>
  </mountain>
  <mountain>
    <name language="English">Mount Vesuvius</name>
    <name language="PigLatin">ountMa esuviusVa</name>
    <location>Italy</location>
    <height units="feet">4203</height>
  </mountain>
  <mountain>
    <name language="English">Mount Etna</name>
    <name language="PigLatin">ountMa tnaEa</name>
    <location>Sicily</location>
    <height units="feet">10922</height>
  </mountain>
</FamousMountains>

with the output looking like that
Mountain Name: Mount Everest
Pig Latin Name: ountMa verestEa
Mountain Name: Mount Ranier
Mountain Name: Mount St. Helens
Mountain Name: Mount Washington
Pig Latin Name: ountMa ashingtonWa
Mountain Name: Mount Bonnell
Pig Latin Name: ountMa onnellBa
Mountain Name: Mount Vesuvius
Pig Latin Name: ountMa esuviusVa
Mountain Name: Mount Etna
Pig Latin Name: ountMa tnaEa

Any help or insight to what I am doing wrong would be appreciated.

A: Instead of outputting the value of the name elements in the template that matches "mountain", have separate templates for them
<xsl:template match="name[@language='English']">
Mountain Name: <xsl:value-of select="." />
</xsl:template>

<xsl:template match="name[@language='PigLatin']">
Mountain Name:(<xsl:value-of select="." />)
</xsl:template>

Then replace the xsl:value-of with xsl:apply-templates* in the main template
<xsl:apply-templates select="name[@language='English']" />
<xsl:apply-templates select="name[@language='PigLatin']" />

That way, if there is no such name, nothing is output.
Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" ><xsl:output indent="no" method="text"/>
  <xsl:strip-space elements="*" />
  <xsl:template match="/">
    Famous Mountains of the World
  <xsl:apply-templates />
  </xsl:template>

  <xsl:template match="mountain[string-length() !=0]">
    <xsl:apply-templates select="name[@language='English']" />
    <xsl:apply-templates select="name[@language='PigLatin']" />
  </xsl:template>

  <xsl:template match="name[@language='English']">
    Mountain Name: <xsl:value-of select="." />
  </xsl:template>

  <xsl:template match="name[@language='PigLatin']">
    Mountain Name:(<xsl:value-of select="." />)
  </xsl:template>
</xsl:stylesheet>

Note that if "English" always occurs before "Piglatin" in your XML, you could replace the two xsl:apply-templates with a single one
<xsl:apply-templates select="name" />


text:
Q: Unable to populate tick mark on angular checkbox I have angular code something like this: and I want to populate checkbox ticked for the option which are default selected

export class InformationComponent implements OnInit{

dataIds: FormControl;
@Input()
requestBody:Request;
requestForm: FormGroup;

constructor(private _formBuilder: FormBuilder){}

ngOnInit(){
 this.dataIds =  new FormControl(this.requestBody.dataIds);
 this.requestForm = this._formBuilder.group({
 dataIds: this.dataIds;
 })

}

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<form [formGroup]="reqForm" #mainForm>
 <div>
   <app-data-list [dataIds]="dataIds" [disabled]="disabled"> </app-data-list>
 </div>
</form>

and below is my app-data-list component

export class EntityListComponent implemments OnInit, OnDestroy{

@Input()
public disabled:boolean;
public entitiesFilter:FormControl =  new FormControl();

protected entityList = new RequestEntity[];
@Input()
public dataIds:FormControl;

@ViewChild('multiSelect', {static:true}) multiselect:MatSelect;
protected _onDestroy = new Subject<void>();

public filteredEntityList:ReplaySubject<RequestEntity[]> = new ReplaySubject<RequestEntity[]>

ngOnInit(){
 this.myservice.getData().subscribe((resp:RequestEntity[])=>{
entityList = resp;
})
this.filteredEntityList.next(this.entityList.slice());
this.entitiesFilter.valueChanges.pipe(takeUntil(this._onDestroy)).subscribe(() => { this.filterEntitiesList();});
}

ngAfterViewInit(){
this.setInitialValue();
}

setInitialValue(){
this.filteredEntitiesList.pipe(take(1), takeUntil(_onDestroy)).subscribe(() => {
this.multiSelect.compareWith =(a:RequestEntity, b:RequestEntity) => a && b && a.entity == b.entity;
})
}
}
<div [formGroup]="form">
  <mat-form-field>
    <mat-label> Data ids</mat-label>
     <mat-select [formControl]="dataIds" [multiple]="true" #multiSelect [disabled]="disabled">
       <ngx-mat-select-search [formControl]="entitiesFilter" placeholderLabel="Search">
       </ngx-mat-select-search>
       <mat-option *ngFor="let entity of filterdEntitiesList |async" [value]"entity"> {{entity?.entity?.entityName}} </mat-option>
     </mat-select>
  </mat-form-field>
</div>

but my code is not pre populating the checked option against selected dataIds from back end but I had similar snippet in my code which does exactly same thing


text:
Q: Randomizing the order of an arrayList The goal of this project is to take in a matrix of courses with prerequisites and print out a schedule with no prereq conflicts.
I have gotten as far as adding the courses to the ArrayList of courses and printing it all out, however, im having issues doing a random restart on the ArrayList. I have tried swapping the indexes of the items in the array (although i don't know if im doing it correct), and I have also tried doing a collections.sort() on the ArrayList.
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

// Class DelivC does the work for deliverable DelivC of the Prog340

public class DelivC {

    File inputFile;
    File outputFile;
    PrintWriter output;
    Graph g;
    Node n;
    Edge e;
    int conflicts = -1;
    int counter = 0;
    int minConflicts = Integer.MAX_VALUE;
    String sem1 = "20203: ";
    String sem2 = "20205: ";
    String sem3 = "20211: ";
    String sem4 = "20213: ";
    String sem5 = "20215: ";
    String sem6 = "20221: ";
    String sem7 = "20223: ";
    ArrayList<Node> courseArray = new ArrayList<Node>();

    public DelivC(File in, Graph gr) {
        inputFile = in;
        g = gr;

        // Get output file name.
        String inputFileName = inputFile.toString();
        String baseFileName = inputFileName.substring(0, inputFileName.length() - 4); // Strip off ".txt"
        String outputFileName = baseFileName.concat("_out.txt");
        outputFile = new File(outputFileName);
        if (outputFile.exists()) { // For retests
            outputFile.delete();
        }

        try {
            output = new PrintWriter(outputFile);
        } catch (Exception x) {
            System.err.format("Exception: %s%n", x);
            System.exit(0);
        }

        /**
         * DELIVERABLE C.
         */

        // ADDING COURSES TO COURSEARRAY
        for (int i = 0; i < g.nodeList.size(); i++) {
            courseArray.add(g.nodeList.get(i));
        }

        while (counter < 10) {// conflicts != 0) {
            conflicts = 0;
            // SETTING SEMNUM AND SEM STRING
            for (int i = 0; i < g.nodeList.size(); i++) {
                if (i < 3) {
                    g.nodeList.get(i).setSemNum(1);
                    ;
                    sem1 += g.nodeList.get(i).getName() + " ".toString();
                } else if (i < 6) {
                    g.nodeList.get(i).setSemNum(2);
                    ;
                    sem2 += g.nodeList.get(i).getName() + " ".toString();
                } else if (i < 9) {
                    g.nodeList.get(i).setSemNum(3);
                    ;
                    sem3 += g.nodeList.get(i).getName() + " ".toString();
                } else if (i < 12) {
                    g.nodeList.get(i).setSemNum(4);
                    ;
                    sem4 += g.nodeList.get(i).getName() + " ".toString();
                } else if (i < 15) {
                    g.nodeList.get(i).setSemNum(5);
                    ;
                    sem5 += g.nodeList.get(i).getName() + " ".toString();
                } else if (i < 18) {
                    g.nodeList.get(i).setSemNum(6);
                    ;
                    sem6 += g.nodeList.get(i).getName() + " ".toString();
                } else if (i < 21) {
                    g.nodeList.get(i).setSemNum(7);
                    ;
                    sem7 += g.nodeList.get(i).getName() + " ".toString();
                }
            }

            // CHECKING FOR CONFLICTS IN EDGE
            for (int k = 0; k < g.edgeList.size(); k++) {

                String edgeLabel = g.getEdgeList().get(k).getLabel();
                if (edgeLabel == ">") {
                    if (g.getEdgeList().get(k).getHead().getSemNum() >= g.getEdgeList().get(k).getTail().getSemNum()) {
                        conflicts++;
                    }
                } else if (edgeLabel == ">=") {
                    if (g.getEdgeList().get(k).getHead().getSemNum() > g.getEdgeList().get(k).getTail().getSemNum()) {
                        conflicts++;
                    }
                }
            }

            // PRINTING OUT SCHEDULE
            // if (minConflicts > conflicts) {
            System.out.println(courseArray);
            System.out.println(" ");
            System.out.println("There are currently " + conflicts + " conflicts.");
            System.out.println(sem1);
            System.out.println(sem2);
            System.out.println(sem3);
            System.out.println(sem4);
            System.out.println(sem5);
            System.out.println(sem6);
            System.out.println(sem7);
            System.out.println(" ");
            System.out.println(" ");
            // minConflicts = conflicts;
            // }

            // RESETS THE SEMESTER STRINGS
            sem1 = "20203: ";
            sem2 = "20205: ";
            sem3 = "20211: ";
            sem4 = "20213: ";
            sem5 = "20215: ";
            sem6 = "20221: ";
            sem7 = "20223: ";

            // RESETS THE CONFLICTS
            if (conflicts == 0) {
                conflicts = 0;
            } else {
                conflicts = -1;
            }
            counter++;
            // conflicts = 0;

            // RANDOMLY ASSIGNS NEW SEMESTERS TO EACH COURSE
            // randomRestart();
            Collections.sort(courseArray);
        }

    }

    public void randomRestart() {
        Random r = new Random();
        for (int i = 0; i < courseArray.size(); i++) {
            int nodeIndex = courseArray.indexOf(i);
            int swapIndex = r.nextInt(courseArray.size());
            Node currentNode = courseArray.get(i);
            Node swapNode = courseArray.get(swapIndex);
            Node tempNode = currentNode;
            currentNode = courseArray.get(swapIndex);
            swapNode = tempNode;

        }
    }

}


text:
Q: Does `branch..merge` represent a remote tracking branch or an upstream branch? Does branch.<name>.merge represent a remote tracking branch or an upstream branch?

*

*Version Control with Git says

But how did Git know to merge those particular branches? The answer
  comes from the configuration file:
[branch "master"]
        remote = origin
        merge = refs/heads/master

Paraphrased, this gives Git two key pieces of information: When master
  is the current, checked out branch, use origin as the default remote
  from which  to  fetch  updates  during  a  fetch  (or  pull).
  Further,  during  the  merge  step  of git pull, use refs/heads/master
  from the remote as the default branch to merge into this, the master
  branch.

The quote says "during  the  merge  step  of git pull, use
refs/heads/master from the remote as the default branch to merge
into this, the master  branch." It seems to me that
branch.<name>.merge represents a remote tracking branch instead of
an upstream branch.
But refs/heads/master in merge = refs/heads/master doesn't look
like a remote tracking branch (which should look like
refs/remotes/<remote>/master), but a  topic branch, so it seems
only an upstream branch to me.

*The manpage of git config says

branch.<name>.merge

Defines, together with branch..remote, the upstream branch for
  the given branch.

It seems to say branch.<name>.merge represents an upstream branch
instead of a remote tracking branch.

*Is it possible that branch.<name>.merge implies both a remote
tracking branch and an upstream branch? I don't think it is
possible, because a remote tracking branch and its corresponding
upstream branch(es) can have different basenames, according to how
remote.<remote>.fetch is configured.

A: In short, branch.<name>.merge contains the name of the remote branch on the remote server: it is the upstream branch.
How to convince yourself this is true:
Assuming branch origin/dev1 exists but not the local dev1 yet, run this:
git checkout dev1
git branch -m dev1 dev2

These commands set up dev1 as having origin/dev1 as its upstream, then renames it as dev2.
The results in my .git/config is this:
[branch "dev2"]
    remote = origin
    merge = refs/heads/dev1

Now, refs/heads/dev1 is something that does not exist anywhere in my sandbox, only on the remote.
Some further clarification of names, based on the discussion in the comments:
local branch: master or dev2 are local branches that can get updated from their upstream branch.
remote-tracking branch: origin/master or refs/remotes/origin/master is a pointer stored locally to the state of the remote branch at the time of the last git fetch or git pull.
upstream branch: this is the real remote branch, on the remote server itself, not something local.

A: git config remote.origin.fetch will show you the "refspec" that maps refnames on the origin remote to the local "remote-tracking branch" refs.
The default is
+refs/heads/*:refs/remotes/origin/*

and it says fetch all the refs on origin that start "refs/heads/" and substitute the *'d text in the local rewrite, so refs/heads/master the * is master, and that's what gets subbed in for the * in the local ref, the "remote-tracking branch" ref 1.
The config file specifies which repository a branch's upstream came from and what the refname in that repository is.  When you go to rebase or pull or merge and take the implicit upstream, Git looks at the branch name and the refspec for its source repo, usually origin, and figures out what ref that would map to in this repository.
So
[branch "master"]
        remote = origin
        merge = refs/heads/master

[remote "origin"]
        url = git://github.com/git/git
        fetch = +refs/heads/*:refs/remotes/origin/*

the local branch master tracks origin's branch master, and fetching from origin maps that branch there to refs/remotes/origin/master here, so that's the history rebase and pull and probably some others examine by default to find where or whether the histories have diverged.

1The leading + just means "don't complain if the fetch abandons history", which is of course exactly how you want fetch to operate when you're simply tracking what's going on with a remote's refs. See the fetch docs for more of its default behavior, e.g. there's times when you want tags fetched, times when you don't


text:
Q: Application.DoEvents() called constantly while application is running? I was trying to add a form cashing module for my application and i implemented this msdn sample: Form Stacking and Caching
For those who cannot download the sample, this is the class that contains the piece of code i'm referring to:
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Threading;

namespace GUIFramework {
    public class FormStack : CollectionBase {
        private System.Collections.ArrayList stack = new ArrayList();

    public void Run() {
        do {
            System.Windows.Forms.Application.DoEvents();
        } while(List.Count > 0);
    }

    public void Stop() {
        // nicely destroy each Form
        foreach(StackForm sf in List) {
            sf.Dispose();
        }
        // clear the list to kill the message pump in Run()
        List.Clear();
    }

    public void Push(Type FormType) {
        // only allow 1 Push at a time to maintain cache and stack itegrity
        Monitor.Enter(this);

        foreach(StackForm sf in List) {
            if(sf.GetType().Name.Equals(FormType.Name)) {
                // form is cached so display cached version
                sf.Visible = true;

                // add it to the stack
                stack.Add(FormType.Name);

                return;
            }
        }

        // the Form wasn't cached, so create it
        StackForm form = Preload(FormType);

        // display it
        form.Visible = true;

        // add a close event handler
        form.FormClosed += new FormClose(form_FormClosed);

        // add it to the stack
        stack.Add(FormType.Name);

        Monitor.Exit(this);
    }

    public StackForm Preload(Type FormType) {
        StackForm form = (StackForm)Activator.CreateInstance(FormType);

        // get data on a separate thread
        form.LoadData();

        // build the form
        form.InitializeComponent();

        // wait for the data thread to finish
        form.threadRunning.WaitOne();

        // now populate the controls with any retrieved data
        form.Populate();

        form.MinimizeBox = false;  // required to get close event on PPC!

        // add it to the cache
        List.Add(form);

        return form;
    }

    public void Pop(uint FormsToPop) {
        if(stack.Count <= FormsToPop) {
            throw new Exception("You cannot Pop the entire stack!");
        }
        else {
            // remove from stack but not cache
            for(int i = 0 ; i < FormsToPop ; i++) {
                stack.RemoveAt(stack.Count - 1);
            }

            foreach(StackForm sf in List) {
                // find the last form in the stack
                if(sf.GetType().Name.Equals(stack[stack.Count - 1])) {
                    // make it visible
                    sf.Visible = true;
                }
            }
        }
    }

    private void form_FormClosed() {
        Pop(1);
    }

    public override string ToString() {
        string message = "There are " + List.Count.ToString() + " forms cached\r\n";
        message += "Stack contents:";

        for(int i = stack.Count - 1 ; i >= 0 ; i--) {
            message += "\r\n" + stack[i].ToString();
        }

        return message;
    }
}
}

The Run() method is calling constantly  Application.DoEvents() while the application is runnning. I find it hard to believe that this is a good thing for the application. I'd love to hear other opinions about this. Thanks.

A: First you need to understand how WinForms apps work in general.  Way down deep in the bowels of the Application.Run call is a piece of code often referred to as a message pump.  This is an infinite loop that is calling GetMessage, TranslateMessage and DispatchMessage.  Application.DoEvents, in essence, calls for once cycle of that loop. The DoEvents loop you're looking at would simply be doing this operation.
Now why, exactly, that call is even needed I can't honestly say. That's pretty bad since I wrote the code, but in my defense, this code is nearly a decade old and I can barely remember what I did last week.
If you remove the loop, what happens?  I'm not seeing anything that indicates that you'd get drawing artifacts or failures to draw (which is the typical reason for adding the call), but this code was also written aganst CF 1.0, so it may well have been to overcome a runtime limitation.
For what it's worth, I revisited and rewrote the code in 2009 and the rewrite doesn't have the loop (or even a Run method for that matter).
BTW, there's a bug in Push that I see.  The foreach loop has a return without doing a Monitor.Exit.  I'd probably rewrite that method to use a lock or a finally block to call Monitor.Exit.


text:
Q: How can I change (not reset) another user's Windows password? I'm trying to change the password of a local account on a non-domain Windows 10 PC.
Logging in as the user to do the change is a poor solution because:

*

*Local login is denied for the account

*Entering the password into the login screen would be difficult due to its length and presence of characters not on a standard keyboard

I would have normally used the "Change a password" option on the Ctrl + Alt + Del screen (it's not just for your account), but it doesn't show up for me. The group policy setting that controls whether it's shown is set appropriately. A quick experiment seems to suggest that it's always hidden when logged in with a Microsoft account.


text:
Q: Removing ThinkPoint malware from a Windows 7 machine I have a Windows 7 box infected with the fake Thinkpoint anti-malware program. I do not have  of the admin password on this computer. I did find what appears to be some good instructions at BleepingComputer.com to remove this, but am unsure on how to proceed.

*

*Has anyone successfully removed this malware ( if so, can you recommend steps )

*If I need to get into an admin account on Win 7, what is the best way? I have used Ultimate Boot CD in the past on XP boxes, but have not done so on 7 yet.

A: First thing is to get into safe mode.  To do this, while the PC is booting up, press F8.  A list of startup options should be listed.  CHoose Safe Mode.
How to remove ThinkPoint manually:
Manual removal of ThinkPoint is a feasible objective if you have sufficient expertise in dealing with program files, processes, .dll files and registry entries.
The files to be deleted are listed below:
* %UserProfile%\Application Data\hotfix.exe
* %UserProfile%\Application Data\thinkpoint.exe

The registry entries that need to be removed are as follows:
* HKEY_CURRENT_USER\Software\PAV
* HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run "thinkpoint"
* HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Winlogon "Shell" = "%Documents and Settings%\[UserName]\Application Data\hotfix.exe"

(taken from: http://remove-malware.net/how-to-remove-thinkpoint-rogue-anti-spyware/)


text:
Q: Visual Paradigm: Underline togetherness in class diagram I have to create a class diagram with different design patterns inside. I would like to underline the togetherness of the classes belonging to the same design pattern.
What is the "official" or best way in UML to achieve this? I have to use Visual Paradigm and found a solution using packages.

But these packages seems to be very unhandy. I need something more freeform like. I think about just using different background colors for the different patterns.

A: The coloring of element is not the concern in UML as it won't affect the model structure and their relationships. Specifying different color is a good way for visualize categorize your elements in diagram level (same element on different diagram can have different presentation setting). If you want to categorize the elements in model level then you may consider to use stereotypes plus stereotype based presentations so that elements applying the stereotype can automatically inherit the presentation settings (see https://www.visual-paradigm.com/tutorials/stereotypeappearance.jsp)


text:
Q: Is there a list of what CSS styles cascade? CSS float does not cascade In the following example, the child divs one and two have the font-style of the parent but do not have the float style.  Is there a list of which styles should cascade and which will not?
Link to jsfiddle demo
<!DOCTYPE html>

    parent

      one

      two


text:
Q: Karate UI - Find html element via attribute where name contains special charatcers I am a big fan of Karate and exploring Karate UI for the end to end testing but stuck on one simple thing which is finding element by attribute where element contains special charatcers like below
<input autocapitalize="none" autocomplete="on" autocorrect="off" name="session[username_or_email]" spellcheck="false" type="text" dir="auto" data-focusable="true" class="r-30o5oe r-1niwhzg r-17gur6a r-1yadl64 r-deolkf r-homxoj r-poiln3 r-7cikom r-1ny4l3l r-1inuy60 r-utggzx r-vmopo1 r-1w50u8q r-1lrr6ok r-1dz5y72 r-1ttztb7 r-13qz1uu" value="">

This is the html snippet taken from Twitter login page. To get this control I have tried various options from mentioned below but couldn't able to find the control
Option 1
  Given driver 'https://twitter.com/login'
  And input('#session[username_or_email]',['aaaa@gmail.com',Key.ENTER], 100)
  And input('#session[password]',['asasas', Key.ENTER], 100)
  When submit().click("click('{span}Log in')")
  #* def elements = locateAll('{div}Click Me')
  Then locate('.css-901oao').exists

Option 2
  Given driver 'https://twitter.com/login'
  And input('input[name=session[username_or_email]]', 'aaaa@gmail.com')
  When submit().click("click('{span}Log in')")
  Then locate('.css-901oao').exists

I above tried options I couldn't able to find input and span button. Any help or pointer will be very helpful.

A: Here you go, note how you can use double-quotes when needed. I'm also giving an alternate approach, input[type=text] would have also worked:
* input("input[name='session[username_or_email]']", 'hello')
* input('input[type=password]', 'world')
* click('div[role=button]')


text:
Q: Make a bootable CD without ISO file but from a CD I have a Windows XP CD which I want to install on a USB Drive. However my own CD drive is broken.   I have a friend's laptop on which Windows 7 is installed (and no idea if it has a CDROM of not).
Please tell me how to do get the ISO from the CDROM to an USB pendrive?
I am using Debian 7

A: Here is a Windows based tool, ISO to USB. Also you could try using UNetbootin to write an ISO file to a USB thumb drive too. UNetbootin runs on all OSes.
excerpt from UNetbootin website

UNetbootin allows you to create bootable Live USB drives for Ubuntu, Fedora, and other Linux distributions without burning a CD. It runs on Windows, Linux, and Mac OS X. You can either let UNetbootin download one of the many distributions supported out-of-the-box for you, or supply your own Linux .iso file if you've already downloaded one or your preferred distribution isn't on the list.


text:
Q: Open Jquery accordion will not close when clicked there are a 4 accordions on the page, currently the open accordion only closes when you click on another accordion. I need to also close when you click on it. Here's the code I used.
$(document).ready(function() {

  var accordionEntries = document.querySelectorAll('.accordion-entry');
  var accordionImages = document.querySelectorAll('.accordion-image');

  for (var i = 0; i < accordionEntries.length; i++) {
    accordionEntries[i].dataset.target = 'accordion-image-' + i;
    accordionImages[i].classList.add('accordion-image-' + i);
  }

  $(document).on('click', '.accordion-header', function() {
    $('.accordion-open').removeClass('accordion-open')
    var parent = $(this).closest('.accordion-entry');
    parent.addClass('accordion-open');
    $('.' + parent.data('target')).addClass('accordion-open')
  })
})

A: The issue is caused by:
$('.accordion-open').removeClass('accordion-open')

which closes all accordion panels including the one you click on, then (re)opens the current one.
If you want to "toggle" the accordion panel, you need to check if the current panel is open first, then close it, then do nothing.
This can be achieved with:
$(document).on('click', '.accordion-header', function() {
    if ($(this).is(".accordion-open")) {
        $(this).removeClass("accordion-open");
        return;
    }
    ...


text:
Q: UNIQUE constraint failed: auth_profile.user_id Django Allauth I have a create_or_update_user_profile methods to the User model, whenever a save event occurs, but I added a new method set_initial_user_names to save a url, then now it shows me an error IntegrityError at /accounts/social/signup/ UNIQUE constraint failed: auth_profile.user_id
class UserProfile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=170, blank=True)
    avatar_url = models.CharField(max_length=256, blank=True)
    facebook_url = models.CharField(max_length=40, blank=True)
    twitter_url = models.CharField(max_length=40, blank=True)
    instagram_url = models.CharField(max_length=40, blank=True)
    web_url = models.CharField(max_length=40, blank=True)

    class Meta():
        db_table = 'auth_profile'

    def __str__(self):
        return self.user.username

@receiver(user_signed_up)
def set_initial_user_names(request, user, sociallogin=None, **kwargs):

    preferred_avatar_size_pixels = 256

    picture_url = "http://www.gravatar.com/avatar/{0}?s={1}".format(
        hashlib.md5(user.email.encode('UTF-8')).hexdigest(),
        preferred_avatar_size_pixels
    )

    if sociallogin:
        if sociallogin.account.provider == 'twitter':
            name = sociallogin.account.extra_data['name']
            user.first_name = name.split()[0]
            user.last_name = name.split()[1]

        if sociallogin.account.provider == 'facebook':
            user.first_name = sociallogin.account.extra_data['first_name']
            user.last_name = sociallogin.account.extra_data['last_name']

            picture_url = "http://graph.facebook.com/{0}/picture?width={1}&height={1}".format(
                sociallogin.account.uid, preferred_avatar_size_pixels)

        if sociallogin.account.provider == 'google':
            user.first_name = sociallogin.account.extra_data['given_name']
            user.last_name = sociallogin.account.extra_data['family_name']
            picture_url = sociallogin.account.extra_data['picture']

    profile = UserProfile(user=user, avatar_url=picture_url)
    profile.save()

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
    instance.userprofile.save()

IntegrityError at /accounts/social/signup/ UNIQUE constraint failed:
  auth_profile.user_id

A: You are trying to create user twice for the same user.
First one is created in create_or_update_user_profile handler right after user instance creation. Second is here:
@receiver(user_signed_up)
def set_initial_user_names(request, user, sociallogin=None, **kwargs):
    ...

    profile = UserProfile(user=user, avatar_url=picture_url)
    profile.save()  # <--- HERE

receiver(user_signed_up) is triggered after user object is already created, so user profile already was create by create_or_update_user_profile.
So to fix the problem you should use existing user profile, not create a new one:
@receiver(user_signed_up)
def set_initial_user_names(request, user, sociallogin=None, **kwargs):
    ...

    user.userprofile.avatar_url = picture_url
    user.userprofile.save()


text:
Q: no results when file is uppercase, python #!/usr/bin/python

catalog=open("physicsjournals2.txt","r")
catalogdata=catalog.readlines()

import glob
import os
import sys

directories = ['Analytica Chimica Acta' , 'Analytical and Bioanalytical Chemistry' , 'Journal of Chromatography A' , 'Sensors' , 'Talanta' , 'Carbohydrate Polymers' , 'Dyes and Pigments' , 'Food Chemistry' , 'Food Hydrocolloids' , 'Journal of Agricultural and Food Chemistry' , 'Microporous and Mesoporous Materials' , 'Dalton Transactions' , 'European Journal of Inorganic Chemistry' , 'Organometallics' , 'Angewandte Chemie - International Edition' , 'Journal of the American Chemical Society' , 'Tetrahedron - Asymmetry' , 'Biomacromolecules' , 'Journal of Organic Chemistry' , 'Organic Letters' , 'Advanced Materials' , 'Colloids and Surfaces B - Biointerfaces' , 'Journal of Physical Chemistry B' , 'Journal of Physical Chemistry C' , 'Langmuir' , 'Physical Chemistry Chemical Physics' , 'Journal of Membrane Science' , 'Macromolecular Bioscience' , 'Macromolecules' , 'Plasma Processes and Polymers']

catalogRecs = {}

for line in catalogdata:
    rec = "SO " + line.strip()
    catalogRecs[rec] = True

for folder in directories:
    savedrecfilenames = glob.glob(os.path.join(folder, "savedrecs (*).txt journals.txt"))
    #print savedrecfilenames
    for savedrecfilename in savedrecfilenames:
        i = 0
        savedrecfile=open(savedrecfilename,"r")
        fdata=savedrecfile.readlines()
        for line in fdata:
            name = line.strip()
            #print name
            if catalogRecs.has_key(name):
                i+=1
        #print savedrecfilename + " cited " + str(i) + " sources."
        ## veya sadece sayi outputlamak istersen
        print str(i)

when I use this code to get results, when the physicsjournals2 (txt) catalog has lines that are both uppercase and lowercase, I get results. However, I realized that these results are smaller numbers that they need to be, so I changed the catalog's lines to uppercase (letters in my savedrecs txt files are all uppercase, so it would be better matched), however I got zero results. Besides physicsjournals2, all my other uppercase catalogs yields results.
How must I modify the catalog physicsjournals2 ?

A: You can change this part of your code:
for line in catalogdata:
    rec = "SO " + line.strip().lower()
    catalogRecs[rec] = True


text:
Q: Uncountable set of irrational numbers closed under addition and multiplication? Is such a thing even possible?
There's not much to say really. Obviously if there was a set it would be full of transcendental numbers. This led me to think of a function generating transcendental numbers (given a transcendental number) closed under addition and multiplication - an easy one is algebraic function but these are clearly countable however. (Even worse the numbers would have to be algebraically independent which means you have to cut back on the algebraic functions.).
Any insights, guys?

A: Here's a more "consructive" answer, without using Axiom of Choice. Let ${\cal F}_n$ be the set of functions of $n$ variables corresponding to expressions using each variable once, with $+$ and $*$ (a convenient way to represent these is as trees where each leaf is one of the $n$ variables and each non-leaf node is labelled with either $+$ or $*$: in any case, there are finitely many for each $n$, and they can be enumerated).  Note that ${\cal F}_1$ consists of the one function $x \to x$. I will take $S = \bigcup_{n=1}^\infty \bigcup_{f \in {\cal F}_n} f(C, \ldots,C)$ for a suitable uncountable set $C$.  I need to ensure that for all $f \in {\cal F}_n$, $f(C,\ldots,C)$ does not contain any algebraic numbers.
Enumerate the triples
$(\alpha, n, f)$ where $\alpha$ is algebraic, $n$ is a positive integer and $f \in{\cal F}_n$, as $(\alpha_k, n_k, f_k)_{k=1}^\infty$.  $C$ will be obtained as a nested intersection $\bigcap_{k=0}^\infty C_k$, where $C_0 = [0,1]$,
each $C_k$ is the union of $2^k$ disjoint closed intervals, and each interval of $C_{k-1}$ contains two intervals of $C_{k}$.  These are to be chosen so that
$\alpha_k \notin f_k(C_{k},\ldots,C_k)$.  To do this, note that if we randomly choose  $x_i$ and $y_i$ in each interval of $C_{k-1}$, with probability $1$
none of the numbers $f(z_1,\ldots, z_{n_k})$ for $z_1, \ldots, z_{n_k} \in \{x_i: i=1..2^{k-1} \} \cup \{y_i: i =1..2^{k-1}\}$ is $\alpha_k$.  Taking $\epsilon > 0$  small enough, we can let $C_k$ be the union of the intervals $[x_i - \epsilon, x_i + \epsilon]$ and $[y_i - \epsilon, y_i + \epsilon]$ for $i=1 \ldots 2^{k-1}$, and this will have the required properties.

A: This is possible.
First, consider the set of all numbers of the form
$$
a_1\pi + a_2\pi^2 + \cdots + a_n\pi^n
$$
where $n \geq 1$, the coefficients $a_1,\ldots,a_n$ are non-negative integers, and at least one $a_i$ is positive.  This set is clearly closed under both addition and multiplication.  However, it is not uncountable.
We can make this set larger by adding another number.  For example, we can consider two-variable polynomials involving $\pi$ and $e$ with the same restrictions: there is no constant term, all of the coefficients are non-negative integers, and at least one of the coefficients is positive. Assuming that $\pi$ and $e$ are algebraically independent (which is not known), all of these polynomials are distinct and nonzero, so we get a larger set of transcendental numbers which is closed under addition and multiplication.  However, this set is still not uncountable.
To make an uncountable set that is closed under addition and multiplication, we must start with an uncountable set $S$ of algebraically independent transcendental real numbers.  It is known that such a set exists, since the transcendence degree of the real numbers over the rationals is uncountable.  If we now take all polynomials over the elements of $S$ satisfying the same conditions (no constant term, non-negative integer coefficients, at least one positive coefficient), the result will be an uncountable set of transcendental numbers that is closed under addition and multiplication.

A: Let $A_0$ be a transcendence basis for $\mathbb{R}$ over $\mathbb{Q}$, which already has size of the continuum, and let $$B_0=\{\text{finite sums of elements of }A_0\},$$
$$A_1=\{\text{finite products of elements of }B_0\},$$
$$B_1=\{\text{finite sums of elements of }A_1\},$$
$$\cdots$$
and $S=\bigcup_{n=0}^\infty A_n$. Then $S$ is closed under addition and multiplication by definition, $S$ is uncountable, and every element of $S$ is irrational because no algebraic relation holds between the elements of $A_0$ over $\mathbb{Q}$.
EDIT: This is the same as Jim's suggestion above, just phrased slightly differently.

A: To extend the comment above.
The property: "$S\subset \mathbb R\setminus\mathbb Q$ is closed under addition and multiplication" satisfies Zorn's lemma, so there must be a maximal such set $S$.
Maximality means that for any irrational number $x\notin S$, there must be a polynomial of the form $p(z)-q$ where $q\in \mathbb Q$ and $p(z)$ is a non-zero non-constant polynomial with coefficients in $(S\cup\{0\})\oplus\mathbb N)$ such that $x$ is a root of the polynomial.
But if $S$ is countable, then the set of such polynomials is countable, and therefore the set of such roots is countable.
So any maximal $S$ must necessarily be uncountable.
This can be extended to a more general theorem: If $K\subset \mathbb R$ is uncountable and closed under addition and multiplication, then there is an uncountable $S\subseteq K\setminus\mathbb Q$ which is closed under addition and multiplication.
Proof: Since $K$ is uncountable, it contains a transcendental number, so the positive polynomials in that transcendental form a subset of $K\setminus\mathbb Q$ closed under addition and multiplication.
As before, by Zorn's lemma, there must be a maximal set $S\subset K\setminus\mathbb Q$ closed, and, as before, if $S$ is countable, then you get a contradiction - there are too many elements of $K\setminus (S\cup\mathbb Q)$ and not enough polynomials with coefficients in $(S\cup\{0\})\oplus\mathbb N$.


text:
Q: How to solve a Initialization Failed for Singleton EJB I have a java EE project that is executed in a Glassfish 4.1 container using Eclipse Mars, using EJB injection. I have a Singleton EJB that initialize or update the database when application start
@Startup
@Singleton
public class DatabaseUpdater {

    private static final Logger LOG = Logger.getLogger(DatabaseUpdater.class.getName());

   /**
    * Initializes database process
    */
    @PostConstruct
    public void initialize(UserVO userVO) {
        // ... initialize code
    }
}

The project is executed in Eclipse Mars, using Debug on Server option, and it was working good. However yesterday I just tried to do this to start project, and deployment process failed in Eclipse. This exception stack appears:
2016-02-21T11:03:52.001-0500|Grave: Exception during lifecycle processing
javax.ejb.EJBException: javax.ejb.CreateException: Initialization failed for Singleton DatabaseUpdater
    at com.sun.ejb.containers.AbstractSingletonContainer$SingletonContextFactory.create(AbstractSingletonContainer.java:649)
    at com.sun.ejb.containers.AbstractSingletonContainer.instantiateSingletonInstance(AbstractSingletonContainer.java:389)
    at org.glassfish.ejb.startup.SingletonLifeCycleManager.initializeSingleton(SingletonLifeCycleManager.java:219)
    at org.glassfish.ejb.startup.SingletonLifeCycleManager.initializeSingleton(SingletonLifeCycleManager.java:180)
    at org.glassfish.ejb.startup.SingletonLifeCycleManager.doStartup(SingletonLifeCycleManager.java:158)
    at org.glassfish.ejb.startup.EjbApplication.start(EjbApplication.java:166)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
    at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:291)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:352)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:500)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.ejb.CreateException: Initialization failed for Singleton DatabaseUpdater
    at com.sun.ejb.containers.AbstractSingletonContainer.createSingletonEJB(AbstractSingletonContainer.java:476)
    at com.sun.ejb.containers.AbstractSingletonContainer.access$000(AbstractSingletonContainer.java:74)
    at com.sun.ejb.containers.AbstractSingletonContainer$SingletonContextFactory.create(AbstractSingletonContainer.java:647)
    ... 47 more
Caused by: java.lang.IllegalArgumentException: wrong number of arguments
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.sun.ejb.containers.interceptors.BeanCallbackInterceptor.intercept(InterceptorManager.java:1035)
    at com.sun.ejb.containers.interceptors.CallbackChainImpl.invokeNext(CallbackChainImpl.java:72)
    at com.sun.ejb.containers.interceptors.CallbackInvocationContext.proceed(CallbackInvocationContext.java:205)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:55)
    at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.sun.ejb.containers.interceptors.CallbackInterceptor.intercept(InterceptorManager.java:986)
    at com.sun.ejb.containers.interceptors.CallbackChainImpl.invokeNext(CallbackChainImpl.java:72)
    at com.sun.ejb.containers.interceptors.CallbackInvocationContext.proceed(CallbackInvocationContext.java:205)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.init(SystemInterceptorProxy.java:125)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.sun.ejb.containers.interceptors.CallbackInterceptor.intercept(InterceptorManager.java:986)
    at com.sun.ejb.containers.interceptors.CallbackChainImpl.invokeNext(CallbackChainImpl.java:72)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:412)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:375)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:2014)
    at com.sun.ejb.containers.AbstractSingletonContainer.createSingletonEJB(AbstractSingletonContainer.java:468)
    ... 49 more

Someone knows how to fix this error? After this happen, the DAS of glassfish try again to deploy application, and eclipse generate several times deployment error messages (this only stop when I remove the resource in glassfish server and stop it)
The project is using maven to manage dependencies.

A: As specified in the docs:

The method on which the @PostConstruct annotation is applied MUST fulfill all of the following criteria

*

*The method MUST NOT have any parameters except in the case of EJB interceptors in which case it takes an InvocationC ontext object as
  defined by the EJB specification.

*The return type of the method MUST be void.

*The method MUST NOT throw a checked exception.

*The method on which PostConstruct is applied MAY be public, protected, package private or private.

*The method MUST NOT be static except for the application client.

*The method MAY be final.

*If the method throws an unchecked exception the class MUST NOT be put into service except in the case of EJBs where the EJB can handle
  exceptions and even recover from them.

Then change your method from
@PostConstruct
public void initialize(UserVO userVO) {
    // ... initialize code
}

to
@Inject
UserVO userVO

@PostConstruct
public void initialize() {
    // ... initialize code
}

and create a producer that will be responsible to provide the UserVo object to the injection points with the @Produces annotation.


text:
Q: Pandas DataFrame filter column A depending on if column B contains x for group of values in A I would like to filter the below DataFrame df on column ref, based on if for the value in ref, column type contains the value 'P'.
In [32]: df
Out[32]:
   ref type
0    1    P
1    1    C
2    1    A
3    2    C
4    3    P
5    3    P
6    4    P
7    4    A
8    5    C
9    5    A

Here, ref values 1, 3, and 4 contain at least one row with value 'P' in column type, while 2 and 5 do not.
I am trying to filter out any rows with ref 2 and 5 so that the final output is:
In [34]: df
Out[34]:
   ref type
0    1    P
1    1    C
2    1    A
4    3    P
5    3    P
6    4    P
7    4    A

How could I do this (preferably in one step)?

A: Use groupby and filter:
df.groupby('ref').filter(lambda x : ('P' in x['type'].values))

returns:
   ref type
0    1    P
1    1    C
2    1    A
4    3    P
5    3    P
6    4    P
7    4    A


text:
Q: fetch() fails in Firefox with SSL client authentication I have a web server which uses SSL client authentication. A web page on that server makes a same-origin GET request using the fetch() API.
In Chrome, the client cert is sent in the SSL handshake, as expected, resulting in a 200 "ok" response. In Firefox, the cert isn't sent, resulting in a 403 "forbidden" response.
In Firefox, if I switch it from using fetch() to XMLHttpRequest, it works. If I load the same URL directly from Firefox's URL bar, it works. The problem seems limited to fetch() on Firefox.
Has anyone seen this before? Is there any way to make fetch() play well with SSL client auth in Firefox, or do I need to switch to using XMLHttpRequest everywhere? Thanks.

A: I just solved my own problem. This is what was failing:
fetch(someUrl)

This fixes the issue:
fetch(someUrl, { credentials: 'include' })

Apparently there's different behavior here between Chrome (v54) and Firefox (v45).


text:
Q: Integrating Google Maps API vs3 into a Wordpress plugin? - so close Creating a Google Maps plugin with API vs3? Hi there coders! After scouring the web for hours, cannot find a definitive article on integrating the new version 3 functionality into a wordpress site. Here's what I'm hoping to achieve...
1.) Create a plugin that collects a "Country Name" in the admin via simple post meta.
2.) The map will reverse geocode the country name pullin up a properly zoomed version of that google map
3.) Provide a preview to admin of the Google map
So first off, heres a working example of what we want as a static file:
http://simondelasalle.com/file_drop/google-map-example.htm
All good... pulls the canvas at the right dimension, zooms it... sweet. If you pull up the source you'll notice I've already prepped this a bit for wordpress  integration by taking out the body onload and replacing with window.onload = loadScript;
This almost works, but really need some help fine tuning.
1 Admin Box
Heres the admin meta box for updating the country and previewing the google map in the admin. *note The function for updating the fields themselves is not included below.
'
// add meta box
add_action( 'add_meta_boxes', 'post_map' );

// add meta box to post type
function post_map() {
    add_meta_box(
        'post_map_tab',
        __( 'Map', 'post_textdomain' ),
        'map_tab_box',
        'post'
    );
}

// print box content
function map_tab_box( $post ) {
    // Use nonce for verification
    // wp_nonce_field( plugin_basename( __FILE__ ), 'post_map_noncename' );
    // The actual fields for data entry
    ?>

        Country or Region

    (This is to GeoCode Map the location using Google)
        <input name="geoecode_country" type="text" value="<?php echo get_post_meta($post->ID, 'geoecode_country', true); ?>" size="30" />

        Please enter country and update to preview Google Map

    <?php
}

'
2 Add styles into your plugin CSS
`
#map_canvas {
    width: 400px;
    height: 400px;
}

`
3 Loading the neccesary scripts in the head to preview in admin page (customize placeholders for your plugin and API key). This is hooked into admin_head so we can replace with dynamic values
'
    function print_google_map_script() {

        // we could load conditionally by page if we want here
        global $post;
            $geoecode_country = get_post_meta($post->ID, 'geoecode_country', true);
        ?>

        <?php

    }

     add_action('admin_head', 'print_google_map_script');

'
So close to working it's painful. So the map loads kinda.... if you sit there and refresh a few times, it seems to eventually work. However when you first load the edit post page you get the map crunched up inside the canvas, as well as an incorrect zoom level. Here's a screen:
http://www.simondelasalle.com/file_drop/screen.jpg
Maybe the way the scripts are loaded? Doesn't seem like the API is recognizing canvas width.
Any suggestion or feedback you could provide would be greatly appreciated
Thanks!
S.

A: The problem is that the metabox is added to the page and displayed (and thus given width/height) after the map has drawn. You need to tell the map to refresh once the page has loaded:
$(window).load(function() {
    google.maps.event.trigger(map, "resize");
});

Worse, a metabox may be hidden by a user, then revealed later on; e.g they might hide the metabox when editing one page/post, then reveal it when editing another. Luckily, WP provides for a hook to let you know when a metabox is shown, so you can handle that too:
postboxes.pbshow = function() {
    google.maps.event.trigger(map, "resize");
};


text:
Q: Where did the phrase "chock-full" come from? I hear this phase spoken and rarely written, but Merriam-Webster has a definition their website. The origin states "Middle English chokkefull, probably from choken to choke + full."
Does anyone have more information on the origin? What is chokkefull?

A: The Online Etymology Dictionary offers more detail:

c.1400, chokkeful "crammed full," possibly from choke "cheek" (see cheek (n.)). Or it may be from Old French choquier "collide, crash, hit" [similar to shock].

Middle English chokkeful already had the same meaning as modern chock-full. Both this word and choke "to strangle" likely derive ultimately from Old English words meaning "jaw, cheek." The end result is the same: a mouthful.
Alternately, chokkeful may derive from a more violent word: forced full.
(Wiktionary offers a false etymology based on the kind of chocks used in carpentry and shipbuilding: full up to the chocks, perhaps. However that sense of chock only dates to the 1670s, far too late to influence the Middle English word.)

A: Just an idea. It may come from farmers and from the habit of fattening geese so that they get a fat liver for liver pâté. The food was stuffed into the throat of the animals with force, with a stick, I suppose, till they were almost  choked. From this situation an expression such as choke-full might have its origin, which might easily transform to chockfull when the origin of the word was forgotten. My idea, I haven't done any research yet.
I've just read etymonline's entry. Funny that Douglas Harper comes to choke but interprets it as cheek and gets in my view on a wrong track.

A: A lot of English words come from Low German or Dutch.
There is the word "tjokvol" in Dutch meaning exactly the same as chock-full.

A: I think it comes from the Turkish word çok, meaning very or a lot. It's said the same way and it would make sense to be very full.

A: The "chock" was the Old English name for a small scoop — one could purchase a portion of a "scoop" of, say, coffee or nuts; or a half-scoop; or a "chock"-full (as in the name of the coffee).


text:
Q: Integral equation that's cant solve... Need a hand Help me solve this integral equation, I'm having some troubles... I need to use the Fredholm method for second kind integral equations.
$$\phi(x)= \sin(x)+ \lambda \int_{0}^{\pi}\cos(2x+y)\phi (y)dy$$
Thanks

A: I don't know the method you mention, but notice that you can differentiate twice to get
$$\phi''(x)=-\sin x-4\lambda\int_0^\pi dy\ \phi(y)\cos(2x+y),$$
so that
$$\phi''(x)+4\phi(x)=3\sin x.$$
This is easily solved as
$$\phi(x)=\sin x+A\cos(2x)+B\sin(2x)$$
with constants of integration $A$ and $B$. Now plug $\phi$ back in to the integral and solve for $A$ and $B$ in terms of $\lambda$. I get
$$A=\frac{6\pi\lambda^2}{8\lambda^2-9}\qquad{\rm and}\qquad B=\frac{9\pi\lambda}{2(8\lambda^2-9)}.$$

A: Hint: expand out $\cos(2x+y)$, and you see that the right side will always be a linear combination of $\sin(x)$, $\cos(2x)$ and $\sin(2x)$.   So the left side...


text:
Q: What is the purpose of sSyncAdapterLock in sample SyncService? All of the sample SyncService code that I can find appears to be incompletely or unnecessarily synchronized.
The typical code below uses a static lock when creating the singleton instance.
public class SyncService extends Service {
  private static final Object sSyncAdapterLock = new Object();
  private static SyncAdapter sSyncAdapter = null;

  @Override
  public void onCreate() {
    synchronized (sSyncAdapterLock) {
      if (sSyncAdapter == null) {
        sSyncAdapter = new SyncAdapter(getApplicationContext(), false);
      }
    }
  }

  @Override
  public IBinder onBind(Intent intent) {
    return sSyncAdapter.getSyncAdapterBinder();
  }
}

Source: http://developer.android.com/training/sync-adapters/creating-sync-adapter.html
The two curious things about this code are:

*

*Why is a lock even needed? Isn't onCreate() always called on the main app thread?

*If a lock is needed in onCreate() why isn't this lock used to access the instance in onBind()? FindBugs flags this as 50% synchronized.

A: onCreate may (in theory) be called on two different instances of SyncService in parallel by the Android Runtime. The lock makes sure you really only ever create a single static SyncAdapter.

A: I have the same question, I believe the answer is that the synchronization in this example code is wrong. Yes onCreate is always called on the main thread so no synchronization is needed there. Furthermore even though multiple threads can invoke onBind simultaneously that method will not be invoked until after onCreate has completed. So there is no need for any synchronization at all in this example code.


text:
Q: Javascript Scope <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Youtube embed test</title>

        You need Flash player 8+ and JavaScript enabled to view this video.

    Load

I'm new to Javascript so I'm having trouble trying to get this to work. The debugger is telling me that ytplayer is undefined in function loadVideo(). Why is this? I understand that the variable declared in onYouTubePlayerReady goes out of scope when the brace ends. So how can I access the loadVideoById method? What confuses me further is that I can do something like this:
test

and it turns out that, that is perfectly legal. But why am I allowed to use ytplayer? I'm assuming it has something to do with the callback function onYouTubePlayerReady?

A: function onYouTubePlayerReady(  )  // playerid is usefull here or not
{
    ytplayer = document.getElementById("myytplayer");
    return ytplayer;
}

function loadVideo( id, start )
{
    ytplayer  = onYouTubePlayerReady();  // call onYouTubePlayerReady to get the object of ytplayer
    ytplayer.loadVideoById( id, start );
}


text:
Q: SQL - I have a 'People' table and an 'Account' table. How do I list all of the people in rows, and have a balance column for each account type? I was having a hard time figuring out how to title this question, so my apologies in advance.
Here is my my situation:
I have one table that has just people in it. I have another table that has all the accounts, with a personID, accountType, and balance column. A person can have multiple accounts, there are different account types, and not everyone has all of the different account types.
How can I write a query where I list one person per row, and have a column for the balance of each "account type"?
Ideally, my query would look something like this:
PersonID | Account Type 1 Bal | Account Type 2 Bal | Account Type 3 Bal |
-------------------------------------------------------------------------
    1    |         $100       |         null       |         null       |
    2    |         null       |         $12        |         $1300      |
    3    |         null       |         null       |         $5         |
    4    |         $150       |         null       |         null       |
    5    |         $65        |         $300       |         $45        |

I would assume I would use some sort of case statement, but I haven't been able to figure it out yet. Also, if they have multiple of the same account type, i assume I would just use sum() correct?
Thanks.

A: Something like this should work for postgres
select p.person_id,
  (select sum(a.balance) from account a where a.person_id = p.person_id and a.account_type = 'Type1') type1_balance,
  (select sum(a.balance) from account a where a.person_id = p.person_id and a.account_type = 'Type2') type2_balance,
  (select sum(a.balance) from account a where a.person_id = p.person_id and a.account_type = 'Type3') type3_balance
from person p

sqlfiddle example

A: Check if this helps -
http://sqlfiddle.com/#!4/30ebb/10/0
CREATE TABLE person
    ("person_id" int, "name" varchar2(9))
;

INSERT ALL
    INTO person ("person_id", "name")
         VALUES (1, '''Abcd''')
    INTO person ("person_id", "name")
         VALUES (2, '''xyz''')
    INTO person ("person_id", "name")
         VALUES (3, '''jjjjj''')
    INTO person ("person_id", "name")
         VALUES (4, '''sfds''')
    INTO person ("person_id", "name")
         VALUES (5, '''temp''')
SELECT * FROM dual
;

CREATE TABLE accounts
    ("personID" int, "accountType" int, "balance" int)
;

INSERT ALL
    INTO accounts ("personID", "accountType", "balance")
         VALUES (1, 1, 100)
    INTO accounts ("personID", "accountType", "balance")
         VALUES (1, 2, 150)
    INTO accounts ("personID", "accountType", "balance")
         VALUES (2, 1, 20)
    INTO accounts ("personID", "accountType", "balance")
         VALUES (3, 1, 40)
    INTO accounts ("personID", "accountType", "balance")
         VALUES (3, 2, 440)
    INTO accounts ("personID", "accountType", "balance")
         VALUES (4, 1, 600)
    INTO accounts ("personID", "accountType", "balance")
         VALUES (5, 1, 43)
    INTO accounts ("personID", "accountType", "balance")
         VALUES (5, 2, 50)
SELECT * FROM dual
;

Query -

select * from (
select p."person_id", a."accountType", a."balance"
from person p, accounts a
where p."person_id" = a."personID"
)
pivot (sum("balance") for "accountType" in (1 as acc_type1_bal,2 as acc_type2_bal));

person_id   ACC_TYPE1_BAL   ACC_TYPE2_BAL
1   100 150
2   20  (null)
4   600 (null)
5   43  50
3   40  440

A: select personid
      ,sum(ac1bal) accounttype1bal
      ,sum(ac2bal) accounttype2bal
      ,sum(ac3bal) accounttype3bal
from (
select persontable.personid
        ,case when (accounttype=1) then bal end ac1bal
        ,case when (accounttype=2) then bal end ac2bal
        ,case when (accounttype=3) then bal end ac3bal
from persontable
left join accounttable on persontable.personid = accounttable.personid
    )
group by personid


text:
Q: Getting 'unrecognized selector sent to instance' with PDFDocument initWithData? I'm using jsPDF in a webview to generate a PDF that I'd like to print out on a connected USB label printer. I'm getting a 'unrecognized selector sent to instance' error.
Here is the error from the Xcode console:
-[__NSCFString bytes]: unrecognized selector sent to instance 0x1089cb868

Here is the function for reference:
- (void) printPDFwithPrinter: (NSString *) printerName andData: (NSData *) data{

    NSLog(@"%@", printerName);

    PDFDocument *pdfDocument = [[PDFDocument alloc] initWithData:data];

    NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
    [printInfo setTopMargin:0.0];
    [printInfo setBottomMargin:0.0];
    [printInfo setLeftMargin:0.0];
    [printInfo setRightMargin:0.0];
    [printInfo setHorizontalPagination:NSFitPagination];
    [printInfo setVerticalPagination:NSFitPagination];
    [printInfo setPrinter:[NSPrinter printerWithName:printerName]];

    PDFPrintScalingMode scale = kPDFPrintPageScaleDownToFit;

    NSPrintOperation *op = [pdfDocument printOperationForPrintInfo: printInfo scalingMode: scale autoRotate: YES];

    [op setShowsPrintPanel:NO];
    [op setShowsProgressPanel:NO];
    [op runOperation];
}

The pdf data is the raw output of the pdf body as a string. (Docs)
I'm brand new to Objective-C, so I'm using AppBurger for my Native/webview bridge (building my app in HTML/JS/CSS).
Here is my Xcode project so far:
https://github.com/josiaho/AppBurger-Print-Test

A: How to debug:

*

*Add a breakpoint on the line
PDFDocument *pdfDocument = [[PDFDocument alloc] initWithData:data];

*Test the app. When the app hits the breakpoint, inspect data.

*data is a NSString and initWithData: expects NSData.
How to fix:

*

*Rename

- (void) printPDFwithPrinter: (NSString *) printerName andData: (NSData *) data
to
- (void) printPDFwithPrinter: (NSString *) printerName andString: (NSString *)  string

*Convert string to NSData.

NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

*Test the app.


text:
Q: Jade Syntax Highlighting in Visual Studio 2013 I wonder if there is an option I missed in Visual Studio 2013 to get the Jade syntax highlighting to work?
There is a pretty good integration of Node.js, Express and Jade in Visual Studio 2013, but it seems it lacks a proper syntax highlighting.
In that WebMatrix Tool of Microsoft the Jade syntax works pretty well and I dont't get because of what that features is missing in VS 2013. Maybe I made a mistake at some point of installation, project creating, missed an option or something like that.

A: In the new NTVS beta version I found this today and it works great:
NTVS supports the following:

...
Jade syntax highlighting -- New for Beta
...

For a download and more information see the Node.js Tools for Visual Studio project site on CodePlex.

A: I looked into it a couple of months ago and didn't find any resources for handling Jade better in Visual Studio at the time and there may not currently be any solution short of writing the tools you need yourself.
With that said, I did ask one of the developers behind a popular build extension for using languages like LESS or CoffeeScript in Visual Studio if he's considered adding Jade support and his answer was that they're working on it. I unfortunately have no idea what the timeline would be.
Sorry I don't have a better answer for you, I'm hoping for a solution as well. In the meantime I found a combination of Visual Studio, Sublime Text and Prepros works well enough for now.


text:
Q: Invalid RegEx Entered by User in Django Form Causes 500 Server Error I have a simple Django search form set up in my web application, where users can search for particular words in my Arabic corpus. The users can search one of three way: 'Exact' (the word just as it's typed), 'Stem' (which brings up all inflected forms of the lemma entered), and 'RegEx' (where they can do more complex searches by regular expression).
The problem I'm having is, if the user submits an invalid regex, instead of giving them a validation error or empty results, it triggers a 500 server error. Which I imagine is confusing. Below is the traceback for such and error, caused by searching for a regex with unbalanced parenthesis: ha((.*(?!al))
Is there anyway to catch this kind of error, or make it more user-friendly? (I've also included the code for my form below.)
Thank you.
class ConcordanceForm(forms.Form):
    searchterm = forms.CharField(max_length=100, required=True)
    search_type = forms.ChoiceField(widget=RadioSelect(),
             choices= ([('string', 'Exact'), ('lemma', 'Stem'), ('regex', 'Regex') ]),
             required=True )

def concord_test(request):
    if request.method == 'POST':
        form = ConcordanceForm(request.POST)
        if form.is_valid():
            searchterm = form.cleaned_data['searchterm'].encode('utf-8')
            search_type = form.cleaned_data['search_type']
            context, texts_len, results_len = make_concordance(searchterm, search_type)
            return render_to_response('corpus/concord.html', locals())
    else:
        form = ConcordanceForm()
    return render_to_response('corpus/search_test.html',
                              {'form': form}, context_instance=RequestContext(request))

Search for any word in the corpus:

<form action="/search_test/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

Traceback (most recent call last):
  File "/home/larapsodia/webapps/django/lib/python2.6/django/core/handlers/base.py", line 100, in get_response
    response = callback(request, *callback_args, **callback_kwargs)

  File "/home/larapsodia/webapps/django/tunisiya2/corpus/views.py", line 154, in concord_test
    context, texts_len, results_len = make_concordance(searchterm, search_type)

  File "/home/larapsodia/webapps/django/tunisiya2/corpus/views.py", line 91, in make_concordance
    p = re.compile(r'\b' + searchterm + r'__') # initial position in word_pos_lemma string

  File "/usr/local/lib/python2.6/re.py", line 190, in compile
    return _compile(pattern, flags)

  File "/usr/local/lib/python2.6/re.py", line 245, in _compile
    raise error, v # invalid expression

error: unbalanced parenthesis

<WSGIRequest
GET:<QueryDict: {}>,
POST:<QueryDict: {u'searchterm': [u'ha((.*(?!al))'], u'search_type': [u'regex'], u'csrfmiddlewaretoken': [u'c9a6cad4a0761580f5e351e9e534e028']}>,
COOKIES:{'__utma': '58037167.1544119768.1401037185.1401381302.1401384825.14',
 '__utmb': '58037167.10.10.1401384825',
 '__utmc': '58037167',
 '__utmz': '58037167.1401037185.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)',
 'csrftoken': 'c9a6cad4a0761580f5e351e9e534e028',
 'sessionid': '8d5b0b8730ccce0860b687b4c7ec1fdb'},
META:{'CONTENT_LENGTH': '109',
 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
 'CSRF_COOKIE': 'c9a6cad4a0761580f5e351e9e534e028',
 'DOCUMENT_ROOT': '/usr/local/apache2/htdocs',
 'GATEWAY_INTERFACE': 'CGI/1.1',
 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
 'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch',
 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8,ar;q=0.6',
 'HTTP_CACHE_CONTROL': 'max-age=0',
 'HTTP_CONNECTION': 'close',
 'HTTP_COOKIE': 'sessionid=8d5b0b8730ccce0860b687b4c7ec1fdb; csrftoken=c9a6cad4a0761580f5e351e9e534e028; __utma=58037167.1544119768.1401037185.1401381302.1401384825.14; __utmb=58037167.10.10.1401384825; __utmc=58037167; __utmz=58037167.1401037185.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)',
 'HTTP_FORWARDED_REQUEST_URI': '/search_test/',
 'HTTP_HOST': 'www.tunisiya.org',
 'HTTP_HTTPS': 'off',
 'HTTP_HTTP_X_FORWARDED_PROTO': 'http',
 'HTTP_ORIGIN': 'http://www.tunisiya.org',
 'HTTP_REFERER': 'http://www.tunisiya.org/search_test/',
 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36',
 'HTTP_X_FORWARDED_FOR': '68.9.41.110',
 'HTTP_X_FORWARDED_HOST': 'www.tunisiya.org',
 'HTTP_X_FORWARDED_PROTO': 'http',
 'HTTP_X_FORWARDED_SERVER': 'www.tunisiya.org',
 'HTTP_X_FORWARDED_SSL': 'off',
 'PATH_INFO': u'/search_test/',
 'PATH_TRANSLATED': '/home/larapsodia/webapps/django/tunisiya2.wsgi/search_test/',
 'QUERY_STRING': '',
 'REMOTE_ADDR': '127.0.0.1',
 'REMOTE_PORT': '37086',
 'REQUEST_METHOD': 'POST',
 'REQUEST_URI': '/search_test/',
 'SCRIPT_FILENAME': '/home/larapsodia/webapps/django/tunisiya2.wsgi',
 'SCRIPT_NAME': u'',
 'SERVER_ADDR': '127.0.0.1',
 'SERVER_ADMIN': '[no address given]',
 'SERVER_NAME': 'www.tunisiya.org',
 'SERVER_PORT': '80',
 'SERVER_PROTOCOL': 'HTTP/1.0',
 'SERVER_SIGNATURE': '',
 'SERVER_SOFTWARE': 'Apache/2.2.15 (Unix) mod_wsgi/3.2 Python/2.6.8',
 'mod_wsgi.application_group': 'tunisiya2.com|',
 'mod_wsgi.callable_object': 'application',
 'mod_wsgi.handler_script': '',
 'mod_wsgi.input_chunked': '0',
 'mod_wsgi.listener_host': '',
 'mod_wsgi.listener_port': '39877',
 'mod_wsgi.process_group': '',
 'mod_wsgi.request_handler': 'wsgi-script',
 'mod_wsgi.script_reloading': '1',
 'mod_wsgi.version': (3, 2),
 'wsgi.errors': <mod_wsgi.Log object at 0xd69b570>,
 'wsgi.file_wrapper': <built-in method file_wrapper of mod_wsgi.Adapter object at 0xa7efda0>,
 'wsgi.input': <mod_wsgi.Input object at 0xd69b598>,

 'wsgi.multiprocess': False,
 'wsgi.multithread': True,
 'wsgi.run_once': False,
 'wsgi.url_scheme': 'http',
 'wsgi.version': (1, 1)}>

A: Wrap the make_concordance in try-except; if an exception occurs,
render the original form template for the user, along with the error information.
import re
try:
    context, texts_len, results_len = make_concordance(searchterm, search_type)
except re.error as e:
    form._errors['search_term'] = str(e)
    del form.cleaned_data['search_term']

    return render_to_response('corpus/search_test.html',
         {'form': form}, context_instance=RequestContext(request))

The better way could be to make a custom cleaner, but it seems to be a bit more complicated, and I do not have Django.

A: I ended up building a custom cleaner, as Antti mentioned. This is what worked in the end:
def clean(self):
    cleaned_data = self.cleaned_data
    searchterm = cleaned_data.get('searchterm')
    search_type = cleaned_data.get('search_type')
    if search_type == 'regex':
        try:
            re.search(searchterm, 'randomdatastring') #this is just to test if the regex is valid
        except re.error:
            raise forms.ValidationError("Invalid regular expression.")
    return cleaned_data

A: To build on @Sam's comment, here's how to capture the specific error when a regular expression fails to compile:
import re
err_message = None
try:
    re.compile('(unbalanced')
except re.error as exc:
    err_message = 'Uhoh: {}'.format(exc)

print err_message

Output:

Uhoh: unbalanced parenthesis


text:
Q: android brief notifications icon background color problem(samsung) image
My origin brief notification icon background color is white,but after the other app's brief notification was shown,my app's brief notification background color will turn to that app setting(Red).
How can i change my icon's background color not affect by other app?
PS:I am sure that color will changed by last notification sent by other app.


text:
Q: Checking Checksum of a file from a url I want to check the sha1 hash of file from a url.
- name: Download CONF WEB/WS/CORE files
  get_url:
    url: "{{ file.url }}"
    checksum: "sha1:{{ file.url }}.sha1"
    dest: "/home/file"
    force_basic_auth: yes
    url_username: "xxxx"
    url_password: "xxxxx"
    mode: 0640
    timeout: 300
    force: yes

i have a file located in http://domaine.com/file
and the checksum located in http://domaine.com/file.sha1
when i execute the playbook i get this error message:
The checksum parameter has to be in format <algorithm>:<checksum> the example in ansible documentation is as below:

Ansible documentation :
If a checksum is passed to this parameter, the digest of the destination
 file will be calculated after it is downloaded to ensure its integrity and
 verify that the transfer completed successfully. Format:
:, e.g. checksum="sha256:D98291AC[...]B6DC7B97",
checksum="sha256:http://example.com/path/sha256sum.txt"
Did someone encountered the same errors
Thanks for your help in advance ^^,

A: Due to this comment it seems they won't provide such feature to check the checksum against an URL
https://github.com/ansible/ansible/issues/48790#issuecomment-440432038
It seems you need to do it in two separated tasks, one to download the checksum file and a second task to extract the checksum value from the downloaded file
I did this
---
- hosts: localhost
  tasks:
  - name: Download file
    get_url:
      url: "http://localhost/file"
      checksum: "sha1:3b71f43ff30...e84eb5a3"
      dest: "/home/user/file"

and it worked

Related issues
https://github.com/ansible/ansible/issues/27617
https://github.com/ansible/ansible/issues/48790
https://github.com/ansible/ansible/issues/48847


text:
Q: invalid data is getting inserted in table in sql server database I faced a situation and also searched for it in the internet but could not be able to get any solution.
Problem
My sql server table has 15000 records. It has several columns.
Among all the records, the 'Email ID' column of one record is storing value along with an unidentified character at the beginning. (Please refer to picture attached)

What I want
I want to get rid of that character using sql query. I am using sql server 2012 version.
I tried with 'replace()' and 'patindex()'. I even tried 'stuff' function.
But, its not working. Instead, when I am fetching the data using query, it is showing that typical character.
Please help me with some ideas. If I need to do some settings in database or table, I am ready for that.
Thanks.


text:
Q: Any service that can do a location lookup that Tableau can understand? Tableau has a limited set of geographic roles (outside the US) that can be displayed on a choropleth map. I have a list of (Country, City) or (Country, District) pairs and I want to have it converted into a format that Tableau can read as a Geographic role.
Any service that can do that?
TIA


text:
Q: UTF8 Filenames in PHP and Different Unicode Encodings I have a file containing Unicode characters on a server running linux. If I SSH into the server and use tab-completion to navigate to the file/folder containing unicode characters I have no problem accessing the file/folder. The problem arises when I try accessing the file via PHP (the function I was accessing the file system from was stat). If I output the path generated by the PHP script to the browser and paste it into the terminal the file also seems to exist (even though looking at the terminal the file paths are exactly the same).
I set PHP to use UTF8 as its default encoding via php_ini as well as set mb_internal_encoding. I checked the PHP filepath string encoding and it comes out as UTF8, as it should. Poking around a bit more I decided to hexdump the é character that the terminal's tab-completion and compare it to the hexdump of the 'regular' é character created by the PHP script or by manually entering in the character via keyboard (option+e+e on os x). Here is the result:

echo -n é | hexdump
0000000 cc65 0081
0000003
echo -n é | hexdump
0000000 a9c3
0000002

The é character that allows a correct file reference in the terminal is the 3-byte one. I'm not sure where to go from here, what encoding should I use in PHP? Should I be converting the path to another encoding via iconv or mb_convert_encoding?

A: Thanks to the tips given in the two answers I was able to poke around and find some methods for normalizing the different unicode decompositions of a given character. In the situation I was faced with I was accessing files created by a OS X Carbon application. It is a fairly popular application and thus its file names seemed to adhere to a specific unicode decomposition.
In PHP 5.3 a new set of functions was introduced that allows you to normalize a unicode string to a particular decomposition. Apparently there are four decomposition standards which you can decompose you unicode string into. Python has had unicode normalization capabilties since version 2.3 via unicode.normalize. This article on python's handling of unicode strings was helpful in understanding encoding / string handling a bit better.
Here is a quick example on normalizing a unicode filepath:
filePath = unicodedata.normalize('NFD', filePath)

I found that the NFD format worked for all my purposes, I wonder if this is this is the standard decomposition for unicode filenames.

A: The three byte sequence is actually the utf8 representation of an e (0x65) followed by a combining ´ (0xcc 0x81), while 0xc3 0xa9 stands "directly" for é.
An utf-8 aware collation should be aware of the possible decompositions, but I don't know how you can enable that (and probably recompile the php source) on a mac.
Best I can offer is the "Using UTF-8 with Gentoo" description.

A: Firstly: You should try to avoid imposing semantics on the names of files. I can't really tell why PHP is generating filenames in your scenario, so I can't suggest how you should apply this rule.
The different (two byte and three byte) representations of é are UTF-8 encodings of the composed and decomposed variations of this character in Unicode. In Unicode these are distinct ways to represent the same visual character. Unicode has the concept of "canonicalisation" in which all representations of the same character are converted to a single representation, sort of like squashing two strings to lowercase to perform a caseless comparison.
Linux does not perform canonicalisation or any other processing automatically for file names, so a file may be named with precomposed (like the two byte sequence) or decomposed (like the three byte sequence) characters or any mix of the two, it's up to whoever named the file. If you are creating the files, you could set a policy (e.g. always use precomposed characters) and write some code to enforce it. Otherwise, you can't rely on any particular rule here.