Macro/constant as a function argument?

Suppose I have file.c and file.h. In file.h:

#ifndef FILE_H #define FILE_H  #define N  3  #endif 

then in file.c, I have a function that uses this macro:

#include <file.h>  int foo() {      return N + 1; } 

Now, I have another file2.c that calls foo function.

My question is should foo simply be foo(), or should it be refactored to foo(int num) { return num + 1; }, then in file2.c, I simply call foo(N)?

About an argument in the paper “Commutators on $\ell_\infty$” by Dosev and Johnson

In the paper “Commutators on $ \ell_\infty$ ” by Dosev and Johnson, in Lemma 4.2 Cas II, the authors have said that “There exists a normalized bock basis $ \{u_i\}$ of $ \{x_i\}$ and a normalized block basis $ \{v_i\}$ of $ \{y_i\}$ such that $ \|u_i-v_i\|<\frac{1}{i}.$ Does anyone have any idea to prove this?

More elaborately, we have two subspaces $ X$ and $ Y$ of $ \ell_\infty$ both isomorphic to $ c_0.$ $ \{x_i\}$ and $ \{y_i\}$ are bases of $ X$ and $ Y$ respectively which are equivalent to standard base of $ c_0$ . We have also $ X\cap Y=\{0\}$ and $ d(X,Y):=\inf\{\|x-y\|:x\in X,y\in Y, \|x\|=1\}=0.$ Now how to show “There exists a normalized bock basis $ \{u_i\}$ of $ \{x_i\}$ and a normalized block basis $ \{v_i\}$ of $ \{y_i\}$ such that $ \|u_i-v_i\|<\frac{1}{i}.$ ” ?

TypeError: normalize() missing 1 required positional argument: ‘text’

I’m working on a project that takes a file, goes through a specified directory and returns their similarities in %…i have been able to succeed, but the problem is converting it into GUI, the raw code works, but when implemented into the GUI (PyQt5) it raises an TypeError: normalize() missing 1 required positional argument: 'text' error…

here is the raw code

import docx import nltk, string from sklearn.feature_extraction.text import TfidfVectorizer import os from pathlib import Path from TV1 import App   def getText(filename):     doc = docx.Document(filename)     fullText = []     for para in doc.paragraphs:         fullText.append(para.text)     print('\n'.join(fullText))     return '\n'.join(fullText)   # nltk.download('punkt')  # if necessary...  stemmer = nltk.stem.porter.PorterStemmer() remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)   def stem_tokens(tokens):     return [stemmer.stem(item) for item in tokens]   '''remove punctuation, lowercase, stem'''   def normalize(text):     return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))   vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')   def cosine_sim(text1, text2):     text11 = text1     text22 = open(text2, 'r', encoding='utf-8', errors='ignore').read()     tfidf = vectorizer.fit_transform([text11, text22])      n = (((tfidf * tfidf.T) * 100).A)[0, 1]     return '%.3f%% similarity' % n  file = 'BB.docx' spath = r'C:\Users\Black Laptop\Desktop\Work'  print('---------------------------------')  text = getText(file) if os.path.exists(spath):     for path in Path(spath).iterdir():         print(path)         print(os.path.basename(path))         print(cosine_sim(text, path))         print('') 

GUI…

import sys  from PyQt5.QtCore import (QDate, QDateTime, QRegExp, QSortFilterProxyModel, Qt,                           QTime) from PyQt5.QtGui import QStandardItemModel from PyQt5.QtWidgets import (QApplication, QCheckBox, QComboBox, QGridLayout,                              QGroupBox, QHBoxLayout, QLabel, QLineEdit, QTreeView, QVBoxLayout,                              QWidget, QTableView, QTableWidget)  import docx import nltk, string from sklearn.feature_extraction.text import TfidfVectorizer import os from pathlib import Path   class App(QWidget):     FILES, SIMILAR = range(2)      def __init__(self):         super().__init__()         self.title = 'Plagiarism Checker'         self.left = 50         self.top = 50         self.width = 640         self.height = 240         # self.initUI()         self.one()      def initUI(self):[...]      def getText(self, filename):         doc = docx.Document(filename)         fullText = []         for para in doc.paragraphs:             fullText.append(para.text)         print('\n'.join(fullText))         return '\n'.join(fullText)      # nltk.download('punkt')  # if necessary...      stemmer = nltk.stem.porter.PorterStemmer()     remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)      def stem_tokens(self, tokens):         return [self.stemmer.stem(item) for item in tokens]      '''remove punctuation, lowercase, stem'''      def normalize(self, text):         return self.stem_tokens(nltk.word_tokenize(text.lower().translate(self.remove_punctuation_map)))      vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')      def cosine_sim(self, text1, text2):         text11 = text1         text22 = open(text2, 'r', encoding='utf-8', errors='ignore').read()         tfidf = self.vectorizer.fit_transform([text11, text22])          n = (((tfidf * tfidf.T) * 100).A)[0, 1]         return '%.3f%% similarity' % n      def one(self):         file = 'BB.docx'         spath = r'C:\Users\Black Laptop\Desktop\Work'          print('---------------------------------')          text = self.getText(file)         if os.path.exists(spath):             for path in Path(spath).iterdir():                 print(path)                 print(os.path.basename(path))                 print(self.cosine_sim(text, path))                 print('')   if __name__ == '__main__':     app = QApplication(sys.argv)     ex = App()     sys.exit(app.exec_()) 

ERROR..

