text:
Q: Creating an AppleScript to do a find in a replace in a given document I'm looking to create aAppleScript that when run will:

*

*Search the document for a given string

*Replace that string with another given string

The strings will always be the same
Search for

This will be used in textmate - I was trying to do this in textmate
I know I can use textmate's find and replace functionality - I'm just trying to automate a little.
This should only make changes on the current page.
Is this possible?
UPDATE:
So I've found some code that has got me started...
tell application "TextMate" to activate
tell application "System Events"
    keystroke "f" using {command down}
        tell process "TextMate"
            keystroke "<?"
            keystroke tab
            keystroke "<?php"
            click button "Replace All"
        end tell
    keystroke "esc"
end tell

but I get the following error:
error "System Events got an error: Can't get button \"Replace All\" of process \"TextMate\"." number -1728 from button "Replace All" of process "TextMate"

On the find and replace dialog of Textmate the button is labeled "Replace All"  Am I missing something here?

A: You're better off looking at MacScripter; there are lots of examples and solutions for find and replacing with or without a texteditor using Applescripts delimiters: MacScripter / Search results, like this:
on replaceText(find, replace, someText)
   set prevTIDs to text item delimiters of AppleScript
   set text item delimiters of AppleScript to find
   set someText to text items of someText
   set text item delimiters of AppleScript to replace
   set someText to "" & someText
   set text item delimiters of AppleScript to prevTIDs
   return someText
end replaceText

A: You'll have to send the keystroke to the proper window. Something like tell window "find dialog" (or whatever). You have to be completely specific, so it might be
tell tab 1 of pane 1 of window "find and replace" of app textmate...

User interface scripting is so hackalicious you should only do it as a last resort.
Looks like you need sed.
on a command line, or with do shell script:
cat /path/to/your/file.php|sed "s_<?_<?php_g">/path/to/your/newfile.php

or for a whole folder's worth
cd /path/to/your/folder
for file in *.php; do  cat "$file"|sed "s_<?_<?php_g">"${file/.php/-new.php}"; done

A: It's all very well sending folks to do search/replace within AppleScript strings, or sending them to Mac OS X's underlying Unix tools, like sed and Perl, but those are often no real substitue for searching/replacing text directly in the target application.
I had the exact same problem, albeit in Dragon Dicate rather than TextMade. Google led me here, where I was dismayed to find no direct solution. So let me share the one I came up with:
set find to "the"
set replace to "THE"
tell application "Dragon Dictate"
    activate
    tell application "System Events"
        tell process "Dragon Dictate"
            keystroke "f" using {command down}
            keystroke find
            keystroke tab
            keystroke replace
            tell window "Find"
                click button "Replace All"
            end tell
        end tell
    end tell
end tell

The key difference is addressing the Find window, which knows about the "Replace All" button. You will also have to change the "Dragon Dicate" target app to "TextMate" of course. (AppleScript seems to require knowing EXACTLY what app a script is being fired against, unless you want to fall back into some truly ugly low-level message sending. When dealing with AppleScript, that's just the 337th sigh of the day!)

A: If you want to write an AppleScript to manipulate text, there is nothing better than to use an AppleScriptable text editor. That is the right tool for the job. Then you can write just a few lines of code and get the job done.
For example, in TextMate, go Edit > Select All and Edit > Copy to copy the contents of your document to the clipboard. Then run this AppleScript:
tell application "TextWrangler"
    activate
    set theSearchString to the clipboard
    set theResultString to replace "old term" using "new term" searchingString theSearchString
    set the clipboard to theResultString
end tell

Then go back into TextMate and go Edit > Paste.
TextWrangler is available for free in Mac App Store.
You may be able to expand this script so that the TextMate work is automated with GUI scripting, but since it is just selecting all and copying and pasting, that is a fairly small task.


text:
Q: To print the reverse of a given number in java lang I have found examples which imported java.util.scanner and used reverse and scanner keys. Im a beginner and I tried a simpler way, though I am not getting the right output. please find the mistake in my code.
public class ReverseNum {

public static void main(String[] args) {
    int i=234,n,x;

    n=i%10;
    x=n;

    while(i>=0){

        i=(i/10)-n;
        n=i%10;
        x=(x*10)+n;
        System.out.print(x);

    }

}

}

A: There, I fixed it for you.
class HelloWorld{
 public static void main(String args[]){

  int i=2340,n;
  while(i>0){
    n=i%10;
    i=(i/10);
    System.out.print(n);
  }

 }
}

You can also do this without math operations.
int i=234;

System.out.print(new StringBuffer(i+"").reverse().toString());

A: public static void main(String[] args) {
        int i = 234, n;
        while (i > 0) {
            n = i % 10;
            i = i / 10;
            System.out.print(n);
        }
}

hope this is what you wanted...

A: Program 1: Reverse a number using while Loop
The program will prompt user to input the number and then it will reverse the same number using while loop.
import java.util.Scanner;

class ReverseNumberWhile{
    public static void main(String args[]){
      int num=0;
      int reversenum =0;
      System.out.println("Input your number and press enter: ");
      //This statement will capture the user input
      Scanner in = new Scanner(System.in);
      //Captured input would be stored in number num
      num = in.nextInt();
      //While Loop: Logic to find out the reverse number
      while( num != 0 ){
          reversenum = reversenum * 10;
          reversenum = reversenum + num%10;
          num = num/10;
      }

      System.out.println("Reverse of input number is: "+reversenum);
    }
}

Output:
Input your number and press enter:
145689
Reverse of input number is:

986541

http://beginnersbook.com/2014/01/java-program-to-reverse-a-number/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configure NodeJs on Jenkins? I installed the NodeJS plugin 1.3.7 on an installation of Jenkins 2.235.2. After restarting Jenkins I see the NodeJS options on job configuration screens, but there is nothing on the Jenkins configuration screen that makes any mention of Node, so I am not able to add any installations for the jobs to use. I've found several sources that say that clicking Check now on the Advanced tab of the Plugin Manager screen will solve this, but that has had no effect. Can anyone suggest what else I might try to be able to add Node installations, or explain what I'm missing?

A: Go to Manage Jenkins >> Global tool configuration
and configure node there according to you

and in your jenkinsfile use
tools {
  nodejs "nodejs-2.x"
}


text:
Q: Is an algebraic integer all of whose conjugates have absolute value 1 a root of unity?
Possible Duplicate:
Are all algebraic integers with absolute value 1 roots of unity?

Let $\alpha$ be an algebraic integer.
Suppose that all the roots of its minimal polynomial have absolute value 1.
Is $\alpha$ a root of unity?


text:
Q: how to calculate percentile value of number in dataframe column grouped by index I have a dataframe like this:
df:
        Score
group
  A      100
  A      34
  A      40
  A      30
  C      24
  C      60
  C      35

For every group in the data, I want to find out the percentile value of Score 35.
(i.e the percentile where the 35 fits in the grouped data)
I tried different tricks but none of them worked.
scipy.stats.percentileofscore(df['Score], 35, kind='weak')
 --> This is working but this doesn't give me the percentile grouped by index

df.groupby('group')['Score].percentileofscore()
 --> 'SeriesGroupBy' object has no attribute 'percentileofscore'

scipy.stats.percentileofscore(df.groupby('group')[['Score]], 35, kind='strict')
 --> TypeError: '<' not supported between instances of 'str' and 'int'

My ideal output looks like this:
df:
        Score Percentile
group
  A       50
  C       33

Can anyone suggest to me what works well here?

A: Inverse quantile function for a sequence at point X is the proportion of values less than X in the sequence, right? So:
In [158]: df["Score"].lt(35).groupby(df["group"]).mean().mul(100)
Out[158]:
group
A    50.000000
C    33.333333
Name: Score, dtype: float64

*

*get a True/False Series of whether < 35 or not on "Score"

*group this Series over "group"

*take the mean

*

*since True == 1 and False == 0, it will effectively give the proportion!

*multiply by 100 to get percentages

A: To answer in a bit more general purpose way you're looking to do a custom aggregation on the group, which pandas lets you do with the agg method.
You can define the function yourself or use one from a library:
def percentileofscore(ser: pd.Series) -> float:
    return 100 * (ser > 35).sum() / ser.size

df.groupby("group").agg(percentileofscore)

Output:
      Score
group
A     50.000000
C     33.333333


text:
Q: Orchard CMS front-end all possible content filtering by user permissions Good day!
In my Orchard, I have several content types all with my custom part attached. This part defines to what users this content is available. For each logged user there is external service, which defines what content user can or cannot access. Now I need access restriction to apply everywhere where orchard display content lists, this includes results by specific tag from a tag cloud, or results listed from Taxonomy term. I seems can't find any good way to do it except modifying TaxonomyServices code as well as TagCloud services, to join also my part and filter by it. Is this indeed the only way to do it or there are other solutions? I would like to avoid doing changes to built-in modules if possible but cannot find other way.
Thanks in advance.

A: I'm currently bumbling around with the same issue. One way I'm currently looking at is to hook into the content manager.
[OrchardSuppressDependency("Orchard.ContentManagement.DefaultContentManager")]
    public class ModContentManager : DefaultContentManager, IContentManager
    {
        //private readonly Lazy<IShapeFactory> _shapeFactory;
        private readonly IModAuthContext _modAuthContext;

        public ModContentManager(IComponentContext context,
            IRepository<ContentTypeRecord> contentTypeRepository,
            IRepository<ContentItemRecord> contentItemRepository,
            IRepository<ContentItemVersionRecord> contentItemVersionRepository,
            IContentDefinitionManager contentDefinitionManager,
            ICacheManager cacheManager,
            Func<IContentManagerSession> contentManagerSession,
            Lazy<IContentDisplay> contentDisplay,
            Lazy<ISessionLocator> sessionLocator,
            Lazy<IEnumerable<IContentHandler>> handlers,
            Lazy<IEnumerable<IIdentityResolverSelector>> identityResolverSelectors,
            Lazy<IEnumerable<ISqlStatementProvider>> sqlStatementProviders,
            ShellSettings shellSettings,
            ISignals signals,
            //Lazy<IShapeFactory> shapeFactory,
            IModAuthContext modAuthContext)
            : base(context,
                contentTypeRepository,
                contentItemRepository,
                contentItemVersionRepository,
                contentDefinitionManager,
                cacheManager,
                contentManagerSession,
                contentDisplay,
                sessionLocator,
                handlers,
                identityResolverSelectors,
                sqlStatementProviders,
                shellSettings,
                signals) {
            //_shapeFactory = shapeFactory;
            _modAuthContext = modAuthContext;
        }

        public new dynamic BuildDisplay(IContent content, string displayType = "", string groupId = "") {
            // So you could do something like...
            // var myPart = content.As<MyAuthoPart>();
            // if(!myPart.IsUserAuthorized)...
            // then display something else or display nothing (I think returning null works for this but
            //don't quote me on that. Can always return a random empty shape)

            // else return base.BuildDisplay(content, displayType, groupId);

            // ever want to display a shape based on the name...
            //dynamic shapes = _shapeFactory.Value;
        }
    }
}

Could also hook into the IAuthorizationServiceEventHandler, which is activated before in the main ItemController and do a check to see if you are rendering a projection or taxonomy list set a value to tell your content manager to perform checks else just let them through. Might help :)


text:
Q: JSON.NET Tutorial Can anyone help me in finding some code examples or tutorials to understand how to use JSON.NET features.
The documentation seems to be a litle confusing and difficult for me to undersatand.
I am new in field of JSON and .NET
Thanks
Puneet

A: Check the examples given here:
http://james.newtonking.com/pages/json-net.aspx
If you are still confused then provide detail of what you want to achieve?

A: Start off with
http://www.json.org/
Then check out
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
Using Json with .NET is really easy.


text:
Q: Object attribute not saving I was making a django application ,i overwrote the save method of a model to introduce a new attribute slug using sluggish fuction . But when i try to access that attribute from shell it raises an error AttributeError: 'States' object has no attribute 'slug'
code :-
from django.db import models
from django.template.defaultfilters import slugify

class States(models.Model):
    title = models.CharField(max_length = 100)
    country = models.CharField(max_length = 79)

    def __str__(self):
        return self.title

    def save(self,*args,**kwargs):
        self.slug = slugify(self.title)
        super(States,self).save(*args,**kwargs)

class Colleges(models.Model):
    title = models.CharField(max_length = 100)
    state = models.ForeignKey(States)
    Description = models.TextField()

    def __str__(self):
        return self.title

A: That wouldn't work. Django would always check the initial definition of your model class to create the database mapping, django wouldn't recognize slug is a database field the way you do it. In your current implementation, you are only creating slug as a python class attribute but not database field, because django model is, well, a python class as well.
I'm not sure why you don't want to define slug the same way you define title and country, but the easiest fix would be adding it as a class attribute.

A: If you don't want to save the slug in your database, you can calculate it in a class method of State:
@property
def slug (self):
    return slugify (self.title)

Now you can access it as a property like title:
obj.slug


text:
Q: Rails Looking for more efficient way of looping through records and displaying child records Say I have the following controller action:
TeamController < ApplicationController

  def index
    @teams = Team.all
  end

end

Then on the index view I'm looping through all records and also displaying some information about child records for each team.
#/views/teams/index.slim

h1 pluralize(@teams.count, 'Team')
ul
  = render @teams

#/views/teams/_team.slim

li
  span = team.name.titleize
  span = pluralize(team.members.count, 'member')

Here's the issue that stands out to me.  By calling team.members from the team partial it means that the server does a select query for each time the partial is called.  Obviously this is less than desirable outcome.
In the past I've tried:
TeamController < ApplicationController

    def index
      @teams = Team.all
      @members = Member.all
    end

  end

Then using Array.select in the partial like so:
#/views/teams/_team.slim

li
  span = team.name.titleize
  span = pluralize(@members.select{ |m| m.team_id == team.id }.count, 'member')

While this results in a much faster page render it puts more logic in the view than I would like. Additionally this approach easily breaks if @members is nil.
Has anyone faced this issue before?  What have you done to speed up the your list oriented index views?

A: The normal Rails solution to this is to "Eager Load" your associations like this:
def index
  @teams = Team.includes(:members).all
end

When this code actually fires off the SQL query, it will do 2 queries.
It will retrieve the teams with SQL (something) like this:
select * from teams
select * from members where id in (select member_id from teams)

And automatically stitch the data from the second query into the objects returned, so you can continue to call
= team.members.count

Without incurring the N+1 Query penalty every time this partial gets iterated over.
You can read more about Eager Loading associations here


text:
Q: Task List desktop app using Visual Studio 2015 Is it possible to develop in Visual Studio 2015 a Desktop App that will retrieve Tasks from multiple task lists in a Office 365 Collection and display them based on the currently logging in user?
Does anyone have samples or guides to create this?
Thank you.

A: You can access lists programmatically using the Client Library:
https://msdn.microsoft.com/en-us/library/office/fp179912.aspx#BasicOps_SPListTasks
or for JavaScript:
https://msdn.microsoft.com/en-us/library/office/jj163201.aspx#BasicOps_SPListItemTasks
Identifying logged in users:
http://blog.furuknap.net/find-number-of-users-currently-logged-on-to-a-sharepoint-site
I've given up on SharePoint Online, myself, as MS has continued to lock-down and restrict access to everything that I found to be of any use, but I'm pretty sure you are still able to read Lists etc.


text:
Q: Reading External Text File and Storing into an array How do i read an external text file, possibly using a Scanner and store 2 values from each line into an array.
I would want to store the node id which is the first value of each line and the parent number which is the last value in each line.
The text file contains what you see below
1       2,7,|0|BLACK|NULL
10      3,4,12,|3|BLACK|3
11      4,12,|4|BLACK|4
12      8,10,11,|3|BLACK|8
2       1,3,6,8,|1|BLACK|1
3       2,4,5,6,8,10,|2|BLACK|2
4       3,5,9,10,11,|3|BLACK|3
5       3,4,8,|3|BLACK|3
6       2,3,|2|BLACK|2
7       1,8,|1|BLACK|1
8       2,3,5,7,9,12,|2|BLACK|2
9       4,8,|3|BLACK|8

A: A regex approach (have left the array bit as an exercise for the reader):
BufferedReader br = new BufferedReader(new FileReader("hadoop_data.txt"));

String currentLine;
while ((currentLine = br.readLine()) != null) {

    Matcher matcher = Pattern.compile("(\\d+).*\\|(\\w+)").matcher(currentLine);
    if (matcher.matches()) {
        System.out.println(matcher.group(1) + "\t" + matcher.group(2));
            // add to array
    }
}

A: Shonna, you can achieve what you want using a HashMap, a Scanner, and some simple string parsing.  Here's my whole class:
import java.io.*;
import java.util.*;

public class nodes {

    private static HashMap<Integer, String> map = new HashMap<Integer, String>();

    public static void main(String[] args) {
        File file = new File("nodes.txt");
        Scanner scnr = null;
        try {
            scnr = new Scanner(file);
        } catch (FileNotFoundException e) {

        }
        while(scnr.hasNext()) {
            String line = scnr.nextLine();
            String[] getId = line.split("\\s+");
            int id = Integer.parseInt(getId[0]);
            int count = 0;
            int copy = 0;
            for(int i = 0; i < line.length(); i++) {
                if(line.charAt(i) == '|')
                    count++;
                if(count == 3) {
                    copy = i;
                    break;
                }
            }
            String parent = line.substring(copy + 1);
            map.put(id, parent);
            System.out.println(map);
        }
    }

}

What it does is it reads through each line of the file, first extracting the node id.  It then cycles through each character in the line until it counts three |'s, at which point we know the rest of the line will be the parent of the node.  After this is done, it pairs the id with the parent in a HashMap.


text:
Q: connecting two java frame Actually I am New to java I want to know how to link two frames. I made two different java files, which looks simple. But I am unable to solve it till now. It should open the welcome frame by clicking Next Button in Enter.java. Can anybody help me?
Here is my code:
Enter.java

import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Enter extends JFrame {

public Enter() {
// TODO Auto-generated constructor stub

setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));

add(new JLabel("Name"));
add(new JTextField(8));
add(new JLabel("Address"));
add(new JTextField(15));
add(new JLabel("Surname"));
add(new JTextField(8));
add(new JLabel("Phone"));
add(new JTextField(8));
add(new JButton("Next"));
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
    Enter myProg = new Enter();
myProg.setTitle("Ceng 344 - Lab 7");
myProg.setSize(450, 400);
myProg.setLocationRelativeTo(null);
myProg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myProg.setVisible(true);
}

}

Welcome.java
 import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class welcome extends JFrame {

public welcome() {
// TODO Auto-generated constructor stub

setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));

add(new JLabel("Welcome"));
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
welcome myProg = new welcome();
myProg.setTitle("Ceng 344 - Lab 7");
myProg.setSize(450, 400);
myProg.setLocationRelativeTo(null);
myProg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myProg.setVisible(true);
}

}

A: If you need to call the Welcome Frame from the Next Button, so that you can add the action to this button.
Try this:
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Main extends JFrame {

    public Main() {
// TODO Auto-generated constructor stub

        setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));

        add(new JLabel("Name"));
        add(new JTextField(8));
        add(new JLabel("Address"));
        add(new JTextField(15));
        add(new JLabel("Surname"));
        add(new JTextField(8));
        add(new JLabel("Phone"));
        add(new JTextField(8));
        JButton next = new JButton("Next");
        add(next);
        next.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NextActionPerformed(evt);
            }

            private void NextActionPerformed(ActionEvent evt) {
                welcome myProg = new welcome();
                myProg.setTitle("Ceng 344 - Lab 7");
                myProg.setSize(450, 400);
                myProg.setLocationRelativeTo(null);
                myProg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                myProg.setVisible(true);
            }
        });

    }

    /**
     * @param args
     */
    public static void main(String[] args) {
// TODO Auto-generated method stub
        Main myProg = new Main();
        myProg.setTitle("Ceng 344 - Lab 7");
        myProg.setSize(450, 400);
        myProg.setLocationRelativeTo(null);
        myProg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myProg.setVisible(true);
    }
}

class welcome extends JFrame {

    public welcome() {
// TODO Auto-generated constructor stub

        setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
        add(new JLabel("Welcome"));
    }
    /**
     * @param args
     */
}

i remove the Welcome's Main class , and add it's content to the NextActionPerformed method

A: First of all

*

*You need to add ActionListener to the JButton

*You can set the properties of JFrame inside constructor.

*You don't need main() in welcome.java, only `constructor will do
it.

Enter.java
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Enter extends JFrame implements ActionListener {
public Enter(){
    setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
    add(new JLabel("Name"));
    add(new JTextField(8));
    add(new JLabel("Address"));
    add(new JTextField(15));
    add(new JLabel("Surname"));
    add(new JTextField(8));
    add(new JLabel("Phone"));
    add(new JTextField(8));
    JButton next = new JButton("Next");
    next.addActionListener(this);
    add(next);
}

public void actionPerformed(ActionEvent ae){
    //if your frame contains more than one button then you can check which button is clicked using ae.getSource() or using ae.getActionCommand()
    new Welcome();
}
public static void main(String[] args) {
    Enter myProg = new Enter();
    myProg.setTitle("Ceng 344 - Lab 7");
    myProg.setSize(450, 400);
    myProg.setLocationRelativeTo(null);
    myProg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myProg.setVisible(true);
}
}