Traceback (most recent call last):   File "C:/Users/Black Laptop/PycharmProjects/StringPatternMatcher/CT.py", line 117, in <module>     ex = App()   File "C:/Users/Black Laptop/PycharmProjects/StringPatternMatcher/CT.py", line 29, in __init__     self.one()   File "C:/Users/Black Laptop/PycharmProjects/StringPatternMatcher/CT.py", line 111, in one     print(self.cosine_sim(text, path))   File "C:/Users/Black Laptop/PycharmProjects/StringPatternMatcher/CT.py", line 93, in cosine_sim     tfidf = self.vectorizer.fit_transform([text11, text22])   File "C:\Program Files (x86)\Python36-32\lib\site-packages\sklearn\feature_extraction\text.py", line 1652, in fit_transform     X = super().fit_transform(raw_documents)   File "C:\Program Files (x86)\Python36-32\lib\site-packages\sklearn\feature_extraction\text.py", line 1058, in fit_transform     self.fixed_vocabulary_)   File "C:\Program Files (x86)\Python36-32\lib\site-packages\sklearn\feature_extraction\text.py", line 970, in _count_vocab     for feature in analyze(doc):   File "C:\Program Files (x86)\Python36-32\lib\site-packages\sklearn\feature_extraction\text.py", line 352, in <lambda>     tokenize(preprocess(self.decode(doc))), stop_words) TypeError: normalize() missing 1 required positional argument: 'text'  Process finished with exit code 1 

Any help would be appreciated…thanks

Argument handling for subclasses that use both `__init__` and `__new__`

I am making a subclass of a well-established python class: pendulum.Period, which overrides both __new__ and __init__ (it does this because it is subclassing the python builtin class timedelta, which uses __new__).

In my case, I want my class to handle a wider range of arguments than the superclass. The only way I have managed to get the code to work is to duplicate my handling code in both __new__ and __init__ — this is because, per the documentation, the arguments passed to __new__ are then passed to the __init__ of the new instance, unaltered.

The result is repeated code execution. Is this avoidable?

from pendulum import Period, Date  def _toDate(val):     """     Convert various inputs into a Date     """     if isinstance(val, int) or isinstance(val, float):         return Date.fromtimestamp(val)     elif isinstance(val, tuple):         return Date(*val)     return Date(val.year, val.month, val.day)   class MyInterval(Period):         def __new__(cls, start, end, inclusive=True, **kwargs):         start = _toDate(start)         end = _toDate(end)          if inclusive:             end = end.add(days=1)          return super(MyInterval, cls).__new__(cls, start, end, **kwargs)      def __init__(self, start, end, inclusive=True, **kwargs):         """         Creates a pendulum Period where the interval is limited to whole          days. Both are cast to dates, then the end date is incremented by          one day if inclusive=True         :param start: cast to date         :param end: cast to date         :param inclusive: [True] whether the last day of the interval should           be included (increments by 1 day)         """         start = _toDate(start)         end = _toDate(end)          if inclusive:             end = end.add(days=1)          super(MyInterval, self).__init__(start, end, **kwargs) 

Compact command line argument parser : Revisited

This question is a follow up to my previous one which can be found here. The user dfhwze suggested me to look into compiler construction and recommended me to write a lexer and a parser that would process the input step by step. I am very grateful that he pointed me into this direction, because I have the feeling everything is much more robust now. As this is my first time implementing a lexer and a parser I am convinced there are still things that can be optimized a lot.

A few things things that come to my mind:

  1. Are my naming conventions fine? Are all identifiers self-descriptive?
  2. Can I abstract the project more? I’d like it to be as flexible as possible.
  3. Are there performance optimizations that can be made?

Notes:

  1. Comma separated lists are intentionally processed as one argument.

To test the code run the unit tests (xUnit).

CommandLineLexer.cs