//Welcome
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Welcome extends JFrame {
    public Welcome() {
        setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
        add(new JLabel("Welcome"));
        setTitle("Ceng 344 - Lab 7");
        setSize(450, 400);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
}


text:
Q: Best practice for wildcard SSL certificate renewal in Azure, having pinned mobile application We have the following situation and need an advice, since nobody ha a previous experience with pinned mobile applications.

*

*We have one wildcard SSL certificate for the domain, maintained at Azure - *.example.com

*There are multiple endpoints that the cert had been applied to, including the the one that is used by mobile application.

*Mobile application has this certificate pinned.

*The cert will expire in about 45 days.

What will be the best course of actions to renew the certificate, with ideally no downtime, or minimal downtime for mobile and other applications?
If we renew the cert, we need to push an update for a mobile application to the store with it. It will take some time to get approved by the store and during that time the application will not be able to communicate with the backend, if we'll go straight forward.
So, we need an advice from those with such experience, please.
Thanks for your help in advance.

A: The only reliable solution will be:

*

*acquire new certificate now (in advance), get its details (thumbpring, public key, whatever else properties you use for pinning)

*make mobile application (external endpoint) update to trust existing and newly acquired certificate.

*push update to appropriate stores (where clients can get new version of mobile application)

*wait until current certificate expires and hope that all clients have updated their application

*switch web app to new certificate.

that is, certificate replacement must be obtained in advance to get its details, make updates, have time to propagate updates and only then change certificate on front end.


text:
Q: How to create addPlayer() method. (Python 3) I'm currently working on an OOP project in my CSI class in which I have to create various sports team and athlete objects as well as a method addPlayer() for adding the athletes to a roster. This is what I have so far.
class Athlete:

def __init__(self, name, number):
    self.name = name
    self.number = number

def __str__(self):
    return "Athlete(" + self.name + ", " + self.number + ")"

def name(self):
    return self.name

def number(self):
    return self.number

from Athlete import *

class SportsTeam:

    roster = []

    def __init__(self, city, name, colors):
        self.city = city
        self.name = name
        self.colors = colors
        SportsTeam.roster = roster

    def __str__(self):
        return "SportsTeam(" + self.city + ", " + self.name + \
              ", " + str(self.colors) + ", " + ")"

    def getcity(self):
        return self.city

    def getname(self):
        return self.name

    def getcolors(self):
        return self.colors

    def getRoster(self):
        return SportsTeam.roster

    def printRoster(self):
        for player in roster:
            print("Current Team Roster: " + str(SportsTeam.roster))

    def addPlayer(self, player):
        SportsTeam.roster.append(player)
        return SportsTeam.roster

The thing is when I try to use the addPlayer() method I created, I get an error message telling me that list has no attribute. Not sure what needs to be added to fix this.
P.S I have only been programming for a couple of months, so I apologize if the solution is obvious

A: When you are dealing with classes, you have your instance variables (like self.city = city) and your class variables (like roster = []).
Instance variables are tied to an instance of the class. So if you create 2 SportsTeam objects, they each have their own city.
Class variables are a little different. They are not tied to an instance of the class; meaning, no matter how many SportsTeam objects you create, there will only be one roster variable.
To me, roster being a class variable seems a bit odd because each SportsTeam should have its own roster. However, if you are required to use class variables for you CSI class, maybe you could keep a list of all_teams and/or all_players.
Taking this into consideration:
class SportsTeam:

    all_teams = []
    all_players = []

    def __init__(self, city, name, colors):
        self.city = city
        self.name = name
        self.colors = colors
        self.roster = []

        SportsTeam.all_teams.append(self)

    def __str__(self):
        return "SportsTeam(" + self.city + ", " + self.name + ", " + str(self.colors) + ")"

    def getCity(self):
        return self.city

    def getName(self):
        return self.name

    def getColors(self):
        return self.colors

    def getRoster(self):
        return self.roster

    def printRoster(self):
        # the for loop was unnecessary
        print("Current Team Roster:", str(self.roster))

    def addPlayer(self, player):
        SportsTeam.all_players.append(player)
        self.roster.append(player)
        return self.roster

If you would like to keep roster as a class variable, leave a comment and I can help you adjust the code to accommodate for this.


text:
Q: mvc: Model.IsValid not working if Iam using Request.Form Iam a beginner in MVC.
If iam using below code then Model.IsValid is not validating the object which in this case is Customer.
 public ActionResult Submit()
    {
        Customer custObj = new Customer();
        custObj.CustomerCode = Request.Form["CustomerCode"];
        custObj.CustomerName = Request.Form["CustomerName"];

        if (ModelState.IsValid)
            return View("Load", obj);
        else
            return View("EnterCustomer");
    }

While if Iam passing the Customer object in parameter then Model.IsValid is working perfectly.
public ActionResult Submit(Customer obj)
    {
        //Customer custObj = new Customer();
        //custObj.CustomerCode = Request.Form["CustomerCode"];
        //custObj.CustomerName = Request.Form["CustomerName"];

        if (ModelState.IsValid)
            return View("Load", obj);
        else
            return View("EnterCustomer");
    }

Can any1 help me in getting to know the reason.

A: It doesn't work beause MVC never bound to the model itself. You manually overrode it so MVC has no clue whether the model is valid or not. It doesn't event know that custObj is the model.
ModelState.IsValid is set before your action method is called, so in your second example, when you allow MVC to bind to the model itself, it works. In the first, it doesn't work because you create the model and do manual binding to it.
Update
You can, however, also manually run the model validation by calling ValidateModel or TryValidateModel on the controller.
Documentation:

*

*ValidateModel: https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.validatemodel(v=vs.100).aspx

*TryValidateModel: https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryvalidatemodel(v=vs.100).aspx

A: As mentioned in other answers, your model is already validated before the action 'Submit' is called. So, when you are changing the model from inside your action, you will have to manually validated the model. You may use below code for it.
var context = new ValidationContext(custObj, serviceProvider: null, items: null);
var validationResults = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(custObj, context, validationResults, true);
if (isValid)
   return View("Load", obj);
else
   return View("EnterCustomer");
use below url for further details.
http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx


text:
Q: The difference between convergence in probability and convergence in distribution. I'm confused with the concepts of convergence in probability and convergence in distribution. After reading some examples in Wiki, can I say convergence in probability means the decrease of variance as n goes to infinity, that is we become more and more confident that one outcome in the sample space will happen? Convergence in distribution just indicates the probability distribution.

A: One of the key differences is that convergence in probability tells you something about random variables being close in a pointwise sense (with a high probability) whereas convergence in distribution says only something about the closeness of the distributions.
Let me illustrate this with an example: Take to identically distributed random variables $X$ and $Y$ and define $$X_n := Y \qquad \text{for all $n \geq 1$}.$$ Since all the random variables have the same distribution, we clearly have $X_n \to X$ in distribution. On the other hand, we can, in general not, expect that $X$ is close to $Y$ in a pointwise sense. For instance, if $X \sim N(0,1)$ and we set $Y=X_n:=-X$, then $$\mathbb{P}(|X-X_n|>\delta) = \mathbb{P}(|X|>\delta/2)>0$$ which means that $X_n$ does not convergence in probability to $X$.
Convergence in distribution does not even require that the random variables are all defined on the same probability space, i.e. each random variable $X_n$ may be defined on some probability space $(\Omega_n,\mathcal{A}_n,\mathbb{P}_n)$. In particular, it doesn't even make sense to ask whether the random variables $X_n$ are being close to each other since we can't calculate the probability of the set
$$\{\omega \in ??; |X_n(\omega)-X_m(\omega)| >\delta\}$$
(probability with respect to which measure? $\mathbb{P}_n$ or $\mathbb{P}_m$...? In fact, we can't even write down the set properly since the $\omega$'s are elements in different probability spaces.)


text:
Q: Issue setting border in UITableViewCell and flickering when scroll I have problem setting the top border to UITableViewCell. My requirement is to setup the bottom borders for all the cells and only top border to the first cell. I used the below code to setup this
if (indexPath.row == 0){
  CALayer* topCellBorder = [CALayer layer];
  topCellBorder.frame = CGRectMake(0, 1, CGRectGetWidth(cell.frame) , 0.5);
  topCellBorder.backgroundColor = [config getColour:@"theme.table-border.color"].CGColor;
  [cell.layer addSublayer:topCellBorder];
}
CALayer* bottomCellBorder = [CALayer layer];
bottomCellBorder.frame = CGRectMake(0, CGRectGetHeight(cell.frame) - 0.5, CGRectGetWidth(cell.frame)  , 0.5);
bottomCellBorder.backgroundColor = [config getColour:@"theme.table-border.color"].CGColor;
[cell.layer addSublayer:bottomCellBorder];

This works fine at first, heres the screenshot

But after the scroll, the top border is gone and added to the next view like this

Also i am seeing the border flickers when scroll. Any ideas what causing this behaviour

A: Cells are being reused so the old borders remain. When you scroll the first cell will be reused for some other cell and it will already have topCellBorder.
I suggest you add cell border in awakeFromNib method for the cell and simply toggle on and off top and bottom border. So your cells should have both border layers, but based on indexPath.row in table view data source, you just show and hide them.


text:
Q: Load last records first using for loop in JavaScript Right the data is loading in ascending order but I want to display the records in descending order.
I am using a for loop for getting 5 records at a time.
I tired to reverse the for loop but the data still loads in ascending order.
Temp is where the json gets loaded from api.
Code:
 for (i = 0; i < temp; i++) {
   const row = resp.shift();
   $('#dataRow').append(getElement(row.name, row.id, row.address, row.time));
 }

I tried this but this din work, like it still loaded data in ascending order:
for (i = temp; i >0; i--)

I also tried unshift but that gives all records as undefined.
It would be good if data is loaded based on time. Most recent one first.
sample json:
"data":[
  {
    "name": "demo",
    "id":1,
    "address":"not available",
    "time":"2019-10-11 11:12:53"
  },
  {
    "name": "demo1",
    "id":2,
    "address":"not available",
    "time":"2019-10-11 11:12:59"
  }
]

A: You can sort resp by time in descending order first.
resp.sort((a, b) => new Date(b.time) - new Date(a.time))

Then iterate resp as normal.

A: Use prepend to insert as the first child, so the last one ends up before all the previous ones.
This is the only change you need to make:
$('#dataRow').prepend(getElement(row.name, row.id, row.address, row.time));

And just to demonstrate the reversed order:

var resp = [
  '
one
',
  '
two
',
  '
three
',
  '
four
',
  '
five
',
];

$(resp).each(function() {
  $('#dataRow').prepend(this)
})


text:
Q: Drupal8 REST-api for taxonomy terms do not work I am writing an Angular2 web app with Drupal8 in the backend. I need to convert taxonomy id's to their respective labels, for that I want to use the API endpoint "/taxonomy/term/{taxonomy_term}". I have enabled the correct REST-API and given access to all roles, however when I try to access that end-point with an ID and ?_format=json, I get the message '{"message":"Not acceptable format: json"}'. If I remove the ?format=json, however, it gives me the results I want in HTML.
This error message is found in the file /core/lib/Drupal/Core/EventSubscriber/AcceptNegotiation406.php and is preceded by the following comment:
   // If this is a render array then we assume that the router went with the
    // generic controller and not one with a format. If the format requested is
    // not HTML though we can also assume that the requested format is invalid
    // so we provide a 406 response.

Can anyone help me with this? Alternatively, I will have to scrape the taxonomy label from the HTML-result.

A: In Structure > Views, disable the "Taxonomy term" view.
This view overrides the /taxonomy/term/{taxonomy_term} endpoint created by RESTful Web Services module. It won't accept JSON-format requests unless you add a "REST Export" display yourself.


text:
Q: how to execute some code after a post is published in Wordpress I have written a simple code to do something after a post is updated or published (its related to the varnish purge). I put my code inside post.php file. Everything was just fine before the latest update (4.8.3), after that all my codes were vanished!! of course it is a normal behavior because the post.php file has  been replaced with a new one from update patch. I want to know how can I execute some code after a post is updated or published and my codes do not disappear after a Wordpress update? I don't want to use plugins too :D. Thank you.

A: You're looking for the save_post action. This allows you to add a function when a post is saved (updated).
You can hook into it like this:
function your_save_post_function( $post_id ) {
}

add_action( 'save_post', 'your_save_post_function' );

Remember to not change WordPress Core files, as these will be overwritten when WordPress is updated. You can put this code in your functions.php file, or anywhere else in your theme folder.

A: <?php
add_action( 'save_post', 'varnish_purge' );
function varnish_purge()
{
 // code here
}

A: You can replace publish_{post} , where {post} is any wordpress post type.
function post_published_notification( $ID, $post ) {
    $author = $post->post_author; /* Post author ID. */
    $name = get_the_author_meta( 'display_name', $author );
    $email = get_the_author_meta( 'user_email', $author );
    $title = $post->post_title;
    $permalink = get_permalink( $ID );
    $edit = get_edit_post_link( $ID, '' );
    $to[] = sprintf( '%s <%s>', $name, $email );
    $subject = sprintf( 'Published: %s', $title );
    $message = sprintf ('Congratulations, %s! Your article "%s" has been published.' . "\n\n", $name, $title );
    $message .= sprintf( 'View: %s', $permalink );
    $headers[] = '';
    wp_mail( $to, $subject, $message, $headers );
}
add_action( 'publish_post', 'post_published_notification', 10, 2 );


text:
Q: Translating english statements to logical statement. Scope Ambiguity? I'm working through Discrete Mathematics by Rosen and am in Section 1.6 Example 13. There are two statements made and translated as follow:
"A student in this class has not read the book"
"Everyone in this class passed the first exam"
which are rewritten in logical statements as :\
Let C(x) be "x is in this class," B(x) be "x has read the nook," and P (x) be "x passed the first exam." The remises are ∃x(C(x) ∧ ¬B(x)) and ∀x(C(x) → P (x)).
My question is why is the first statement a conjunction and the second one a conclusion ? Is this just scope ambiguity or did I miss anything obvious ?

A: Well, consider the alternatives.
Suppose we use a conditional for that first statement:
$$\exists x (C(x) \to \neg B(x))$$
Notice that this statement would be true simply by pointing to anything that is not a student in the class, because for such an object, $C(x)$ would be false, and hence the whole conditional would be true. And so, given the existence of any such object, the whole existential statement would be true ... even though it ends up saying nothing about any actual students that are in the course, and whether they read the book or not. So, this is clearly not what we want!
What we want, is that there is something that is a student and hasn't read the book, hence the conjunction.
OK, but why doesn't this work for the second statement?  Well, consider we use a conjunction there:
$$\forall x (C(x) \land P(x))$$
Notice that this statement means that all objects in the domain are students that are in the class, and have passed the first test. But wait: why would everyone in the domain have to be a student in the class?  Maybe we want the domain to also include other objects, like the teacher. So, what we want to say is that if you are a student in the class, then you passed the first test. Hence the conditional.
So yes, often (though not always!) existentials are combined with conjunctions, and universals with conditionals.  And this has nothing to do with the scope of the quantifier.


text:
Q: Transform Json object to an array of key value pairs in NiFi I have a json object in this form
{
    "email" : "test@gmail.com",
    "name" : "somename",
    "age" : "someage"
    .
    .
    .
}

I want to to translate the above json to
[{
  "key" : "email",
  "value": "test@gmail.com"
},
{
  "key" : "name",
  "value": "somename"
},
{
  "key" : "age",
  "value": "someage"
}]

I want to do the above transformation using available NiFi processors. Also, in my requirement, json object fields are dynamic and I need to build a solution to transform the object as an array of objects with key and value fields. Any suggestion would be appreciated.

A: You can use the following Spec in JoltTransformJSON:
[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "$": "[#2].Key",
        "@": "[#2].Value"
      }
    }
  }
]

Screenshot


text:
Q: How to animate Silverlight 4 ListBox items when the bound data is sorted? I'm trying to find out exactly what happens when the data bound with ItemsSource changes. So which method should I override to be able to make the items animate to their new positions in the sorted list?
From what I found out so far I might have to hijack the LayoutUpdated of the ScrollViewer inside the ListBox? How do I find out what happens there in order to be able to attach an animation to the ListBoxItems' position assignments?
Actually it would be even nicer to do this with some attached triggers and behaviors and not having to extend the ListBox class.
Edit: as it turned out both PagedCollectionView and CollectionViewSource destroys and recreates the item list on sorting, so rearranging the list with an animation doesn't seem to be possible without either implementing sorting manually by moving existing items around in the list or to create some sort of item buffer, both of which sounding like a possible source of weird bugs and performance bottleneck. If anyone has a working solution to these though I'd be glad to get any pointers!


text:
Q: Direction on a Sonar Effect? I'm in pre development for a game that will hopefully have a sonar type effect. I.e. You cant see anything, then you send out a sonar ping and as the ping hits objects they becom illuminated. Does anyone have any ideas of where I would start. I'm using cocos2d so it's a sidescroller type game. Any help would really really help.

A: Keeping it simple, here is what I would do. Every update after the sonar is sent out, use ccpDistance and check if the distance between the start of the sonar and all of the objects you want to check is less than some variable i that gets incremented every update. In effect this is basically a growing circle that checks for objects inside its radius.
If the distance is less than i, run an action on the sprite, such as [self runAction:[CCFadeOut actionWithDuration:5]]. This will show the object then fade it out over a duration of 5. If you set the object to visible = false beforehand, you should get a nice sonar effect.
If you need the direction just get the vector from the sonar start position to the object when  it is visible.

A: For illumination you could look at glColorMask - you can see it in action here http://www.youtube.com/watch?v=Bj4ts5KRSTs&t=4m36s. In terms of collision detection, you would probably want to use Box2d.


text:
Q: asp listbox set different label for values here's how I populate my listbox
ImageList.Items.Clear();
        string[] files = Directory.GetFiles(FileImageFolder, "*" + SearchTerms.Text.Replace(" ", "*") + "*");
        files = Array.FindAll(files, delegate(string f) { return IsImage(f); });

        foreach (string file in files)
        {
            if (IsImage(file))
                ImageList.Items.Add(file.Substring(file.LastIndexOf('/') + 1));
        }

it will display file name of images (together with its folder n path) on the list box. however what if I want to display other text instead of the file name (and its path) of the images on the listbox? for example maybe image1, image2 instead of images/bbla/image_1.jpg and images/bbla/cat.jpg. but I don't want to change the attached value.
thanks

A: It's very simple
int id=1;
foreach (string file in files)
{
    if (IsImage(file))
        ImageList.Items.Add(new ListItem("image"+id++,file.Substring(file.LastIndexOf('/') + 1)));
}

or you can do it as follow
foreach (string file in files)
{
    if (IsImage(file))
    {
       ListItem li=new ListItem("image"+id++,file.Substring(file.LastIndexOf('/') + 1))
       ImageList.Items.Add(li);
    }
}

or you can use Array.Length and use for loop instead of foreach loop.


text:
Q: Date to serial number? What I Have:
In A column i have id numbers and in B column i have date(mm-dd-yyyy).
What I want:
In c column I want is Id/yy.
example: 1231/18
I did try using the =CONCATENATE(A1,"/",TEXT(YEAR(B1),"yy"))
its giving #value error.

A: You can use =CONCATENATE(A1,"/",YEAR(B1))
Please check the format of enter date in B1 COLUMN.

A: You've provided very little sample data so I will just assume worst-case scenarios for all data elements and attempt error control on each.
=CONCATENATE(TEXT(A1, "0000;@"), "/", TEXT(IFERROR(DATEVALUE(B1), B1), "yy"))

If you don't require leading zeroes for IDs being less than 4 digits, change the first TEXT format mask from "0000;@" to "0;@".
In the following sample image, note that only the top date is a true date; the bottom two are text that look like dates. Likewise, A2 holds text that looks like a number.


text:
Q: HttpHandler not working in IIS 7 I have an HttpHandler configured in my web.config file like so:
<add verb="GET,HEAD,POST"
     path="TinyMCE.ashx"
     type="Moxiecode.TinyMCE.Web.HttpHandler,Moxiecode.TinyMCE" />

When I deploy to IIS 7 the handler stops working (404).
What do I need to do to get this working?

A: Registration of HttpHandlers is different for IIS7 than for previous versions of IIS. Specifically, you register the handlers in the web.config section named <system.webServer><handlers> not in <httpHandlers>.
See this question for an example.

A: We have a legacy application where changing the webconfig to user system.webServer -> handlers was not an option. We solved this 404 issue by setting the application pool's "Managed Pipeline Mode" to "Classic" on our development machines.
Here is the blog post where I found this solution http://codeskaters.blogspot.ae/2014/04/httphandler-error-404-not-found.html


text:
Q: Integral of the gaussian curvature on surface. Let $S \subset \mathbb{R}^3$ be the surface given by $x^4+y^4+z^4=1$, and let $K$ be its gaussian curvature. Then what is $\int_S K$?
First of all, I think finding patch seems hard. Should I consider 8 patches given by $(x,y,z)=(\pm \sqrt{\sin u \cos v},\pm \sqrt{\sin u \sin v},\pm \sqrt{cosu})$ where $0<u,v<\pi/2$? But then how should I deal with boudaries of the patches(for example, $u=0, v=0$)?

A: I guess you are expected to apply the Gauss-Bonnet theorem rather than calculate directly.
But if you really want to integrate $K$, the  boundaries of patches can be ignored. The surface is smooth, hence there is no singular component to  its curvature. That is, $K$ is a   continuous function, and as such integrates to zero over any set of measure zero.
If the surface was $|x|+|y|+|z|=1$ instead, then you would have to worry about the boundaries between triangular faces: in fact, all of the curvature is concentrated there. (This is  an octahedron, obviously non-smooth).