public class CommandLineLexer {     /// <summary>     /// To read a stream if characters     /// </summary>     private readonly TextReader _reader;      /// <summary>     /// The current token that is processed     /// </summary>     private CommandLineToken? _currentToken;      /// <summary>     /// Create a new lexer for an incoming character stream     /// </summary>     /// <param name="reader">The text reader that processes the data</param>     public CommandLineLexer(TextReader reader)     {         _reader = reader;     }      /// <summary>     /// Gets the next character in the stream     /// </summary>     /// <returns>Read the next character</returns>     private char ReadCharacter()     {         char c = (char) _reader.Read();         return c;     }      /// <summary>     /// Reads next CommandLineToken     /// </summary>     /// <returns>The next lexed token</returns>     public CommandLineToken Next()     {         var nextToken = Peek();         _currentToken = null;         return nextToken;     }      /// <summary>     /// Check next token but doesn't read it yet     /// </summary>     /// <returns>The next token</returns>     public CommandLineToken Peek()     {         if (_currentToken == null)             _currentToken = ReadNextToken();         return _currentToken.Value;     }      /// <summary>     /// Verifies if there are more character is the inputstream     /// </summary>     /// <returns>true if there are more characters, false if end of inputstream</returns>     public bool HasNext()     {         if (_currentToken == null)         {             SkipWhitespaces();             return _reader.Peek() != -1;         }          return true;     }      /// <summary>     /// Do not process whitespaces in the input unless they are part of an argument     /// </summary>     private void SkipWhitespaces()     {         while (true)         {             int c = _reader.Peek();             if (c == -1 || !char.IsWhiteSpace((char) c))                 break;             ReadCharacter();         }     }      /// <summary>     /// Read the next token     /// </summary>     /// <returns>The next lexed token</returns>     /// <exception cref="EndOfStreamException"></exception>     private CommandLineToken ReadNextToken()     {         SkipWhitespaces();          int peakedChar = _reader.Peek();         if (peakedChar == -1)             throw new EndOfStreamException(nameof(_reader));         char character = (char) peakedChar;          // Parsing Logic         switch (character)         {             case '-': return ReadSwitch();             case '"': return ReadQuotedArg();             case ',': return ReadCommaSeparator();             default:                 return ReadArg();         }     }      /// <summary>     /// Reads arguments that start and end with a quotionmark     /// </summary>     /// <returns>The lexed argument token</returns>     private CommandLineToken ReadQuotedArg()     {         var stringBuilder = new StringBuilder();          while (true)         {             stringBuilder.Append(ReadCharacter());             int chr = _reader.Peek();             if (chr == -1 || chr == '"')             {                 stringBuilder.Append("\"");                 ReadCharacter();                 break;             }         }          return new CommandLineToken(CommandLineTerminal.Argument, stringBuilder.ToString());     }      /// <summary>     /// Reads a comma separator token     /// </summary>     /// <returns>The lexed comma token</returns>     private CommandLineToken ReadCommaSeparator()     {         return new CommandLineToken(CommandLineTerminal.Comma, ReadCharacter().ToString());     }      /// <summary>     /// Reads an argument token     /// </summary>     /// <returns>The lexed comma token</returns>     private CommandLineToken ReadArg()     {         var stringBuilder = new StringBuilder();         var allowedChars = "abcdefghijklmonopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:!?.".ToList();         while (true)         {             int chr = _reader.Peek();             if (chr == -1)                 break;             if (chr == ',' || chr == ' ')                 break;             if (!allowedChars.Contains((char) chr))                 throw new FormatException($  "Illegal character in argument");              stringBuilder.Append(ReadCharacter());         }          return new CommandLineToken(CommandLineTerminal.Argument, stringBuilder.ToString());     }      /// <summary>     /// Reads an argument token      /// </summary>     /// <returns>The lexed switch token</returns>     private CommandLineToken ReadSwitch()     {         var stringBuilder = new StringBuilder();         var allowedChars = "abcdefghijklmonopqrstuvxyz-".ToList();         while (true)         {             int chr = _reader.Peek();             if (chr == -1 || chr == ' ')                 break;             if (!allowedChars.Contains((char) chr))                 throw new FormatException($  "Illegal character in switch: {(char) chr}");              stringBuilder.Append(ReadCharacter());         }          if (stringBuilder.ToString().All(x => x == '-'))             throw new FormatException("Switch does not have a name");          return new CommandLineToken(CommandLineTerminal.Switch, stringBuilder.ToString());     } } 

CommandLineToken.cs

public struct CommandLineToken {     public CommandLineTerminal Terminal { get; }     public string Text { get; }      public CommandLineToken(CommandLineTerminal terminal, string text)     {         Terminal = terminal;         Text = text;     } } 

CommandLineTerminal.cs

public enum CommandLineTerminal {     /// <summary>     /// Switch     /// </summary>     Switch,      /// <summary>     /// Argument of a switch     /// </summary>     Argument,      /// <summary>     /// Separator for a list of arguments     /// </summary>     Comma, } 

CommandLineParser.cs

public class CommandLineParser {     /* Grammar:         *          * switches <- switch+         * switch <- SWITCH args         * args <- ARGUMENT (COMMA ARGUMENT)*         */      private readonly CommandLineLexer _lexer;      public CommandLineParser(CommandLineLexer lexer)     {         _lexer = lexer ?? throw new ArgumentNullException(nameof(lexer));     }      public CommandLineParser(TextReader reader)         : this(new CommandLineLexer(reader))     {     }      public CommandLineParser(string input)         : this(new StringReader(input))     {     }       public IEnumerable<CommandLineExpression> ParseAll()     {         var parsed = new List<CommandLineExpression>();         while (_lexer.HasNext())             parsed.Add(Parse());          return parsed;     }      private CommandLineExpression Parse()     {         var @switch = ExpectOneOf(CommandLineTerminal.Switch);          // Switch without args         if (!_lexer.HasNext())             return new CommandLineExpression(@switch.Text, null);          // Verify if there are more args after switch         while (true)         {             var next = _lexer.Peek();             switch (next.Terminal)             {                 case CommandLineTerminal.Switch:                     break;                 case CommandLineTerminal.Argument:                 {                     var allArgs = ParseAllArgs();                     return new CommandLineExpression(@switch.Text, allArgs);                 }                  default:                     throw new FormatException("Invalid character");             }         }     }      private IList<IArgument> ParseAllArgs()     {         var allArgs = new List<IArgument>();         while (true)         {             if (!_lexer.HasNext())                 return allArgs;              var next = _lexer.Peek();             switch (next.Terminal)             {                 case CommandLineTerminal.Switch:                     return allArgs;                 case CommandLineTerminal.Argument:                 {                     // Check if we are dealing with an ArgList                     var token = _lexer.Next();                      if (!_lexer.HasNext())                     {                         allArgs.Add(new CommandLineArgument(token.Text));                         return allArgs;                     }                      var next2 = _lexer.Peek();                      if (next2.Terminal == CommandLineTerminal.Comma)                     {                         var argList = ParseArgList(token);                         allArgs.Add(new CommandLineArgumentList(argList));                          break;                     }                      // Add arg normally - its not part of a list                     allArgs.Add(new CommandLineArgument(token.Text));                     break;                 }                  default:                     throw new FormatException("Invalid character");             }         }     }      private List<CommandLineArgument> ParseArgList(CommandLineToken token)     {         bool commaExpected = true;         var argList = new List<CommandLineArgument>() {new CommandLineArgument(token.Text)};         while (true)         {             if (!_lexer.HasNext())                 return argList;              var next = _lexer.Peek();              switch (@next.Terminal)             {                 case CommandLineTerminal.Switch:                 {                     return argList; // kk, new swithc starts we are done processing the arglist                 }                  case CommandLineTerminal.Argument:                 {                     if (commaExpected)                     {                         // end of arg list but there is more args that do not belong to the list                         return argList;                     }                      argList.Add(new CommandLineArgument(_lexer.Next().Text));                     commaExpected = true;                      break;                 }                  case CommandLineTerminal.Comma:                 {                     if (commaExpected)                     {                         commaExpected = false;                         // consume comma                         _lexer.Next(); // ??                         break;                     }                      throw new FormatException(); // two commas after each other?                 }             }         }     }      private CommandLineToken ExpectOneOf(params CommandLineTerminal[] terminals)     {         var token = _lexer.Next();         if (!terminals.Contains(token.Terminal))             throw new FormatException($  "Expected {string.Join(",", "terminals")}");         return token;     } } 

CommandLineExpression.cs

public class CommandLineExpression {     public string Switch { get; }     public IList<IArgument> Args { get; }      public CommandLineExpression(string @switch, IList<IArgument> args)     {         Switch = @switch;         Args = args;     }     // Can this be optimized?     public override bool Equals(object obj)     {         var cmp = obj as CommandLineExpression ?? throw new ArgumentNullException(nameof(obj));         if (Switch != cmp.Switch)             return false;          if (Args == null ^ cmp.Args == null)             return false;          if (Args == null && cmp.Args == null)             return true;          if (Args.Count != cmp.Args.Count)             return false;          for (var index = 0; index < Args.Count; index++)         {             // Verify if both args are arglists             if (Args[index] is CommandLineArgumentList)             {                 // Compare args and arglists too                 if (cmp.Args[index] is CommandLineArgumentList)                 {                     // Iterate arg lists of both args                     for (var index2 = 0; index2 < ((CommandLineArgumentList) Args[index]).Arg.Count; index2++)                     {                         var argListItem1 = ((CommandLineArgumentList) Args[index]).Arg[index2];                         var argListItem2 = ((CommandLineArgumentList) cmp.Args[index]).Arg[index2];                         if (argListItem1.Argument != argListItem2.Argument)                             return false;                     }                 }                 else                 {                     return false;                 }                  continue;             }              if (cmp.Args[index] is CommandLineArgumentList)             {                 // Compare args and arglists too                 if (Args[index] is CommandLineArgumentList)                 {                     // Compare args and arglists too                     for (var index2 = 0; index2 < ((CommandLineArgumentList) Args[index]).Arg.Count; index2++)                     {                         var argListItem1 = ((CommandLineArgumentList) Args[index]).Arg[index2];                         var argListItem2 = ((CommandLineArgumentList) cmp.Args[index]).Arg[index2];                         if (argListItem1.Argument != argListItem2.Argument)                             return false;                     }                 }                 else                 {                     return false;                 }                  continue;             }              // If argument is not a list do the normal comparison             var arg = (CommandLineArgument) Args[index];             var arg2 = (CommandLineArgument) cmp.Args[index];             if (arg.Argument != arg2.Argument)                 return false;         }          return true;     } } 

CommandLineArgumentList.cs

public class CommandLineArgumentList : IArgument {     public IList<CommandLineArgument> Arg { get; }      public CommandLineArgumentList(IList<CommandLineArgument> arg)     {         Arg = arg;     } } 

CommandLineArgument.cs

public class CommandLineArgument : IArgument {     public string Argument { get; }      public CommandLineArgument(string argument)     {         Argument = argument;     } } 

IArgument.cs

public interface IArgument { } 

Please be nitpicky in the review ­čÖé

A heuristic argument why factoring an integer is difficult?

Let $ n=pq$ be the prime decomposition of $ n$ and let $ n=2^e$ . Let us suppose that $ p \equiv q \equiv \sqrt{n}$ . Let $ p_n$ be the probability to have a number $ 1 \le x \le n$ with $ 1 < \gcd(x,n) < n$ and as such to also have a non-trivial factor of $ n$ . Then we have $ $ p_n = 1-\frac{\phi(n)}{n}=1-\prod_{p|n}{(1-\frac{1}{p})} = 1-(1-\frac{1}{p})(1-\frac{1}{q}) $ $ $ $ = 1-(1-\frac{1}{\sqrt{n}})^2 = 1-(1-\frac{1}{\sqrt{2^e}})^2 $ $ Suppose there exists a factoring-algorithm which runs in polynomial time $ f(e)$ . Let $ X$ be the number of numbers $ x$ with $ 1 \lt x \lt n$ and $ 1 \lt \gcd(x,n) \lt n$ which the algorithm finds after $ f(e)$ steps. Then by definition of the algorithm we must have $ 1 = P(X \ge 1) $ But on the other hand we have $ $ P(X\ge 1) = 1 – P(X=0) = 1 – (1-p_n)^{f(e)} $ $ $ $ = 1-(1-\frac{1}{\sqrt{2^e}})^{2 \cdot f(e)} $ $ The last equality is by definition of the algorithm valid for every $ e$ . But for $ e \rightarrow \infty$ we have $ $ 1 = P(X \ge 1) = 1-(1-\frac{1}{\sqrt{2^e}})^{2 \cdot f(e)} \rightarrow_{e \rightarrow \infty} 0$ $ hence for $ e \rightarrow \infty$ we have the contradiction $ 1 = 0$ .

My question is, if someone has an idea how to replace the condition $ p \equiv q \equiv \sqrt{n}$ with a more rigorous condition. And my second question is, if this proof is logically valid, supposing $ p \equiv q \equiv \sqrt{n}$ ?

Compact command line argument parser

So, I decided to write my own little command line argument parser for various other projects I work on. I am aware that there are many good command line parser libraries, but I did wrote my own anyway (practice & implementation specific reasons).

The parser works fine, but I have a feeling that it can be improved a lot, mainly the following things come to mind

  1. Mainly the actual parser, CommandLineParser.cs. It seems very badly structured and I find it hard to read myself.
  2. Abstraction. I wonder if I can abstract it a bit more without making it a pain to use? Maybe by introducing some interfaces?
  3. Naming. I went with Option for the command line switch and with Value for the possible parameters. Are my methods/classes self-descriptive?
  4. Optimizations. I am sure there are segments that can be done more efficiently, mainly in CommandLineParser.ParseArguments(string[] args)

A couple of things to note:

  1. I’d like to keep the structure for the CommandLineValue.cs and CommandLineOption.cs mostly the same as they are part of a plugin architecture to communicate command line arguments between the plugins and the main application.
  2. No usage of Attributes to store the command line options.
  3. I did write a couple of unit tests to verify the parsers functionality. Despite them being not the main class to review, I am appreciate feedback there too ­čÖé

Parser:

public class CommandLineParser {     /// <summary>     /// Defines all possible command line options the plugin can can process     /// </summary>     public List<CommandLineOption> SupportedOptions { get; }      /// <summary>     /// Initialize the commandline parser with a list of commandline options the plugin exposes     /// </summary>     /// <param name="supportedOptions"></param>     public CommandLineParser(List<CommandLineOption> supportedOptions)     {         SupportedOptions = supportedOptions;     }       /// <summary>     /// Parse the command line arguments and returns a list of commandline values that can be passed to the     /// plugin for further processing. The function also handles invalid amount and/or format of options, values     /// as well as missing required arguments etc     /// </summary>     /// <param name="args">The arguments to parse</param>     /// <returns>A list of parsed commandline values + options</returns>     /// <exception cref="InvalidCommandLineOptionException"></exception>     /// <exception cref="InsufficientCommandLineValuesException"></exception>     /// <exception cref="InvalidCommandLineValueException"></exception>     /// <exception cref="MissingRequiredCommandLineOptionException"></exception>     public IEnumerable<CommandLineValue> ParseArguments(string[] args)     {         var result = new List<CommandLineValue>();          if (args.Length == 0)             return Enumerable.Empty<CommandLineValue>();           // Process all command line arguments         for (int i = 0; i < args.Length; i++)         {             CommandLineOption option = null;             if (!IsSupportedOption(args[i], out option))                 throw new InvalidCommandLineOptionException($  "{args[i]} is not a valid command line option");              // Verify if the option expects additional values             if (HasAdditionalValues(option))             {                 // Check if enough additional values are given                 int additionalValues = option.ParameterTypes.Count;                 if (i + additionalValues + 1 > args.Length)                     throw new InsufficientCommandLineValuesException(                         $  "{args[i]} expects {additionalValues} values.");                  // Check if the additional values are in the right format                 // ToDo: Find more elegant solution                 var values = args.ToList().GetRange(i + 1, i + additionalValues).ToList();                 var types = option.ParameterTypes.ToList();                  var castedValues = values.Zip(types, (value, type) =>                 {                     try                     {                         return Convert.ChangeType(value, type);                     }                     catch                     {                         throw new InvalidCommandLineValueException(                             $  "Cannot cast between value {value} to type {type}");                     }                 });                  result.Add(new CommandLineValue(option, castedValues.ToList()));                  // Increase i to skip to the next option                 i += additionalValues;             }             else             {                 result.Add(new CommandLineValue(option, null));             }         }          // Collect required arguments         List<string> requiredOptions = new List<string>();         foreach (var option in SupportedOptions)         {             if (option.Required)                 foreach (var tag in option.Tags)                 {                     requiredOptions.Add(tag);                 }         }          // Check that no required arguments are missing (or occur twice)         var missing = GetMissingRequiredArgs<string>(requiredOptions, args.ToList());         if (missing == null)             return result;         throw new MissingRequiredCommandLineOptionException(             $  "The required arument(s) {string.Join(",", missing)} occured multiple times");     }      /// <summary>     /// Check that all required options are used and that they (the required options) dont occur multiple times are no duplicates     /// </summary>     /// <param name="required">A list of required options</param>     /// <param name="arguments"><The args to check</param>     /// <typeparam name="T">Any primitive type</typeparam>     /// <exception cref="MissingRequiredCommandLineOptionException">Thrown if any distinct required arguments exist more then once</exception>     /// <returns>A list of missing required args, if any. Null if none are missing.</returns>     static List<T> GetMissingRequiredArgs<T>(List<T> required, List<T> arguments)     {         // convert to Dictionary where we store the required item as a key against count for an item         var requiredDict = required.ToDictionary(k => k, v => 0);          foreach (var item in arguments)         {             if (!requiredDict.ContainsKey(item))                 continue;             requiredDict[item]++; // if we have required, adding to count             if (requiredDict[item] <= 1)                 continue;             throw new DuplicateRequiredCommandLineOptionException(                 $  "Required option {item} appeared more than once!");         }          var result = new List<T>();         // now we are checking for missing items         foreach (var key in requiredDict.Keys)         {             if (requiredDict[key] == 0)             {                 result.Add(key);             }         }          return result.Any() ? result : null;     }       /// <summary>     /// Verify if given option is part of the supported options     /// </summary>     /// <returns>true if the option is supported otherwise false</returns>     private bool IsSupportedOption(string optionIdentifier, out CommandLineOption option)     {         for (var index = 0; index < SupportedOptions.Count; index++)         {             var supportedOption = SupportedOptions[index];             if (supportedOption.Tags.Any(tag => tag == optionIdentifier))             {                 option = SupportedOptions[index];                 return true;             }         }          option = null;         return false;     }      /// <summary>     /// Indicates if a command line option has multiple values or if its just a flag     /// </summary>     /// <param name="option">Commandlineoption to check</param>     /// <returns>true if the option has multiple values, otherwise false</returns>     private bool HasAdditionalValues(CommandLineOption option)     {         var noParameters = option.ParameterTypes == null || option.ParameterTypes.Count == 0;         return !noParameters;     } } 

Classes to store commandline information:

public class CommandLineOption {     /// <summary>     /// The identifier of the commandline option, e.g. -h or --help     /// </summary>     public ICollection<string> Tags { get; }      /// <summary>     /// Description of the commandline option     /// </summary>     public string Description { get; }      /// <summary>     /// Indicates if the argument is optional or required     /// </summary>     public bool Required { get; }      /// <summary>     /// Types of the additional provided values such as directory paths, values etc ..     /// </summary>     public IList<Type> ParameterTypes { get; }      /// <summary>     /// Create a new true/false commandline option      /// </summary>     /// <param name="tags">Identifier of the command line option</param>     /// <param name="description">Description of the command line option</param>     /// <param name="required">Indicates if the command line option is optional or not</param>     public CommandLineOption(IEnumerable<string> tags, string description, bool required = false)     {         Tags = tags.ToList();         Description = description;         Required = required;     }      /// <summary>     /// Create a new true/false commandline option      /// </summary>     /// <param name="tags">Identifier of the command line option</param>     /// <param name="description">Description of the command line option</param>     /// <param name="required">Indicates if the command line option is optional or not</param>     public CommandLineOption(IEnumerable<string> tags, string description, bool required = false, params Type[] parameterTypes):         this(tags, description, required)     {         ParameterTypes = new List<Type>(parameterTypes);     }  } 
public class CommandLineValue : IEqualityComparer<CommandLineValue> {     /// <summary>     /// Holds all the values specified after a command line option     /// </summary>     public IList<object> Values { get; }      /// <summary>     /// The command line option the value(s) belong to     /// </summary>     public CommandLineOption Option { get; set; }      /// <summary>     /// Stores the values that correspond to a commandline option     /// </summary>     /// <param name="option">The commandline option the values refer to</param>     /// <param name="values">The values that are stored</param>     public CommandLineValue(CommandLineOption option, IList<object> values)     {         Option = option;         Values = values;     }       public bool Equals(CommandLineValue x, CommandLineValue y)     {         if (x.Option.Description == y.Option.Description &&             x.Option.Required == y.Option.Required &&             x.Option.Tags.SequenceEqual(y.Option.Tags) &&             x.Option.ParameterTypes.SequenceEqual(y.Option.ParameterTypes) &&             x.Values.SequenceEqual(x.Values))             return true;         return false;     }      public int GetHashCode(CommandLineValue obj)     {         return base.GetHashCode();     } } 

Custom Exception Classes:

public class DuplicateRequiredCommandLineOptionException : Exception {     public DuplicateRequiredCommandLineOptionException(string message) : base(message)     {     } }  public class InsufficientCommandLineValuesException : Exception {     public InsufficientCommandLineValuesException(string message) : base(message)     {     } }  public class InvalidCommandLineOptionException : Exception {     public InvalidCommandLineOptionException(string message) : base(message)     {     } }  public class InvalidCommandLineValueException : Exception {     public InvalidCommandLineValueException(string message) : base(message)     {     } }  public class MissingRequiredCommandLineOptionException : Exception {     public MissingRequiredCommandLineOptionException(string message) : base(message)     {     } } 

Unit Tests:

public class CommandLineParserTests {           [Fact]     public void ParseDuplicateRequiredArguments()     {         var args = new[] {"--randomize", "-o", "/home/user/Documents", "--randomize", "-d"};         var supportedOptions = new List<CommandLineOption>         {             new CommandLineOption(                 new[] {"-r", "--randomize"},                 "Random flag",                 true),             new CommandLineOption(                 new[] {"-o", "--output-directory"},                 "Specifies the output directory",                 true,                 typeof(string)),             new CommandLineOption(                 new[] {"-d", "--dummy"},                 "Just another unused flag"),         };          var parser = new CommandLineParser(supportedOptions);         Assert.Throws<DuplicateRequiredCommandLineOptionException>(() =>             parser.ParseArguments(args)         );     }      [Fact]     public void ParseMissingRequiredArguments()     {         var args = new[] {"--randomize", "--output-directory", "/home/user/Documents"};         var supportedOptions = new List<CommandLineOption>         {             new CommandLineOption(                 new[] {"-r", "--randomize"},                 "Random flag"),             new CommandLineOption(                 new[] {"-o", "--output-directory"},                 "Specifies the output directory",                 true,                 typeof(string)),             new CommandLineOption(                 new[] {"-d", "--dummy"},                 "Just another unused flag"),         };          var parser = new CommandLineParser(supportedOptions);         Assert.Throws<MissingRequiredCommandLineOptionException>(() =>             parser.ParseArguments(args)         );     }      [Fact]     public void ParseMatchingTypeCommandLineValues()     {         var args = new[] {"--log", "info", "1337", "3.1415"};         var supportedOptions = new List<CommandLineOption>         {             new CommandLineOption(                 new[] {"-l", "--log"},                 "Logs info from exactly three data sources",                 false,                 typeof(string), typeof(int), typeof(float))         };          var parser = new CommandLineParser(supportedOptions);          var expectedValue = new CommandLineValue(new CommandLineOption(                 new[] {"-l", "--log"},                 "Logs info from exactly three data sources",                 false,                 typeof(string), typeof(int), typeof(float)),             new object[] {"info", 1337, (float) 3.1415});          var actualValue = parser.ParseArguments(args).ToList()[0];         Assert.True(expectedValue.Equals(actualValue, expectedValue));      }      [Fact]     public void ParseMismatchingTypeCommandLineValues()     {         var args = new[] {"--log", "info", "1337", "3.1415"};         var supportedOptions = new List<CommandLineOption>         {             new CommandLineOption(                 new[] {"-l", "--log"},                 "Logs info from exactly three data sources",                 false,                 typeof(string), typeof(int), typeof(long)),         };         var parser = new CommandLineParser(supportedOptions);          Assert.Throws<InvalidCommandLineValueException>(() =>             parser.ParseArguments(args)         );     }      [Fact]     public void ParseInsufficientCommandLineValues()     {         var args = new[] {"-l", "info", "info2"};         var supportedOptions = new List<CommandLineOption>         {             new CommandLineOption(                 new[] {"-l", "--log"},                 "Logs info from exactly three data sources",                 false, typeof(string), typeof(string), typeof(string)),         };         var parser = new CommandLineParser(supportedOptions);          Assert.Throws<InsufficientCommandLineValuesException>(() =>             parser.ParseArguments(args)         );     }      [Fact]     public void ParseInvalidCommandLineOption()     {         var args = new[] {"--force"};         var supportedOptions = new List<CommandLineOption>         {             new CommandLineOption(new[] {"-h", "--help"}, "Show the help menu"),         };         var parser = new CommandLineParser(supportedOptions);          Assert.Throws<InvalidCommandLineOptionException>(() =>             parser.ParseArguments(args)         );     }      [Fact]     public void ParseNoCommandLineOptions()     {         var args = new string[] { };         var parser = new CommandLineParser(null);         var result = parser.ParseArguments(args);          Assert.Equal(Enumerable.Empty<CommandLineValue>(), result);     } } 

I appreciate all suggestions. Feel free to be very nitpicky. ­čÖé

‘Firebase.push failed: first argument contains undefined in property ‘orders.troco_id”

Nesse meu c├│digo eu tenho dois formul├írios em pop-up, o primeiro que serve para adicionar endere├žo ou editar, e o segundo para adicionar troco ou editar o troco, ambos s├úo salvos com sucesso no seu devido lugar, esses dados que s├úo salvos v├úo para uma form em html que possui op├ž├Áes em (checkbox), ou seja l├í o usu├írio marca o endere├žo e o troco que foi enviado pelos pop ups, ent├úo assim que o usu├írio clicar em enviar formul├írio esses dados deveriam ir para o banco de dados como uma compra, porem estou tendo o retorno destes erro:

> Firebase.push failed: first argument contains undefined in property > 'orders.troco_id' 

C├│digo javascript

//Check if user already logged in firebase.auth().onAuthStateChanged(function(user) {   if (user) {     $  scope.addresses= $  firebaseArray( fireBaseData.refUser().child(user.uid).child("address") );      $  scope.trocos= $  firebaseArray( fireBaseData.refUser().child(user.uid).child("troco") );      $  scope.user_info=user;     } });  $  scope.payments = [   {id: 'CREDIT', name: 'Cart├úo de cr├ędito'},   {id: 'CASHOF', name: 'Dinheiro'} ];  $  scope.pay=function(address,payment,troco){    if(address==null || payment==null){     //Check if the checkboxes are selected ?     sharedUtils.showAlert("Aten├ž├úo!","Por favor selecione o endere├žo e o modo de pagamento.")   }   else {     // Loop throw all the cart item     for (var i = 0; i < sharedCartService.cart_items.length; i++) {       //Add cart item to order table        fireBaseData.refOrder().push({          //Product data is hardcoded for simplicity         product_name: sharedCartService.cart_items[i].item_name,         product_price: sharedCartService.cart_items[i].item_price,         product_image: sharedCartService.cart_items[i].item_image,         product_id: sharedCartService.cart_items[i].$  id,          //item data         item_qty: sharedCartService.cart_items[i].item_qty,          //Order data         user_id: $  scope.user_info.uid,         user_name:$  scope.user_info.displayName,         address_id: address,         troco_id: troco,           time: Date.now(),            status: "Na fila"       });      }      //Remove users cart     fireBaseData.refCart().child($  scope.user_info.uid).remove();      sharedUtils.showAlert("Alerta!", "Pedido feito com sucesso!");      // Go to past order page     $  ionicHistory.nextViewOptions({       historyRoot: true     });     $  state.go('lastOrders', {}, {location: "replace", reload: true});   } }    $  scope.addManipulation = function(edit_val) {  // Takes care of address add and edit ie Address Manipulator     if(edit_val!=null) {     $  scope.data = edit_val; // For editing address     var title="Ediar endere├žo";     var sub_title="Edite seu endere├žo";   }   else {     $  scope.data = {};    // For adding new address     var title="Adicionar endere├žo";     var sub_title="Adicione seu endere├žo";   }   // An elaborate, custom popup   var addressPopup = $  ionicPopup.show({     template: '<input type="text"   placeholder="Nome"  ng-model="data.nickname"> <br/> ' +     '<input type="text"   placeholder="Endere├žo" ng-model="data.address"> <br/> ' +     '<input type="text" placeholder="Cidade" ng-model="data.pin"> <br/> ' +     '<input type="number" placeholder="Telefone" ng-model="data.phone">',     title: title,     subTitle: sub_title,     scope: $  scope,     buttons: [       { text: 'Fechar' },       {         text: '<b>Salvar</b>',         type: 'button-positive',         onTap: function(e) {           if (!$  scope.data.nickname || !$  scope.data.address || !$  scope.data.pin || !$  scope.data.phone ) {             e.preventDefault(); //don't allow the user to close unless he enters full details           } else {             return $  scope.data;           }         }       }     ]   });    addressPopup.then(function(res) {      if(edit_val!=null) {       //Update  address       fireBaseData.refUser().child($  scope.user_info.uid).child("address").child(edit_val.$  id).update({    // set         nickname: res.nickname,         address: res.address,         pin: res.pin,         phone: res.phone       });     }else{       //Add new address       fireBaseData.refUser().child($  scope.user_info.uid).child("address").push({    // set         nickname: res.nickname,         address: res.address,         pin: res.pin,         phone: res.phone       });     }    });  };  $  scope.addTroco = function(edit_troco) {  // Takes care of address add and edit ie Address Manipulator   if(edit_troco!=null) {     $  scope.data = edit_troco; // For editing address     var title="Editar troco";     var sub_title="Edite aqui seu troco";   }   else {     $  scope.data = {};    // For adding new address     var title="Informar troco";     var sub_title="Informe aqui seu troco";   }   // An elaborate, custom popup   var trocoPopup = $  ionicPopup.show({     template: '<input type="text"   placeholder="Troco"  ng-model="data.troco"> <br/> ',     title: title,     subTitle: sub_title,     scope: $  scope,     buttons: [       { text: 'Fechar' },       {         text: '<b>Salvar</b>',         type: 'button-positive',         onTap: function(e) {           if (!$  scope.data.troco) {             e.preventDefault(); //don't allow the user to close unless he enters full details           } else {             return $  scope.data;           }         }       }     ]   });    trocoPopup.then(function(res) {      if(edit_troco!=null) {       //Update  address       fireBaseData.refUser().child($  scope.user_info.uid).child("troco").child(edit_val.$  id).update({    // set         troco: res.troco       });     }else{       //Add new address       fireBaseData.refUser().child($  scope.user_info.uid).child("troco").push({    // set         troco: res.troco       });     }    });  }; 

C├│digo HTML

<ion-view title="Checkout"  id="page16" >   <ion-content padding="false" class="has-header">      <form name="checkoutForm" class="list " ng-submit="pay(address_choice,pay_choice,phone,troco_choice)" >        <!--Address Header-->       <label class="item item-input  item ic-selected" >         <a class="icon icon-right ion-ios-location" style="margin-right: 10px;" ></a>         Endere├žo de entrega         <div class="right">           <button ng-click="addManipulation()" type="button" class="btn btn-success btn-xs glyphicon glyphicon-plus" style="margin-left: 10px;">Adicionar endere├žo</button>         </div>       </label>         <!-- Address -->       <ion-list  ng-repeat="item in addresses">         <ion-radio name="addr_group" ng-value="item.address" ng-model="$  parent.address_choice">           <a class="icon icon-right ion-ios-location"></a>           {{item.nickname}} <br/>           {{item.address}} <br/>           Cidade : {{item.pin}}<br/>           Telefone : {{item.phone}}         </ion-radio>        </ion-list>        <ion-list ng-repeat="user in usersss">          Telefone: {{user}}       </ion-list>        <!--troco Header-->       <label class="item item-input  item ic-selected" >         <a class="icon icon-right ion-ios-location" style="margin-right: 10px;" ></a>         Troco         <div class="right">           <button ng-click="addTroco()" type="button" class="btn btn-success btn-xs glyphicon glyphicon-plus" style="margin-left: 10px;">Adicionar troco</button>         </div>       </label>        <!-- Troco -->       <ion-list name="addr_group" ng-repeat="item in trocos">         <ion-radio ng-value="item.troco" ng-model="$  parent.troco_choice">           <a class="icon icon-right ion-ios-location"></a>           Troco para: {{item.troco}} <br/>         </ion-radio>        </ion-list>         <!--Payment Header-->       <label class="item item-input  item ic-selected" >         <a class="icon icon-right ion-cash" style="margin-right: 10px;" ></a>         Modo de pagamento       </label>         <!-- Payment Options -->       <ion-list  ng-repeat="item in payments">         <ion-radio name="pay_group" ng-value="item.name" ng-model="$  parent.pay_choice" > {{item.name}} </ion-radio>       </ion-list>         <button type="submit" class=" button button-calm  button-block icon-right ion-android-arrow-forward ">         Pagar       </button>      </form>    </ion-content>   </ion-view> 

Luxemburg norm as argument of Young’s function: $\Phi\left(\lVert f \rVert_{L^{\Phi}}\right)$

Let $ \Phi$ be a Youngs’s function, i.e. $ $ \Phi(t) = \int_0^t \varphi(s) \,\mathrm d s$ $ for some $ \varphi$ satifying