A: I changed the notation up a little bit.  In the following, I call the surface defined by $x^4 + y^4 + z^4 = 1$ $Q^2$, for "two (dimensional) quartic", instead of $S$ as does the OP; done since I need the two-sphere $S^2$ below and I wanted to avoid confusion.
The key here is to realize that the surface $x^4 + y^4 + z^4 = 1$ is diffeomorphic to the $2$-sphere  $S^2$, or more specifically,  they each have Euler-Poincare characteristic equal to $2$.  Let us denote the given surface by $Q^2$; to establish a specific diffeomophism $\phi:S^2 \to Q^2$, consider, for any point $(x, y, z) \in S^2$, the ray $t(x, y, z)$, $0 \le t < \infty$.  I claim this ray intersects $Q^2$ for a unique value of $t \ge 1$, and that $t = 1$ precisely for the points $(x, y, z) \in S^2$ such that $(x, y, z) = (\pm 1, 0, 0), (0, \pm 1, 0), (0, 0, \pm 1)$.  This is most easily seen by observing that, if $t(x, y, z) \in Q^2$, then
$t^4(x^4 + y^4 + z^4) = 1 \tag{1}$
with
$x^2 + y^2 + z^2 = 1. \tag{2}$
Now if $(x, y, z) \in  \{(\pm 1, 0, 0), (0, \pm 1, 0), (0, 0, \pm 1)\}$, (1) is clearly satisfied with $t = 1$; these points lie in $S^2 \cap Q^2$.  If, on the other hand, we have $(x, y, z) \notin  \{(\pm 1, 0, 0), (0, \pm 1, 0), (0, 0, \pm 1)\}$ satisfying (2) then we must have $0 \le x^2, y^2, z^2 < 1$, whence $x^4 < x^2, y^4 < y^2, z^4 < z^2$ so that
$x^4 + y^4 + z^4 < x^2 + y^2 + z^2 = 1; \tag{3}$
combining (1) and (3) shows that
$t^4 = (x^4 + y^4 + z^4)^{-1} > 1, \tag{4}$
i.e.
$t(x, y, z) = (x^4 + y^4 + z^4)^{-\frac{1}{4}} > 1 \tag{5}$
is the unique value of $t \in [0, \infty)$ satisfying (1).  We now define $\phi:S^2 \to Q^2$ via
$\phi(x, y, z) = t(x, y, z)(x, y, z) = (x^4 + y^4 + z^4)^{-\frac{1}{4}}(x, y, z) \tag{6}$
for $(x, y, z) \in S^2$, i.e. for $x^2 + y^2 + z^2 = 1$.  $\phi$ is easily seen to be surjective; indeed, if $(x_1, y_1, z_1) \in Q^2$, setting $s = \sqrt{x_1^2 + y_1^2 + z_1^2}$ we have $s^{-1}(x_1, y_1, z_1) \in S^2$; the corresponding value of $t$ is evidently just $s$ itself, as may be verified by a simple calculation:  for $ts^{-1}(x_1, y_1, z_1) \in Q^2$, we have $t^4 s^{-4}(x_1^4 + y_1^4 + z_1^4) = 1$, whence $t^4 s^{-4} = 1$ and so forth.  $\phi$ is injective a well:  if $(x_1, y_1, z_1), (x_2, y_2, z_2) \in S^2$ and $t_1(x_1, y_1, z_1) = t_2(x_2, y_2, z_2)$ then
$t_1^2 = t_1^2(x_1^2 + y_1^2 + z_1^2) = t_2^2(x_2^2 + y_2^2 + z_2^2) = t_2^2$, forcing
$t_1 = t_2$ and hence $(x_1, y_1, z_1) = (x_2, y_2, z_2)$ since $t_1, t_2 \ge 0$.  This $\phi:S^2 \to Q^2$ is an injective surjection; it is invertible, and the preceding argument shows that, for $(x_1, y_2, z_1) \in Q^2$, $\phi^{-1}(x_1, y_1, z_1) = s^{-1}(x_1, y_1, z_1) \in S^2$; the maps $\phi$ and $\phi^{-1}$ simply project $S^2$ and $Q^2$ onto one another along radial rays emanating from the origin $(0, 0, 0)$.  Finally, it is easily seen that both $\phi$ and $\phi_{-1}$ are $C^\infty$, in fact, real analytic maps.  Thus $\phi:S^2 \to Q^2$ is a diffeomorphism.
Having established that $Q^2$ and $S^2$ are diffeomorphic, we immediately conclude that the Euler-Poincaré characteristic $\chi(Q^2)$ of $Q^2$ is $2$, since $\chi(S^2) = 2$.  We now invoke the Gauss-Bonnet theorem in the form which asserts that for a smooth, compact surface without boundary $\Sigma$ the integral of the gaussian curvature $K$ satisfies
$\int_\Sigma K dA = 2 \pi \chi(\Sigma); \tag{7}$
taking $\Sigma = Q^2$ immediately yields
$\int_{Q^2} K dA = 4 \pi, \tag{8}$
the desired result.  QED.
Thanks to the efforts of Messers. Gauss an Bonnet, our real work here lay in establishing, rigorously, that $Q^2$ and $S^2$ are diffeomorphic.  Of course, one could in principle attempt to compute $K$ locally directly from the surface definition
$x^4 + y^4 + z^4 = 1$, but the calculations become rather messy early on in such a pursuit.  I attempted this but soon realized Gauss-Bonnet is a much more tractable approach, easy once one has $\chi(Q^2) = 2$.
Hope this helps.  Cheers,
and as always,
Fiat Lux!!!