  1. $ \varphi:[0,\infty)\to[0,\infty]$ is increasing
  2. $ \varphi$ is lower semi continuous
  3. $ \varphi(0) = 0$
  4. $ \varphi$ is neither identically zero nor identically infinite

and define the Luxemburg norm of $ f:\Omega\to\mathbb{R}$ as $ $ \lVert f \rVert_{L^{\Phi}} := \inf \left\{\gamma>0\,\middle|\, \int_{\Omega} \Phi\left(\frac {\lvert f(x)\rvert}{\gamma} \right)\,\mathrm{d}x\right\}.$ $


Question: What can we say about $ \Phi\left(\lVert f \rVert_{L^{\Phi}}\right)$ ? In particular, I’d like to know, if $ $ \Phi\left(\lVert f \rVert_{L^{\Phi}}\right) \leq C \int_{\Omega}\Phi(\lvert f(x)\rvert) \,\mathrm d x$ $ holds for some $ C$ independent of $ f$ .

Any idea or hint for a reference is welome!


Notes:

  • The above inequality trivially holds for $ \Phi(t) = t^p$ , where $ p>1$
  • Maybe it’s appropriate to consider this question in the more general framework of Musielak-Orlicz spaces. However, e.g. in Lebesgue and Sobolev Spaces with Variable Exponents I was unable to find an appropriate result.
  • I have asked this question on Math.Stackexchange without luck, so I’m trying here.

argument persuasive essay examples

argument essay samples easy persuasive essay topics for high school life after high school essay abstract topics for essay internet essay topics solution to global warming essay death penalty essay introduction pros and cons essay topics essay my favorite school teacher expository essay titles
essays on determination…

argument persuasive essay examples