A: By virtue of Gauss-Bonnet theorem Integra Curvatura ( in Gauss's nomenclature ) is 4 pi in a closed surface. This is the solid angle... as net sum of angle turned in tangent plane on a continuous smooth surface is zero.


text:
Q: React HOC can't pass props? I tried to pass description=Button props to Button Component using HOC.
so that, I expected to render like, `Button
But, Empty Button Elements is Rendered!
My codeSandBoxLink:enter link description here
Button.jsx
import React from 'react'
import withLoading from './withLoading'

function Button() {
    return <button></button>
}
export default withLoading(Button)

withLoading.jsx
export default function withLoading(Component) {
  const WithLoadingComponent = (props) => {
    return <Component>{props.description}</Component>
    );
  };

  return WithLoadingComponent;

App.jsx
return(

    <Button description="button"><Button>

)

Thanks for any help.

A: At Button compnent, you need to use props and follow your code so that is props.description.
function Button(props) {
  return <button>{props.description}</button>;
}

At withLoading HOC, you need to pass all props for Component.
//HOC Example
export default function withLoading(Component) {
  const WithLoadingComponent = (props) => {
    const [loading, setLoading] = React.useState(true);
    console.log("props:", props.description);
    //delay 3sec...
    React.useEffect(() => {
      const timer = setTimeout(() => {
        setLoading(false);
      }, 3000);
      return () => clearTimeout(timer);
    }, []);

    return loading ?
loading...
 : <Component {...props} />;
  };

  return WithLoadingComponent;
}

I have been fork and then fixed it. You can refer by this link:  https://codesandbox.io/s/strange-cerf-glxquu?file=/src/withLoading.jsx


text:
Q: Set of Tuples in JavaScript? What is the best way to implement a Set of coordinates in JavaScript? I would like to be able to do things like:
let s=new Set();
s.add([1,1]);
if (s.has([1,1])) // false, since these are different arrays

The above doesn't work, since the Set is storing a reference to the array instead of the contents.

A: You can subclass Set for more flexibility.

class ObjectSet extends Set{
  add(elem){
    return super.add(typeof elem === 'object' ? JSON.stringify(elem) : elem);
  }
  has(elem){
    return super.has(typeof elem === 'object' ? JSON.stringify(elem) : elem);
  }
}
let s=new ObjectSet();
s.add([1,1]);
console.log(s.has([1,1]))
console.log(s.has([1,2,3]));
console.log([...s]);
console.log([...s].map(JSON.parse));//get objects back

A: This can be done with strings:
let s=new Set();
s.add("1,1");
s.add("2,2");
console.log(s.has("1,1"), s.has("1,2")); // true false

However, I would prefer to do this with some type of numeric tuple to avoid repeated string conversion logic.

A: If you only plan to store pairs of coords, another possibility is to use a combination of a Map (for the first coord) and a Set (for the second coord).

function TupleSet() {
    this.data = new Map();

    this.add = function([first, second]) {
        if (!this.data.has(first)) {
            this.data.set(first, new Set());
        }

        this.data.get(first).add(second);
        return this;
    };

    this.has = function([first, second]) {
        return (
            this.data.has(first) &&
            this.data.get(first).has(second)
        );
    };

    this.delete = function([first, second]) {
        if (!this.data.has(first) ||
            !this.data.get(first).has(second)
        ) return false;

        this.data.get(first).delete(second);
        if (this.data.get(first).size === 0) {
            this.data.delete(first);
        }

        return true;
    };
}

let mySet = new TupleSet();
mySet.add([0,2]);
mySet.add([1,2]);
mySet.add([0,3]);
console.log(mySet.has([1,3]));
console.log(mySet.has([0,2]));
mySet.delete([0,2]);
console.log(mySet.has([0,2]));

Unfortunately, unlike a normal Set for which:

You can iterate through the elements of a set in insertion order.
— MDN Set

This approach will, for the example above, iterate in the order:
[0,2]
[0,3]
[1,2]

A: I was building a game when I came across this problem.
Here's a typescript class that might be able to help you. It uses a tree to do its magic.
You should be able to easily modify this to use arrays instead of the x and y parameters
// uses an internal tree structure to simulate set-like behaviour
export default class CoordinateSet {
  tree: Record<number, Record<number, boolean>> = {}

  add(x: number, y: number) {
    this.tree[x] ||= {}
    this.tree[x][y] = true;
  }

  remove(x: number, y: number) {
    // if the coordinate doesn't exist, don't do anything
    if (!this.tree[x] || !this.tree[y]) {
      return;
    }

    // otherwise, delete it
    delete this.tree[x][y];

    // if the branch has no leaves, delete the branch, too
    if (!Object.keys(this.tree[x]).length) {
      delete this.tree[x]
    }
  }

  has(x: number, y: number) {
    return !!this.tree[x]?.[y];
  }
}

And tests, which will also show you how it works:
import CoordinateSet from "./CoordinateSet";

describe("CoordinateSet", () => {
  it("Can add a coordinate", () => {
    const cs = new CoordinateSet();
    expect(cs.has(1,1)).toBeFalsy();
    cs.add(1, 1);
    expect(cs.has(1,1)).toBeTruthy();
  });

  it("Can remove a coordinate", () => {
    const cs = new CoordinateSet();
    cs.add(1, 1);
    expect(cs.has(1,1)).toBeTruthy();
    cs.remove(1,1);
    expect(cs.has(1,1)).toBeFalsy();
  })
})

A: If we can assume that our tuples are finite integers, they could be encoded as a float.
class TupleSet extends Set{
    add(elem){
      return super.add((typeof elem === 'object'
                        && Number.isSafeInteger(elem[0])
                        && Number.isSafeInteger(elem[1]))
                        ? elem[0]+elem[1]/10000000 : elem);
    }
    has(elem){
      return super.has((typeof elem === 'object'
                        && Number.isSafeInteger(elem[0])
                        && Number.isSafeInteger(elem[1]))
                        ? elem[0]+elem[1]/10000000 : elem);
    }
  }
  function TupleSetParse(elem){
     return (Number.isFinite(elem)?
        [Math.round(elem),Math.round((elem-Math.round(elem))*10000000)]:elem);
  }

  let s=new TupleSet();
  s.add([1,5]);
  s.add([1000000,1000000]);
  s.add([-1000000,-1000000]);
  console.log(s.has([1,5]));  // true
  console.log(s.has([1,2]));  // false
  console.log([...s].map(TupleSetParse));
    // [ [ 1, 5 ], [ 1000000, 1000000 ], [ -1000000, -1000000 ] ]

Of course, this is limited in range. And it is fragile to some malformed input, so additional error checking should be added. However, after some testing, this method is only 25% better in speed and memory usage than the JSON.stringify approach. So, JSON is the preferred approach.


text:
Q: Why does Terraform 0.8.8 keep asking me to interactively input variables? I am using Terraform 0.8.8 and it keeps asking me to interactively input certain variables (the first being var.allowed_ips_app_elb_https_env_specific).
I have a variables.tf file which contains all of the variables I want to input, yet it keeps asking me to input them when I run a terraform plan.
All of our code has been committed to our internal Gitlab and my colleague can run the same code without it asking him to interactively inputting the variables.
The following is part of the variables.tf file that asking me to input the variables when I run the plan command.
# Allowed IPs to both dev/prod environments.
variable "allowed_ips_app_elb_https" {
  default =
  [ "*.*.*.*/*",      # *
    "*.*.*.*/*",      # *
    "*.*.*.*/*",      # *
    "*.*.*.*/*",      # *
    "*.*.*.*/*",      # *
    "*.*.*.*/*",      # *
    "*.*.*.*/*",      # *
    "*.*.*.*/*",      # *
    "*.*.*.*/*",      # *
    "*.*.*.*/*",      # *
    "*.*.*.*/*",      # *
  ]
}

^ I have removed the IPs and comments and change them to *.
Thanks,
O.R

A: Terraform 0.8.8 is almost a year old - it's possible that changes have been made since then regarding automatic parsing of .tf / variable files. Have you verified which version your colleague is running? Even if you can't upgrade to the latest, it would be a good idea to use a consistent version across teams.
In the meantime you can try explicitly loading a Terraform variable file using the var-file argument:
terraform plan -var-file=variables.tf

You should also double check that the contents of your variable file is correct - you are creating a variable called allowed_ips_app_elb_https, but somewhere in your Terraform files you are requesting a different variable called allowed_ips_app_elb_https_env_specific.


text:
Q: How to generate tiled Geo/Topo JSON? Are there any command line tools can take a Shapefile or a GeoJSON file and generate a tiled version of them?

A: From my knowledge, your best option is use Tilestache.
http://tilestache.org/


text:
Q: Java Data Type for CSV File processing I am breaking my head on this problem to find a suitable data type to use, but I am not able to settle with which one would be the most efficient and simple way to program this without using any third party libraries:
Problem:
Consider Share prices for a N number of companies given for each month since year 1990 in a CSV file. Format of the file is as below with first line as header.
Year,Month,Company A, Company B,Company C, .............Company N
1990, Jan, 10, 15, 20, , ..........,50
1990, Feb, 10, 15, 20, , ..........,50
.
.
.

.
2013, Sep, 50, 10, 15............500
Output:
List for each Company year and month in which the share price was highest.
I've considered using trees, Hashmap, Lists but I am unable to finalise THE ONE solution. I am a newbie to Java with a couple of weeks of Java coding experience so far. Any help in the form of pseudo code, program or what data type to use is appreciated.

A: Ok, there are countless way to do this but my favorite one is to create a Company class to hold the Company.name, Company.month, Company.year, Company.price and use the Map to add the data.  The adding logic would then check the map to see if a company with the same name exist, if not exist or the new company price is larger simply put the new company data to the map with company name as key.  Well, the following code is just for demonstrating the purpose, I would make use eclipse to generate the getters/setters and use those instead of direct member variable just like the demo.  And this demo lack the reading and collecting company data from CSV file.
CompanyLoader.java
package org.cnci.poc;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class CompanyLoader {
   private List<Company> companies;
   private int lastReadIdx=0;

   public CompanyLoader() {
   }

   // Simply read the CSV and return the next set of company data
   private Company getNextCompanyData() {
      if (companies == null) {
         lastReadIdx = 0;
         try {
            loadCompanies();
         } catch (Exception e) {
         }
      }
      if (companies == null) return null;
      if (lastReadIdx < companies.size()) return companies.get(lastReadIdx++);
      return null;
   }

   public void loadCompanies() throws Exception {
      Scanner s = null;
      try {
         companies = new ArrayList<Company>();
         File f = new File("test.csv");
         System.out.println(f.getAbsolutePath());
         s = new Scanner(new FileInputStream(f));
         String[] headers = readLine(s);
         System.out.println("headers: " + Arrays.toString(headers));
         if (headers != null && headers.length >0) {
            String[] data = null;
            while ((data = readLine(s)) != null) {
               System.out.println("data: " + Arrays.toString(data));
               if (data.length != headers.length) {
                  companies = null;
                  throw new Exception("Invalid Data - headers count " + headers.length + " does not match with data count "+data.length);
               }
               String year = data[0];
               String month = data[1];
               for (int x=2; x<data.length; x++) {
                  double price = new Double(data[x]).doubleValue();
                  Company company = new Company(headers[x], year, month, price);
                  companies.add(company);
               }
            }
         }
      } finally {
         if (s != null) s.close();
      }
   }

   private String[] readLine(Scanner s) {
      if (s.hasNextLine()) {
         return s.nextLine().trim().split(",");
      }
      return null;
   }

   public void processCompanies() {
      Map<String, Company> companies = new HashMap<String, Company>();
      Company newCompany = null;

      // repeat until all company data processed from CSV file
      while ((newCompany = getNextCompanyData()) != null) {
         Company oldCompany = companies.get(newCompany.getName());
         if (oldCompany == null || newCompany.getPrice() > oldCompany.getPrice())
            companies.put(newCompany.getName(), newCompany);
      }
      // Done, now display the winners
      for (String name : companies.keySet()) {
         Company company = companies.get(name);
         System.out.println(company.getName() + " highest price " + company.getPrice() + " is " + company.getMonth() + " " + company.getYear());
      }
   }

   public static void main(String[] args) {
      CompanyLoader loader = new CompanyLoader();
      loader.processCompanies();
   }
}

Company.java
package org.cnci.poc;

public class Company {
   private String name;
   private String year;
   private String month;
   private double price;

   public Company(String name, String year, String month, double price) {
      super();
      this.name = name;
      this.year = year;
      this.month = month;
      this.price = price;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getYear() {
      return year;
   }
   public void setYear(String year) {
      this.year = year;
   }
   public String getMonth() {
      return month;
   }
   public void setMonth(String month) {
      this.month = month;
   }
   public double getPrice() {
      return price;
   }
   public void setPrice(double price) {
      this.price = price;
   }

   @Override
   public String toString() {
      return "Company [name=" + name + ", year=" + year + ", month=" + month + ", price=" + price + "]";
   }
}

test.csv
Year,Month,Company A,Company B,Company C,Company D,Company N
1990, Jan, 10, 15, 20, 31, 50
1990, Feb, 11, 14, 21, 30, 51

output:
C:\Projects\Java\POC\test.csv
headers: [Year, Month, Company A,  Company B, Company C,  Company D,  Company N]
data: [1990,  Jan,  10,  15,  20,  31,  50]
data: [1990,  Feb,  11,  14,  21,  30,  51]
Company B highest price 15.0 is  Jan 1990
Company C highest price 21.0 is  Feb 1990
Company N highest price 51.0 is  Feb 1990
Company A highest price 11.0 is  Feb 1990
Company D highest price 31.0 is  Jan 1990

A: Well . you should read each line in as a String.  Then, for each line after the title, you might follow one of several strategies: create an array of date, and an array of float for the stock price for each company
Or create a Company Object that itself has an array of  for date and stock price)
you will need an "addDatePrice(date, price) method in the Company object.  You can create the right number of companies from info in the title csv line (and give the Company object a nam)


text:
Q: Changing the character value to numeric for set of variables I am new to R and need help on how to convert character values to numeric.
I am reading 19 variables from a CSV file and they contain following values:
EXTREMELY IMPORTANT-10   ----> This should be actually value 10
9
8
and so on
NOT AT ALL IMPORTANT-01  ----> This should be actually value 01.

Now I need to change values of all these 19 variables from character to numeric
I have written following code and it is giving me error.
path <- "C:/Rajesh-Pandit/SPSS-Trial/BANKING/Salary-Account"
setwd(path)

library(foreign)

final_data <- read.csv("Rajhi-R.csv",header = TRUE, sep = ",")
str(final_data)

x <- (as.data.frame(final_data[,c(15:33)]))

summary(x)

y <- as.matrix(19)
importance <- as.matrix(19)

for(i in (1:19)){
  if (x[i] == "EXTREMELY IMPORTANT-10")   {y[i] <- 10}
  else if (x[i] == "NOT AT ALL IMPORTANT-01")  {y[i] <- 1}
  else if (x[i] == "02") {y[i] <- 2}
  else if (x[i] == "03") {y[i] <- 3}
  else if (x[i] == "04") {y[i] <- 4}
  else if (x[i] == "05") {y[i] <- 5}
  else if (x[i] == "06") {y[i] <- 6}
  else if (x[i] == "07") {y[i] <- 7}
  else if (x[i] == "08") {y[i] <- 8}
  else if (x[i] == "09") {y[i] <- 9}
}
y

importance <- y

Basically x[i] character values are not changing to y[i]. Please give me feedback as to why for and if are not working in this case.

A: You can try this.
library('dplyr')
library('purrr')
library('magrittr')
# use map_if() if you want to round all numeric columns/vectors into 2 decimals
x %<>% mutate_each(funs(as.numeric)) %>% map_if(is.numeric, round, 2)


text:
Q: How can I access the functions from the a directive in JEST? I need to do unit tests in JEST for a directive in Angular 1.x.
Can anybody help me with an example? What I don't know is how I can access the functions from the directive to test them
This is the directive:
angular.module("SEOMod").directive("bfNewToOldTag", [
    "$window",
    "NavigationContext",
    "ROUTE_STATES",
    "$location",
    "BF.SPORT",
    function($window, navigationContext, ROUTE_STATES, $location, bfSport) {
        "use strict";

        let oldURL = navigationContext.view;
        let checkIfNew =  new RegExp("seo");

        function getSportNameEN(id){
            return bfSport.type[id].eventTypeName;
        }

        function getTopDomain() {
            let basePath = "/exchange/plus";
            return $location.protocol() +"://"+ $location.host() + (($location.port() !== 80)?":"+$location.port() : "")+basePath;
        }

       function appendScriptTag() { ...}

        return {
            restrict: "E",
            replace: true,
            controller() {
                appendScriptTag();
            }
        };
    }
]);

This is what I tried
describe("Seo Directive", () => {
    const $window = {};
    const navigationContext = {};
    const ROUTE_STATES = {};
    const $location = {};
    const bfSport = {};

    beforeEach(() => {
        $location.protocol = jest.fn();
        $location.host = jest.fn();
        $location.port = jest.fn();

        navigationContext.view = jest.fn();
    });
    it("should return the sport name in EN", () => {

    });
});


text:
Q: Best practice for offline compatibilty of mobile web app using MySQL and PHP I've been creating a mobile web app wich has a MySQL database back-end and some simple PHP fetch querys to get SQL datasets and put them into an array for further processing with JavaScript.
Right now, everything is built in one file called index.php.
What would be the best practice, to make the site offline compatible. The SQL Data needs to be stored into the local storage with HTML5 somehow and I would probably need to separate the PHP code into an own file and include the query with AJAX, right?
Are there any code examples for that?

A: You might take a look at BreezeJS.  It has support for MySQL and greatly simplifies managing JSON data offline.  You load the data as JSON, which BreezeJS saves in its EntityManager and then you can serialize the data and save it into local storage.  It's very fast and very simple to use once you work through a few examples
var exportData = manager.exportEntities();
window.localStorage.setItem('myOfflineData', exportData);


text:
Q: How to fix 'Unhandled Rejection (TypeError): state.categories.concat is not a function' in react? I am using redux for state management and while trying to add a new data entry I am getting this error.
The following is the code for my reducer
import { ADD_CATEGORY_SUCCESS } from "../actions/type";
const initialState = {
  categories: [],
  status: null,
  statusType: null
};

export default function(state = initialState, action) {
  switch (action.type) {
    case ADD_CATEGORY_SUCCESS:
      console.log(action.payload);
      console.log(state.categories);
      return {
        categories: state.categories.concat(action.payload),
        status: 200,
        statusType: "addCategory"
      };
    default:
      return state;
  }
}

The console.log's for the first one returned an object and for the second one an array of objects. The data is getting added on the database. So I cant understand where the problem is.

A: Hmm why don't you try this, I've only changed the concat to spread operation
import {ADD_CATEGORY_SUCCESS } from '../actions/type';
const initialState = {
categories: [],
status: null,
statusType: null
}

export default function (state = initialState, action) {
  switch (action.type) {
    case ADD_CATEGORY_SUCCESS:
      console.log(action.payload);
      console.log(state.categories);
      return {
         categories: [...state.categories.categories,action.payload],
         status:200,
         statusType: "addCategory"
      }
     default:
       return state;
   }
}

A: In case state.categories is an array:
Array.concat() accepts an array while action.payload is an object.
In your case you can try one of those solutions:
return {
  // Concat
  categories: state.categories.concat([action.payload]),

  // Spead operator
  caregories: [...state.categoris, action.payload],
  ...
}


text:
Q: Regular expression that matches "articles" but not "articles-main"? How would I write a regular expression that matches any URL containing the segment "articles" followed by any other segment, but does NOT match URLs with the segment "articles-main"?
So it would match these:
www.mysite.com/articles
www.mysite.com/articles/tinman

But not these:
www.mysite.com/articles-main
www.mysite.com/articles-main/tinman

This is for use in ExpressionEngine if it matters.

A: Use a so called negative lookahead:
articles(?!-main)

or more precisely:
mysite.com/articles(?!-main)

A: to run counter to @Regexident's advice, i'd recommend a positive lookahead articles(?=$|\/).
This is saying to match articles and see if it is followed by a / character or the end of the string. That way it won't matter whether you're matching against, "articles-main" or "articlessomethingelse".
What this won't do is check if articles is its own directory. A value of http://example.com/some-articles will match, which might not be acceptable.
If you don't care about whether the / characters are included in the match, you could use a regular expression along the lines of:
\/articles(?=\/|$)

If you do care and you're using PHP's pcre functions, you could use a positive lookbehind ((?<=)):
(?<=\/)articles(?=\/|$)

More information about these regex assertions can be found on the php.net website.

A: Look for "articles/". With your examples regex might be a little overkill.


text:
Q: Updating array in a function causes pointer lose I am trying to divide my code into functions, I have a sample code of "Game Of Life".
However, when I try to initialize 2D grid array in a function, gnuplot gives no valid data points error.
These are global variables declared before main:
static char **currWorld=NULL, **nextWorld=NULL

This is the original logic to init game grid, but this part is in main.
if (game == 0){ // Use Random input
    for(i=1;i<nx-1;i++){
        for(j=1;j<ny-1;j++) {
            currWorld[i][j] = (real_rand() < prob);
            population[w_plot] += currWorld[i][j];
        }
    }
}
else if (game == 1){ //  Block, still life
    printf("2x2 Block, still life\n");
    int nx2 = nx/2;
    int ny2 = ny/2;
    currWorld[nx2+1][ny2+1] = currWorld[nx2][ny2+1] = currWorld[nx2+1][ny2] = currWorld[nx2][ny2] = 1;
    population[w_plot] = 4;
}
else if (game == 2){ //  Glider (spaceship)
    printf("Glider (spaceship)\n");
    // Your code codes here
}
else {
    printf("Unknown game %d\n",game);
    exit(-1);
}

This is my function:
  int init_game(int choice, int probability){

    int i,j;
    if (choice == 0){ // Use Random input
        for(i=1;i<nx-1;i++){
            for(j=1;j<ny-1;j++) {
                currWorld[i][j] = (real_rand() < probability);
                population[w_plot] += currWorld[i][j];
            }
        }
    }
    else if (choice == 1){ //  Block, still life
        printf("2x2 Block, still life\n");
        int nx2 = nx/2;
        int ny2 = ny/2;
        currWorld[nx2+1][ny2+1] = currWorld[nx2][ny2+1] = currWorld[nx2+1][ny2] = currWorld[nx2][ny2] = 1;
        population[w_plot] = 4;
    }
    else if (choice == 2){ //  Glider (spaceship)
        printf("Glider (spaceship)\n");
        // Your code codes here
    }
    else {
        printf("Unknown game %d\n",choice);
        exit(-1);
    }
}

and my function call in main:
init_game(game, prob);

value of game is 0, prob is 0.2 and I tested memory allocations and other stuff, they work fine.
Only difference is I moved the logic to a function. How can this happen? My arrays are global, I cannot understand how it cannot be initialized.
This is the gnuplot error:
Skipping data file with no valid points

Since gnuplot and other functions are works fine, I did not add them but if you need any info, I can add.
Here is the link of file itself:
file


text:
Q: Proof that if an algebraic integer is rational, it is integer? There is a well-known fact that the intersection of  and ℚ is ℤ. It is mentioned in many places, including Wikipedia, without proof. Does this theorem have a well-known name, and where can i find the proof?

A: In elementary contexts, one can refer to this as the monic case of the  Rational Root test (RRT).
More generally, $\,\Bbb Z\,$ is integrally closed (in $\Bbb  Q),\,$ since $ $ Euclidean $\,\Rightarrow$ PID $\Rightarrow$ gcd domains are integrally-closed (the  proof of RRT in $\,\Bbb Z\,$ immediately generalizes to any domain with gcds).


text:
Q: How to import part of spreadsheet from xlsm into Access DB Recently I started to use Access since I can use Excel functions to manipulate data in Access which quite useful. Unfortunately, MySQL doesn't have needed functions.
So now I am trying to move all scripts, etc to work with Access DB.
I want to make button which will allow me to load data from let's say Sheet_Name, Cells A:D into Access table (acc_table), which already exists. Before insert data, table should be cleaned out and replaced with new data from A:D table AND first 5 lines to be ignored.
I know how to import CSV file but it inserts whole table and I don't know how to specify Sheet name of .xlsm file and how to mention to ignore some lines.
This is how I import whole CSV file into Access DB:
Sub doit()

    ' Create an instance of the Access application object.
    Dim objAccess As Access.Application
    Set objAccess = CreateObject("Access.Application")

Dim curworkday As String
curworkday = Range("A3").Value
MsgBox curworkday
Dim CSVfile As String
CSVfile = "C:\1.csv"
MsgBox CSVfile
    ' Check that this is the path on YOUR PC for
    Const conPATH = "C:\1.accdb"
    objAccess.OpenCurrentDatabase conPATH
    objAccess.Visible = True

     ' do the Transfer
    objAccess.DoCmd.TransferText acImportDelim, "", _
    "acc_table", CSVfile, True

    ' close out the mdb
    objAccess.Quit
    Set objAccess = Nothing

End Sub


text:
Q: Possible to configure rails to load per project .irbrc file? Can rails load .irbrc from the rails project root such as ~/rails-projct/.irbrc. Rather then ~/.irbrc. Since it would be nice to add configuration that's specific to a project.

A: Per the docs:

IRB reads from ~/.irbrc when it's invoked.
If ~/.irbrc doesn't exist, irb will try to read in the following order:

*

*.irbrc

*irb.rc

*_irbrc

*$irbrc

Meaning that this is possible, but only if you don't have a .irbrc file in your home directory. Tested and confirmed in Ruby 2.7.
If that's not possible, you'll have to rely on command line options and/or environment variables.


text:
Q: Postgres find the incorrect datapoint I am inserting a bunch of values into a table from an external csv that I got from somewhere. My table columns are expected to be:
     Column       |            Type             | Modifiers
-------------------+-----------------------------+-----------
 name              | text                        |
 info              | text                        |
 other             | text                        |
 value1            | numeric(6,3)                |
 value2            | numeric                     |
 someOtherValue    | numeric(6,3)                |
 timestampX        | timestamp without time zone |

db=# refresh materialized view <table_name>;
ERROR:  invalid input syntax for integer: "2001-09-07 16:30:00.000"

I imagine there is an issue with the file I am importing from. How could I find the problematic row?


text:
Q: Regex for selecting two types of ID In a table I have an ID field that may vary e.g.
ID

*

*4.01.03.137

*0.000.00.3562

Note that the second level could have two or three digits depending on the type of product. I have tried make a query to split that table in two tables, one containing just data with two digits and another one with the three digits data, but I was unable to succeed using regex.
Any help would be appreciated.

A: for two  digits
SELECT * FROM TestTable
WHERE ID LIKE '%.[0-9][0-9].%.%'

for three digits
SELECT * FROM TestTable
WHERE ID LIKE '%.[0-9][0-9][0-9].%.%'


text:
Q: Have a specific nested UL element open upon page load Here's the JSFiddle
I've created a very simple "archive tree" that uses nested ULs and LIs to browse through years, months and days. Currently, I have one problem that I'd like to solve:
If you click any of the day links that lead to another page, I'd like for the whole thing to stay open to that month. (For example, like having an "active" class for a navbar element, only in this case, the UL element would display as a block on the new page for that month, as if it had been opened previously. I have tried adding a separate class to display as a block, but it does not change (see JSFiddle).
.month-active {
    display: block;
}

<button class="navbutton">key5</button>

<button class="navbuttoninner">key53</button>

Test link

Test link

A: You can add a data attribute to each link, then set a localStorage item with the value for the last link clicked. And on page load, if the localStorage item is set, show that element and traverse back up the DOM and show the parents, too.
Since this won't work in the sandbox on SO, here's a fiddle. https://jsfiddle.net/pppL1rwx/4/

if (localStorage.lastClicked) {
  $('[data-id="' + localStorage.lastClicked + '"]').parentsUntil('.parent').each(function() {
    $(this).siblings().addBack().slideDown();
  });
}

$('.year-button, .month-button').click(function(e) {
  e.stopPropagation();
  $(this).children('ul').slideToggle();
  var clicked = e.target.getAttribute('data-id');
  if (clicked) {
    localStorage.lastClicked = clicked;
  }
});
.navbutton {
  -webkit-appearance: none;
  background-color: #cfa9db;
  border: none;
  color: white;
  padding: 9px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  width: 100%;
  font-weight: bold;
  transition: all 0.2s ease 0s;
}

.navbuttoninner {
  -webkit-appearance: none;
  background-color: #cfa9db;
  border: none;
  color: white;
  padding: 9px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  width: 290px;
  font-weight: bold;
  transition: all 0.2s ease 0s;
}

.archive_year {
  font-size: large;
  font-weight: bold;
  cursor: pointer;
  list-style: none;
}

.archive_month {
  list-style: none;
  font-weight: normal;
  cursor: pointer;
}

.archive_dayList {
  margin-left: 32px;
  list-style: none;
  font-weight: normal;
  cursor: pointer;
}

.month-button {
  padding-top: 6px;
}

.archive_day {
  padding-top: 6px;
}

.archive_month,
.archive_dayList {
  display: none
}

      <button class="navbutton">2017</button>

          <button class="navbuttoninner">June</button>

Test link

Test link

          <button class="navbuttoninner">July</button>

Test link

Test link


text:
Q: Vaadin Button Submit I am using a Vaadin table to display some reprts. While my submit button is working, if I click again it's showing the same data multiple times (duplicates). My code is
Button executeSearchButton = new Button("Search");
executeSearchButton.addListener(new Button.ClickListener() {
    @Override
    public void buttonClick(ClickEvent event) {
        if(caseId != null || sitename != null || menunames != null )
        runSerachPage(searchTable, caseId.getValue().toString(), sitename.getValue().toString(), menunames);
    }
});

A: Looks like you doesn't clear table before inserting new records.
I assume that you should have something like table.removeAllItems() in runSerachPage before adding new items.


text:
Q: Cannot get username in spring boot The problem is: When I use JpaRepository and use a method to get the user by username like the code below:
public interface UserRepository extends JpaRepository<User, Integer> {

    @Query(value = "select * from users where username = :name", nativeQuery = true)
    User findUserByName(@Param("name") String name);
}

This is the entity:
@Entity
@Table(name = "users")
@Data
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "username", nullable = false, unique = true)
    private String username;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "joined_date", nullable = false, unique = true)
    @CreatedDate
    private Date joinedDate;

    @Column(name = "password")
    private String password;

    @Column(name = "bio")
    private String bio;

    @Column(name = "email", nullable = false, unique = true)
    private String email;
}

And this is the controller:
@RestController
@RequestMapping("/u")
public class UserController {
    @Autowired
    private UserRepository repo;
    ....

    @GetMapping("/{name}")
    public ResponseEntity<User> getUsernameAndPasswordByName(@PathVariable("name") String name) {
        User user = repo.findUserByName(name);

        if(user == null) {
            return new ResponseEntity(HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }
}

This is the entire data of JSON while getting all user from DB:

And when I get user from name(the url: localhost/u/{username}):

I assure that the name entered from the URL is correct.

A: you have duplicate mappings in your UserController for the path /u/{name}. getUserById and getUsernameAndPasswordByName have same endpoints.

A: The error states that you have mapped two RestController methods with similar path:
getUsernameAndPasswordByName and getUserById.
Try have different @GetMapping values, for example: @GetMapping("/name/{name}"), @GetMapping("/id/{id}").

A: You have two methods with the same mapping
1 - getUsernameAndPasswordByName(@PathVariable("name") String name)
@GetMapping("/{name}")
2 - getUserById(@PathVariable("id") int id)
@GetMapping("/{id}")

and this is ambiguous for spring;
just change one of mappings to something like this:
@GetMapping("/find-by-id/{id}")

A: Spring is not able to distinguish between getUsernameAndPasswordByName(String) and getUserById(Integer) because your mapping is ambiguous.
Try to use a query parameter for the getUsernameAndPasswordByName(String) method, it will be more appropriate like -
    getUsernameAndPasswordByName(@PathVariable("name") String name)

    //and

    getUserById(@PathVariable("id") int id)


text:
Q: Missing Pokemon Go coins? I have a problem with Pokecoins. The last three days I was playing and my bag was full. I slept, then in the morning I found that my Pokecoins were less by almost 4000 coins! I opened my bag I found that the capacity is 600 and got 3 Lucky Eggs, 200 Balls and 3 Incense. I contacted support and they haven't replied yet.
Did anyone experience this issue? Are they going to return my coins back if there is a bug?

A: If you attempted to purchase things but got an error, that may be the same issue I ran into. I tried to purchase a single Incubator, but it gave an error and said to try again later. Following instructions, I tried again later. Same error. I tried again, and at least one more time. About an hour later, I looked at my profile screen and saw I had 0 coins instead of the 600 I was supposed to have. It had actually processed each purchase despite telling me to try again.
The support for the game seems to be nonexistent at the moment. I also have received no response to my complained about a glitch taking 3 eggs without giving pokemon and with 3 paid-for incubator uses deducted.


text:
Q: Angular js ng-model not accessible for textbox control in template directive on master page asp.net i am not able to access Model for textbox, please find code below.
HTML Tag, which i am using
{{name.An}}<input type="text"
style="width:515px;" ng-value="{{name.An}}" ng-model="name.An"
id="topmost[0]" />

Also,Please find the directive which i use.
angularform.directive("formChange",function($compile){
 return{
 restrict:"EA",
 terminal:true,
 priority:1000,
 scope:{},
 transclude:true,
 templateUrl:"../../app/Pages/dpang.html",
 css:"../../Common/Styles/style.css"
}
})

Also the controller function is
$scope.LoadFieldData = function () {
debugger;
alert('function called.')
$scope.name.An = 'An is my name';
}

I am calling the directive like this in a div on master page.master.
<form-change/>

but when i am trying to access the variable {{name.An}}, only {{name.an}} is displayed on the html  screen, instead of the value of variable "An is my name".
Can anybody please help.

A: Not sure if it will work with iFrame like you are trying in the plnkr.
You should use the directive tag like this:
<teen-internal></teen-internal>

Also in your directive you dont need the empty scope:
myApp.directive('teenInternal', function() {
  return {
    restrict: 'AE',
    templateUrl: 'teen-external.html'

  };
});

This is should work. Plunker
Cheers,


text:
Q: How can I prove the equality of $\sup(A)$ and $sup(A\setminus B)?$ If $\emptyset\neq A\subseteq\mathbb{R}$ is a set bound from above, and $A$ does not have a maximal value, and $B\subseteq A$ and $B$ has a maximal value, how can I prove that $\sup(A)=\sup(A\setminus B)$?
Doesn't this seem impossible?

A: Since $B$ has a maximum there exists some $a \in A$ such that $b \leq a$ for all $b \in B$. Since $A$ does not have a maximal value there exists some $x > a$ with $x \in A$, otherwise $a$ would be maximal. Since all $x > a$ are not in $B$ we have $\sup (A \setminus B) = \sup A$.


text:
Q: Is google analytics important in my app? So i paid someone to do an app for me. I tried to publish it to the app store but it got rejected because of this:

"PLA 3.3.12. We found your app uses the iOS Advertising Identifier but
  does not include ad functionality."

I heard Google Analytics was often the cause of this problem. I don't know if deleting this plugin will ruin my app. It's a really simple game so i don't think google analytics really matters... I just want to know if i can delete Google Analytics safely without ruining my app and what's the best way to remove a plugin.

A: update your Google Analytics up to 3.03c if you want use GA anyway.
https://developers.google.com/analytics/devguides/collection/ios/changelog
Change log says 'No changes to Google Analytics directly. GA users should note that Google Tag Manager no longer has a dependency on AdSupport.framework by default.'
related GA issue page
https://code.google.com/p/analytics-issues/issues/detail?id=387


text:
Q: HTML table header continues to be repeated for each row in the table For someone may be nonsense, but neither are some days that I can get on top.
I have this code that I create a table from a query I would like the column header was repeated each line.
$contenuto="

 Data
Cognome
Nome
Data di Nascita
Luogo di nascita
Luogo del fatto
Ora

 ";

while ($riga = mysql_fetch_assoc($risultato)) {

$contenuto .= "".$riga["data"]."	";
$contenuto .= "".$riga["cognome"]."	";
$contenuto .= "".$riga["nome"]."	";
$contenuto .= "".$riga["data_nasc"]."	";
$contenuto .= "".$riga["luogo"]."	";
$contenuto .= "".$riga["luogo_fatto"]."	";
$contenuto .= "  ".$riga["ora"]."	";
$contenuto .= "
Fatto
".$riga["fatto"]."
";
$contenuto .= "
Descrizione del fatto

".$riga["descri"]."
";

}

How can I do?

A: This one will help you simply you can place the header part with in it
 echo "
";
 $contenuto="

 Data
     Cognome
      Nome
       Data di Nascita
       Luogo di nascita
      Luogo del fatto
       Ora

 ";

      while ($riga = mysql_fetch_assoc($risultato)) {
          echo $contenuto.  "".$riga["data"]."	".$riga["cognome"]."	".$riga["nome"]."	".$riga["data_nasc"]."	 ".$riga["luogo"]."	".$riga["luogo_fatto"]."	".$riga["ora"]."

Fatto

".$riga["fatto"]."

Descrizione del fatto

".$riga["descri"]."
";
         }

You have missed few tr tags. I added those two. This one will help you sure.

A: Just insert the code inside the while..
while ($riga = mysql_fetch_assoc($risultato)) {

 Data
          Cognome
          Nome
          Data di Nascita
          Luogo di nascita
          Luogo del fatto
          Ora

 ";

 }

A: $head='*head html sentence*';

while ($riga = mysql_fetch_assoc($risultato)) {
$contenuto .= $head;
$contenuto .= "".$riga["data"]."	";
$contenuto .= "".$riga["cognome"]."	";
$contenuto .= "".$riga["nome"]."	";
$contenuto .= "".$riga["data_nasc"]."	";
$contenuto .= "".$riga["luogo"]."	";
$contenuto .= "".$riga["luogo_fatto"]."	";
$contenuto .= "  ".$riga["ora"]."	";
$contenuto .= "
Fatto
".$riga["fatto"]."
";
$contenuto .= "
Descrizione del fatto

".$riga["descri"]."
";

}