text:
Q: Match with RegExp in Linux Find Command with iname I need to do a massive file renaming that are scattered in different folders and subfolders. But I need to only change those files that have a specific value in an specific sequence group. The first sequence will always have a number value but the other sequences may be empty (see row 4 in example)
Example: Change the sequence value in the files that matches '123' with '888' in the second sequence group only.
From this group of files It should only accept the first four filenames
023-123-491-716-11-20170921.txt
215-123-789-014-11-20170312.txt
053-123-123-066-09-20180101.txt
088-123--066-01-20180101.txt
123-345-678-910-08-20160321.txt
966-067-076-322-08-20170312.txt
321-673-123-916-20-20170921.txt
476-976-021-123-20-20170921.txt
987-211-322-677-09-20180101.txt
123-987-123-001-09-20180101.txt
986--123-061-14-20170101.txt
186-563-123--14-20170101.txt

For this task I will use this command
$ find . -iname 'regexp' -exec rename -v '-123-' '-888-' {} \;

This is a simple valid RegExp for the task "\d+-123-\d*-\d*-\d*-\d*.txt" tested in https://regex101.com/ but is not working in find.
With the purpose of testing the regex i only need the find part, but the regexp is not matching the desired results. I tried this expressions without good results
All this shows no results:
$ find . -iname '\d+-123-\d*-\d*-\d*-\d*.txt'
$ find . -iname "[0-9]+-123-*.txt"
$ find . -iname "\([0-9]\)+-123-*.txt"
$ find . -iname "\([0-9]\)*-123-*.txt"
$ find . -iname "([0-9])+-123-*.txt"
$ find . -iname "([0-9])*-123-*.txt"

(0 results)

And this one is showing wrong results because it's not taking into account that the match value has to be exactly in the second sequence group and also ignoring the fourth row example:
$ find . -iname "[0-9]*-123-*.txt"
023-123-491-716-11-20170921.txt
215-123-789-014-11-20170312.txt
053-123-123-066-09-20180101.txt
321-673-123-916-20-20170921.txt
476-976-021-123-20-20170921.txt
123-987-123-001-09-20180101.txt

I've been checking the Emacs Syntax, but is not working either or I'm doing something really wrong. Any help is appreciated.
Thanks

A: -iname doensn't use regex for searching, it uses glob syntax.
If you want to use regex, use -iregex instead.
However, -iregex matches the full path name, not just the file name, and for searches in . that will include a leading ./.
Also, none of the regextypes supported by find supports the \d character class, so you'll have to use [0-9] or [[:digit:]] instead.
This should work:
find . -regextype posix-extended -iregex '.*/[0-9]+-123(-[0-9]+){4}\.txt'


text:
Q: Python - Why can't the methods of mutable objects be hashed? I understand that mutable objects can't be hashed, but why should this also be true of the methods on mutable objects, especially given that they compare as expected?
For example:
>>> d1, d2 = {}, {}
>>> d1.keys == d2.keys
False
>>> set([d1.keys])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

In the example, d1.keys is not itself the dict the exception complains about. Simply having a dict as an attribute is obviously no general bar to being hashable, as instances of user-created classes, by default, are both hashable and have a __dict__ attribute. A method object will not itself change in any meaningful way over it's lifetime, whether or not its __self__ component is mutable. Is there some way I'm not seeing that hashing methods on mutable object breaks the contract implied by hashing?
Below is my attempt at a wrapper that ensures a method will be hashable and also plays nice with regular method objects. For a normally unhashable method, the hash value is calculated from a tuple containing the method implementation object and the id of the method's __self__ component. Any reason this might blow up on me?
class HashableMethod(object):
    __slots__ = ['_method', '_hashval', '__weakref__']

    def __init__(self, method):
        self._method = method

    def __getattr__(self, name):
        return getattr(self._method, name)

    def __call__(self, *args, **kwds):
        return self._method(*args, **kwds)

    def __eq__(self, other):
        return self._method == other

    def __hash__(self):
        try:
            return self._hashval
        except AttributeError: # self._hashval is not yet calculated
            pass

        meth = self._method
        try:
            hashval = self._hashval = hash(meth)
        except TypeError: # self._method is not ordinarily hashable
            obj = meth.__self__
            try:
                func = meth.__func__
            except AttributeError: # self._method is builtin
                func = getattr(type(obj), meth.__name__)
            hashval = self._hashval = hash((func, id(obj)))
        return hashval

redpajama_set_name: RedPajamaStackExchange


text:
Q: get vertex coordinate after transformation OpenGL ES 1.0 I am working on a board game for android using opengl es 1.0. The game board is a polygon an there are two transformations: scale (zoom) and translate. Now I need the vertex coordinates after the transformation. I managed to get the model view matrix and the projection matrix and now I'm stuck, how do I use this data to get the new coordinates from my old vertex coordinates.

A: new vertex coordinate = projection matrix * modelview matrix * old vertex coordinate


text:
Q: Adding module name in Gradle build We just moved from Ant+Ivy builds to Gradle.My project structure is
Project A  which has two sub modules : module1 and module2

Both module1 and module2 have their own build.gradle files.The problem is when I publish an artifact from module1,I want the artifact pattern to be like :
projectA-module1.jar instead of just module1.jar

It was pretty simple to do in Ivy using:
<info organisation="abc" module="projectA-module1">

Is there any way I can change the module name in gradle?
PS: I researched and found out we have group instead of organisation in gradle but not for module name.I am publishing to Artifactory
Thanks.

A: As I understand, you just want to change the name of the project. It's easy to do in the 'settings.gradle' file. Just set the name of the project to projectA-module1:
rootProject.name = 'projectA-module1'


text:
Q: Adding a UITapGesture to UIScrollView I have a UIScrollView.  I put a tap gesture to it as this:
self.tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapped(_:)))
self.tapGesture.delegate = self
self.tapGesture.numberOfTapsRequired = 1
self.tapGesture.numberOfTouchesRequired = 1
self.tapGesture.cancelsTouchesInView = false
self.tapGesture.delaysTouchesBegan = false
self.tapGesture.delaysTouchesEnded = false
self.scrollView.addGestureRecognizer(self.tapGesture)

This works fine, except when the scrollview is scrolling (scrolling animation is happening, not user dragging), tap gesture is ignored.
How I am animating the scroll view:
UIView.animate(withDuration: 0.3, delay: 0.0,
                           options:[.beginFromCurrentState, .curveEaseInOut], animations:
    {
        self.scrollView.contentOffset = CGPoint(x:self.scrollView.contentOffset.x, y:yOffset)
    },  completion: nil)

This scrollview is scrolling most the time and I am trying to get it to recognize the tap gesture while scroll view is animating scrolling ....

A: Take a look at the UIGestureRecogniserDelegate functions.
You should be able to specify that both the pan and tap gestures can be recognised at the same time with the following function:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return (gestureRecogniser is UIPanGestureRecogniser || gestureRecogniser is UITapGestureRecogniser) && (otherGestureRecognizer is UIPanGestureRecogniser || otherGestureRecognizer is UITapGestureRecogniser)
}

Note: Ensure your class conforms to the UIGestureRecogniserDelegate protocol and you set the gestures delegate so self.
This should work, but I am unable to fully test it right now.
UPDATE:
If you are trying to recognise a tap during an animation you will likely need to use the UIViewAnimationOptions.AllowUserInteraction option in the options of UIView.animateWithDuration. Used this other answer as a source


text:
Q: How to log different types of webview javascript messages to java ide console The well-known way to log messages from webview javascript to java ide console is
webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage cm) {
                Logger.d(cm.message());
                return true;
            }
}

There is only "onConsoleMessage" method, but there is no "onConsoleError" or "onConsoleDebug" methods
But what is the best way to log different types of messages?

A: You can check to see what kind of console message you have received by looking at the MessageLevel attribute.
For example, to log only debug messages, use something similar to the below:
webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage cm) {
          if(cm.MessageLevel.valueOf("DEBUG")) {
          Logger.d(cm.message());
          }
          return true;
        }
}


text:
Q: android scrollview and scrollbar position I have a scrollview that contain a linearlayout. I need to give little margin on the right of the scrollbar of my scrollview ,i.e scrollbar should  visible inside the linearlayout not at the border.
<ScrollView
    android:fillViewport="true"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:scrollbarStyle="outsideOverlay"
    android:scrollbarAlwaysDrawVerticalTrack="true"
    android:scrollbarTrackVertical="@drawable/scrollbattrack"
    android:scrollbarThumbVertical="@drawable/scrollbarthumb"

    android:fadeScrollbars="false"
    android:layout_height="match_parent">
         <LinearLayout
            android:id="@+id/ListView"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/transparent">

          </LinearLayout>
</ScrollView>

A: Experiment with the left and right margin of the LinearLayout inside the scrollview or as said in another post with the left and right padding.

A: find equivalent for XML:i could do it using code in this way::
 ScrollView sv = new ScrollView(Activity);

 LinearLayout.LayoutParams svParams = new
 LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ht, 0.0F);

 svParams.setMargins(1, 0, 1, 0);


text:
Q: How do I convert OVERLAPPED struct to js-ctypes? I'm trying to get ReadFileEx working in js-ctypes and ran into a bit of an obstacle converting the OVERLAPPED struct to js-ctypes. Any tips on the translation would be much appreciated:
typedef struct _OVERLAPPED {
  ULONG_PTR Internal;
  ULONG_PTR InternalHigh;
  union {
    struct {
      DWORD Offset;
      DWORD OffsetHigh;
    };
    PVOID  Pointer;
  };
  HANDLE    hEvent;
} OVERLAPPED, *LPOVERLAPPED;

This is not right, but I started with
const struct_overlapped = new ctypes.StructType("overlapped",
  [ {"Internal": ctypes.uint64_t.ptr},
    {"InternalHigh": ctypes.uint64_t.ptr},
    [ [ {"Offset": ctypes.uint32_t},
        {"OffsetHigh": ctypes.uint32_t} ],
      {"Pointer": ctypes.voidptr_t} ],
    {"hEvent": ctypes.voidptr_t} ]);

but I'm not sure how to handle the "union" and the second struct.
Update. Maybe something like this?
const struct_offset = new ctypes.StructType("offsetStruct",
  [ {"Offset": ctypes.uint32_t},
    {"OffsetHigh": ctypes.uint32_t} ]);

const struct_overlapped = new ctypes.StructType("overlapped",
  [ {"Internal": ctypes.uint64_t.ptr},
    {"InternalHigh": ctypes.uint64_t.ptr},
    [ {"offsetStruct": ctypes.struct_offset},
      {"Pointer": ctypes.voidptr_t} ],
    {"hEvent": ctypes.voidptr_t} ]);

But I get an error

Message: Error: struct field descriptors must contain one property

Update 2. Maybe the first attempt will work?

A: Before getting in overlapped structs and completion routines, the solution to these synchronus blocking APIs such as WinAPI, COM, Objective-C, GTK, XCB, X11, etc etc etc is to use works.
Note that some callbacks in GTK and ObjC and X11 have to be on the main thread. And its not possible to use dispatch_queue to set up the callback on the mainthread from workers due to an unfixable bug.
Windows is full on fun with workers no sweat.
I personally love PromiseWorkers - https://developer.mozilla.org/en-US/docs/Web/API/PromiseWorker - I hacked it up so I can call functions from the mainthread from the PromiseWorker (you might not need this so I wouldn't recommend copying the PromiseWorker boiler plate from my addons)


text:
Q: Change html bootstrap markup if no featured image is selected I have a custom Joomla 3 bootstrap template based off of the Protostar template.
Currently the left main content area markup is:

If the featured image isn't set/active is there a way for the left main content markup to be this instead:

Basicaly if the right sidebar/featured image isn't set the main content area should be full-width (12 cols).
Excerpt from default.php markup for the main content area and right featured image sidebar is as follows:

  <?php
    if (!empty($this->item->pagination) && $this->item->pagination && !$this->item->paginationposition && !$this->item->paginationrelative):
        echo $this->item->pagination;
    endif;
    ?>
    <?php if (isset ($this->item->toc)) :
        echo $this->item->toc;
    endif; ?>
      <?php echo $this->item->text; ?>

        <?php if ($useDefList && ($info == 1 || $info == 2)) : ?>

<?php echo JText::_('COM_CONTENT_ARTICLE_INFO'); ?>

              <?php if ($info == 1) : ?>
                <?php if ($params->get('show_author') && !empty($this->item->author )) : ?>

                    <?php $author = $this->item->created_by_alias ? $this->item->created_by_alias : $this->item->author; ?>
                      <?php if (!empty($this->item->contactid) && $params->get('link_author') == true) : ?>
                        <?php
                        $needle = 'index.php?option=com_contact&view=contact&id=' . $this->item->contactid;
                        $menu = JFactory::getApplication()->getMenu();
                        $item = $menu->getItems('link', $needle, true);
                        $cntlink = !empty($item) ? $needle . '&Itemid=' . $item->id : $needle;
                        ?>
                          <?php echo JText::sprintf('COM_CONTENT_WRITTEN_BY', JHtml::_('link', JRoute::_($cntlink), $author)); ?>
                            <?php else: ?>
                              <?php echo JText::sprintf('COM_CONTENT_WRITTEN_BY', $author); ?>
                                <?php endif; ?>

                  <?php endif; ?>
                    <?php if ($params->get('show_parent_category') && !empty($this->item->parent_slug)) : ?>

                        <?php   $title = $this->escape($this->item->parent_title);
                        $url = 'item->parent_slug)) . '">' . $title . '';?>
                          <?php if ($params->get('link_parent_category') && $this->item->parent_slug) : ?>
                            <?php echo JText::sprintf('COM_CONTENT_PARENT', $url); ?>
                              <?php else : ?>
                                <?php echo JText::sprintf('COM_CONTENT_PARENT', $title); ?>
                                  <?php endif; ?>

                      <?php endif; ?>
                        <?php if ($params->get('show_category')) : ?>

                            <?php   $title = $this->escape($this->item->category_title);
                        $url = 'item->catslug)) . '">' . $title . '';?>
                              <?php if ($params->get('link_category') && $this->item->catslug) : ?>
                                <?php echo JText::sprintf('COM_CONTENT_CATEGORY', $url); ?>
                                  <?php else : ?>
                                    <?php echo JText::sprintf('COM_CONTENT_CATEGORY', $title); ?>
                                      <?php endif; ?>

                          <?php endif; ?>
                            <?php if ($params->get('show_publish_date')) : ?>

                                <?php echo JText::sprintf('COM_CONTENT_PUBLISHED_DATE_ON', JHtml::_('date', $this->item->publish_up, JText::_('DATE_FORMAT_LC3'))); ?>

                              <?php endif; ?>
                                <?php endif; ?>

                                  <?php if ($params->get('show_create_date')) : ?>

                                      <?php echo JText::sprintf('COM_CONTENT_CREATED_DATE_ON', JHtml::_('date', $this->item->modified, JText::_('DATE_FORMAT_LC3'))); ?>

                                    <?php endif; ?>
                                      <?php if ($params->get('show_modify_date')) : ?>

                                          <?php echo JText::sprintf('COM_CONTENT_LAST_UPDATED', JHtml::_('date', $this->item->modified, JText::_('DATE_FORMAT_LC3'))); ?>

                                        <?php endif; ?>
                                          <?php if ($params->get('show_hits')) : ?>

                                              <?php echo JText::sprintf('COM_CONTENT_ARTICLE_HITS', $this->item->hits); ?>

                                            <?php endif; ?>

          <?php endif; ?>

            <?php
if (!empty($this->item->pagination) && $this->item->pagination && $this->item->paginationposition && !$this->item->paginationrelative):
    echo $this->item->pagination;
?>
              <?php endif; ?>
                <?php if (isset($urls) && ((!empty($urls->urls_position) && ($urls->urls_position == '1')) || ($params->get('urls_position') == '1'))) : ?>
                  <?php echo $this->loadTemplate('links'); ?>
                    <?php endif; ?>
                      <?php // Optional teaser intro text for guests ?>
                        <?php elseif ($params->get('show_noauth') == true && $user->get('guest')) : ?>
                          <?php echo $this->item->introtext; ?>
                            <?php //Optional link to let them register to see the whole article. ?>
                              <?php if ($params->get('show_readmore') && $this->item->fulltext != null) :
        $link1 = JRoute::_('index.php?option=com_users&view=login');
        $link = new JURI($link1);?>

                                  <a href="<?php echo $link; ?>">
                                    <?php $attribs = json_decode($this->item->attribs); ?>
                                      <?php
        if ($attribs->alternative_readmore == null) :
            echo JText::_('COM_CONTENT_REGISTER_TO_READ_MORE');
        elseif ($readmore = $this->item->alternative_readmore) :
            echo $readmore;
            if ($params->get('show_readmore_title', 0) != 0) :
                echo JHtml::_('string.truncate', ($this->item->title), $params->get('readmore_limit'));
            endif;
        elseif ($params->get('show_readmore_title', 0) == 0) :
            echo JText::sprintf('COM_CONTENT_READ_MORE_TITLE');
        else :
            echo JText::_('COM_CONTENT_READ_MORE');
            echo JHtml::_('string.truncate', ($this->item->title), $params->get('readmore_limit'));
        endif; ?>

                                <?php endif; ?>
                                  <?php endif; ?>
                                    <?php
if (!empty($this->item->pagination) && $this->item->pagination && $this->item->paginationposition && $this->item->paginationrelative) :
    echo $this->item->pagination;
?>
                                      <?php endif; ?>
                                        <?php echo $this->item->event->afterDisplayContent; ?>

<?php if ($params->get('access-view')):?>
  <?php if (isset($images->image_fulltext) && !empty($images->image_fulltext)) : ?>
    <?php $imgfloat = (empty($images->float_fulltext)) ? $params->get('float_fulltext') : $images->float_fulltext; ?>
      <div class="pull-<?php echo htmlspecialchars($imgfloat); ?> item-image col-sm-4 col-xs-12"> <img <?php if ($images->image_fulltext_caption): echo 'class="caption"'.' title="' .htmlspecialchars($images->image_fulltext_caption) . '"'; endif; ?> src="
        <?php echo htmlspecialchars($images->image_fulltext); ?>" alt="
          <?php echo htmlspecialchars($images->image_fulltext_alt); ?>"/>

      <?php endif; ?>
        <?php endif; ?>

Here is the site itself http://dev.shareandcare.org/empoweringruralindia/signature-programs/educate-2-success-e2s

A: It appears that the image is contained in $images->image_fulltext, so you can use empty to see if it exists.
Only print the class name col-sm-8 if the image exists.
<div class="itemMainContent <?php if (!empty($images->image_fulltext)) echo "col-sm-8" ?> col-xs-12">

I'm sorry that I'm not familiar with Joomla, so I am curious how the $image variable is populated. Considering my solution takes place at the beginning of your posted code, the $image variable might not be available yet. In that case, you will need to get it first. I'm suspiciously looking at the first line of the sidebar $params->get('access-view'). You might need to call this first. I would expect it to be OK to call again later, but you might have to play with it, or someone with more experience might chime in.


text:
Q: I need a way to remove non-german letters and only allow specific characters I want to gsub a String so that I have a string in the end which has

*

*only german letters and normal Numbers

*no special characters except , . ? and !

*no leading or trailing non-printable characters

*no consecutive non-printable characters, there should only be one space between words

*there should be no whitespace in front of the allowed special characters . , ? !

*the , and . is not allowed to be the last character

Example (On two lines to be more visible for you):
'   §$%""%& Überschnell    du$§"rch   die Nacht .
    Genießen Sie Ihre Aussicht , Sie Blödm人物ann   !   $"§ '

Should become:
'Überschnell durch die Nacht. Genießen Sie Ihre Aussicht, Sie Blödmann!'

I hope it is clear what I need to the string to happen. Its for prettier titles in my Rails app when the user types anything that isnt English or german or doesnt care about right punctuation or so.
Edit: This is what works ok at the moment thanks to @mudasobwa
irb(main):021:0> str='   §$%""%& Überschnell    du$§"rch   die Nacht .   Genießen Sie Ihre Aussicht , Sie Blödm??an>
=> "   \xF5$%\"\"%& \x9Aberschnell    du$\xF5\"rch   die Nacht .   Genie\xE1en Sie Ihre Aussicht , Sie Bl\x94dm??ann   !   $\"\xF5 "

irb(main):016:0> str=str.gsub(/\s\s+/, ' ')
=> " \xF5$%\"\"%& \x9Aberschnell du$\xF5\"rch die Nacht . Genie\xE1en Sie Ihre Aussicht , Sie Bl\x94dm??ann ! $\"\xF5 "

irb(main):017:0> str=str.gsub(/[^a-zA-z\s!?.,äöüÄÄÖÜß]/, "")
=> "  \x9Aberschnell durch die Nacht . Genie\xE1en Sie Ihre Aussicht , Sie Bl\x94dm??ann !  "

irb(main):018:0> str=str.gsub(/\s+([,.!?])/, "\\1")
=> "  \x9Aberschnell durch die Nacht. Genie\xE1en Sie Ihre Aussicht, Sie Bl\x94dm??ann!  "

irb(main):019:0> str=str.strip
=> "\x9Aberschnell durch die Nacht. Genie\xE1en Sie Ihre Aussicht, Sie Bl\x94dm??ann!"

irb(main):020:0> str=str.encode("UTF-8").unicode_normalize(:nfc)
=> "Überschnell durch die Nacht. Genießen Sie Ihre Aussicht, Sie Blödm??ann!"

But when on Windows I get a Encoding::CompatibilityError: incompatible encoding regexp match (UTF-8 regexp with CP850 string)
Will this happen in the production app on HEroku also or can I just use this without worrying??

A: The main issue here would be to unicode normalize the input to :nfc form:
'   §$%""%& Überschnell    du$§"rch   die Nacht . ' \
'Genießen Sie Ihre Aussicht , Sie Blödm人物ann   !   $"§ '.
  unicode_normalize(:nfc).  # ⇐ HERE
  gsub(/\s+([,.!?])/, "\\1").
  gsub(/[^a-zA-Z,.!?äöüÄÖÜß\s]/, "").
  strip.
  squeeze

#⇒ 'Überschnell durch die Nacht. Genießen Sie Ihre Aussicht, Sie Blödmann!'


text:
Q: Как создать скрипт записывающий в файл уникальные ip и количество их посещений? Вроде бы просто, но не хватает опыта. Скрипт записывающий уникальные ip - т.е($_SERVER('REMOTE_ADDR') и количество посещений в файл ip.txt.

A: $ip = $_SERVER['REMOTE_ADDR']; // Запись IP-Адреса в переменную
$file = file('./ip.txt'); // Вместо ip.txt можно вписать другое расширение и название файла

if (in_array($ip, $file)) // Проверяем есть ли IP-Адрес в файле ip.txt и при отсутствии записываем
    echo 'Вы уже посещали эту страницу';
else
    file_put_contents('ip.txt', $ip, FILE_APPEND);

Источник


text:
Q: MySQLdb import causing error in Python 2.7.14 I have got the following error:

Traceback (most recent call last):   File "C:\Python27\databasepy.py",
  line 1, in
      import MySQLdb   File "C:\Python27\lib\site-packages\MySQLdb__init__.py", line 19, in

      import _mysql ImportError: DLL load failed: %1 is not a valid Win32 application.

While executing the following code:
import MySQLdb
from MySQLdb import Error
try:
    db = MySQLdb.Connect(host="localhost",port=3306,user="root",passwd="Azmat@123",db="test")
    cursor=db.cursor()
    cursor.execute("SELECT VERSION()")
    data=cursor.fetchone()
    print "Database version :%s " %data
    db.close()
except Error as er:
    print er


text:
Q: Unable to deploy Grails app to Tomcat 8 with JDK mismatch: 404 The requested resource is not available I found I am unable to deploy simple helloworld web application, created with Grails, onto Tomcat. It looks like Tomcat does not see application at all and regarding just a bunch of files.
I have tried to put static HTML into application and Tomcat serves it.
I have tried to set logback of webapplication (in groovy) to more verbose level and nothing happens, as if Tomcat ignores it.
UPDATE
I have removed details since the major problem appeared to be clear: it was because Tomcat on the server was running under Java 1.7 and on the development computer I was compiling for 1.8
But the question persists, because I can't understand an effect: how can it happen, that target JDK mismatch causes no error message and no exceptions, but just silent nothing happening?

A: You should read about starting tomcat, deploying and managing apps on it. Check out official documentation.
But first check out this default webapps manager: http://localhost:8080/manager/
(but I think you will need to add tomcat user before you can get it)

A: In your grails application, look into two places:

*

*application.properties and look for app.name, usually the context path is same app.name

*BuildConfig.groovyand look for grails.project.war.file. This will tell you how zip file name is structured.

If you have specific set of properties in your Config.groovy file, make sure that you add environment name in your war command. Ex war test

A: Have you tried  http://myhost/MyApp-0.1 ?
If you dont change anything in the Config.groovy, the route is similar but running over the 80 port.


text:
Q: Recognise txt file characteristics I am trying to develop a software in which the user will open a txt file filled with data.
I want to read the data but I don't know if the txt file is Delimited or Fixed Field and if is delimited what is the field delimiter (, or ; or  / etc ) or the line delimiter (CR+LF or CR or CF etc).
I know how to read a file if I know all these but can I find out these characteristics in an automatic way?
Thanks

A: You can make a good guess: look at file for inspiration.
For example:

*

*read a chunk of data (pick some size that's big enough it should contain a whole line)

*scan it for CR, LF, likely delimiter characters and whitespace

*did it have CR+LF? were they always together?

*did you find any delimiters? If you found more than one, can you see any pattern?

*did you find runs of whitespace always ending at the same column on successive lines?

etc. etc.

A: You can read the file and make some educated guesses.
Are there CR/LFs ?
If not, it's most likely fixed length, who would specify another line delimiter.
If so, read all lines and count the number of all characters individually.
Is there a character that appears on each line the same number of times?
If so, it's likely the field delimiter.
If not, it's probably fixed length fields.
If it's fixed length fields, build one line with statistics. For each character, what percentage of blanks over all lines and what percentage of non-blanks over all lines does it have? Find the points where indexes jump from very-high-blank-percentage to very-low-blank-percentage, that is likely to be a field boundary (the last field ending in blanks because it's not "full", the next starting with a non-blank because it's filled.)


text:
Q: "SyntaxError: Unexpected token < in JSON at position 0" In a React app component which handles Facebook-like content feeds, I am running into an error:

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0

I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn't seem to be the case here.
More confusingly, I rolled the code back to an earlier, known-working version and I'm still getting the error.
Feed.js:
import React from 'react';

var ThreadForm = React.createClass({
  getInitialState: function () {
    return {author: '',
            text: '',
            included: '',
            victim: ''
            }
  },
  handleAuthorChange: function (e) {
    this.setState({author: e.target.value})
  },
  handleTextChange: function (e) {
    this.setState({text: e.target.value})
  },
  handleIncludedChange: function (e) {
    this.setState({included: e.target.value})
  },
  handleVictimChange: function (e) {
    this.setState({victim: e.target.value})
  },
  handleSubmit: function (e) {
    e.preventDefault()
    var author = this.state.author.trim()
    var text = this.state.text.trim()
    var included = this.state.included.trim()
    var victim = this.state.victim.trim()
    if (!text || !author || !included || !victim) {
      return
    }
    this.props.onThreadSubmit({author: author,
                                text: text,
                                included: included,
                                victim: victim
                              })
    this.setState({author: '',
                  text: '',
                  included: '',
                  victim: ''
                  })
  },
  render: function () {
    return (
    <form className="threadForm" onSubmit={this.handleSubmit}>
      <input
        type="text"
        placeholder="Your name"
        value={this.state.author}
        onChange={this.handleAuthorChange} />
      <input
        type="text"
        placeholder="Say something..."
        value={this.state.text}
        onChange={this.handleTextChange} />
      <input
        type="text"
        placeholder="Name your victim"
        value={this.state.victim}
        onChange={this.handleVictimChange} />
      <input
        type="text"
        placeholder="Who can see?"
        value={this.state.included}
        onChange={this.handleIncludedChange} />
      <input type="submit" value="Post" />
    </form>
    )
  }
})

var ThreadsBox = React.createClass({
  loadThreadsFromServer: function () {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  handleThreadSubmit: function (thread) {
    var threads = this.state.data
    var newThreads = threads.concat([thread])
    this.setState({data: newThreads})
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: thread,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        this.setState({data: threads})
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  getInitialState: function () {
    return {data: []}
  },
  componentDidMount: function () {
    this.loadThreadsFromServer()
    setInterval(this.loadThreadsFromServer, this.props.pollInterval)
  },
  render: function () {
    return (

Feed

        <ThreadForm onThreadSubmit={this.handleThreadSubmit} />

    )
  }
})

module.exports = ThreadsBox

In Chrome developer tools, the error seems to be coming from this function:
 loadThreadsFromServer: function loadThreadsFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

with the line console.error(this.props.url, status, err.toString() underlined.
Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.
EDIT:
I've checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.
EDIT 2:
It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727 instead of the expected http://localhost:3001/api/threads.
I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What's frustrating here is that this was working correctly the last time I worked on it and can't find what I could have possibly changed to break it.

A: You're receiving HTML (or XML) back from the server, but the dataType: json is telling jQuery to parse as JSON. Check the "Network" tab in Chrome dev tools to see contents of the server's response.

A: This error occurs when you define the response as application/json and you are getting a HTML as a response. Basically, this happened when you are writing server side script for specific url with a response of JSON but the error format is in HTML.

A: Those who are using create-react-app and trying to fetch local json files.
As in create-react-app, webpack-dev-server is used to handle the request and for every request it serves the index.html. So you are getting

SyntaxError: Unexpected token < in JSON at position 0.

To solve this, you need to eject the app and modify the webpack-dev-server configuration file.
You can follow the steps from here.

A: In a nutshell, if you're getting this error or a similar error, that means only one thing: Someplace in our codebase, we were expecting a valid JSON format to process, and we didn't get one. For example,
var string = "some string";
JSON.parse(string)

will throw an error, saying

Uncaught SyntaxError: Unexpected token s in JSON at position 0

Because, the first character in string is s & it's not a valid JSON now. This can throw error in between also. like:
var invalidJSON= '{"foo" : "bar", "missedquotehere : "value" }';
JSON.parse(invalidJSON)

Will throw error:
VM598:1 Uncaught SyntaxError: Unexpected token v in JSON at position 36

because we intentionally missed a quote in the JSON string invalidJSON at position 36.
And if you fix that:
var validJSON= '{"foo" : "bar", "missedquotehere" : "value" }';
JSON.parse(validJSON)

will give you an object in JSON.
This error can be thrown in any place & in any framework/library. Most of the time you may be reading a network response which is not valid JSON. So steps of debugging this issue can be like:

*

*curl or hit the actual API you're calling.

*Log/Copy the response and try to parse it with JSON.parse. If you're getting error, fix it.

*If not, make sure your code is not mutating/changing the original response.

A: I was facing the same issue.
I removed the dataType:'json' from the $.ajax method.

A: I my case the error was a result of me not assigning my return value to a variable. The following caused the error message:
return new JavaScriptSerializer().Serialize("hello");

I changed it to:
string H = "hello";
return new JavaScriptSerializer().Serialize(H);

Without the variable JSON is unable to properly format the data.

A: In my case, for an Azure hosted Angular 2/4 site, my API call to mySite/api/... was redirecting due to mySite routing issues.  So, it was returning the HTML from the redirected page instead of the api JSON.  I added an exclusion in a web.config file for the api path.
I was not getting this error when developing locally because the Site and API were on different ports.  There is probably a better way to do this ... but it worked.
<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <system.webServer>
        <rewrite>
        <rules>
        <clear />

        <rule name="AngularJS Conditions" stopProcessing="true">
        <match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="None" />
        </rule>

        <rule name="AngularJS Wildcard" enabled="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="Rewrite" url="index.html" />
        </rule>

        </rules>
        </rewrite>
    </system.webServer>
</configuration>

2022 UPDATE: having written this several years ago.  I'd call this suggestion more of a workaround - a direct fix.  The better hosting pattern is to simply not try to host these api paths under your website path; rather, host them on separate base URLs entirely.  For my use case example, the API and Web path would be entirely separate Azure Web Services and would get different URL endpoints.

A: For future googlers:
This message will be generated if the server-side function crashes.
Or if the server-side function doesn't even exist ( i.e. Typo in function name ).
So - suppose you are using a GET request... and everything looks perfect and you've triple-checked everything...
Check that GET string one more time.  Mine was:
'/theRouteIWant&someVar=Some value to send'

should be
'/theRouteIWant?someVar=Some value to send'
               ^

CrAsH !        ( ... invisibly, on the server ...)
Node/Express sends back the incredibly helpful message:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

A: The wording of the error message corresponds to what you get from Google Chrome when you run JSON.parse('<...'). I know you said the server is setting Content-Type:application/json, but I am led to believe the response body is actually HTML.

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0"
with the line console.error(this.props.url, status, err.toString()) underlined.

The err was actually thrown within jQuery, and passed to you as a variable err. The reason that line is underlined is simply because that is where you are logging it.
I would suggest that you add to your logging. Looking at the actual xhr (XMLHttpRequest) properties to learn more about the response. Try adding console.warn(xhr.responseText) and you will most likely see the HTML that is being received.

A:
SyntaxError: Unexpected token < in JSON at position 0

You are getting an HTML file (or XML) instead of json.
Html files begin with <!DOCTYPE html>.
I "achieved" this error by forgetting the https:// in my fetch method:
fetch(`/api.github.com/users/${login}`)
    .then(response => response.json())
    .then(setData);

I verified my hunch:
I logged the response as text instead of JSON.
fetch(`/api.github.com/users/${login}`)
    .then(response => response.text())
    .then(text => console.log(text))
    .then(setData);

Yep, an html file.
Solution:
I fixed the error by adding back the https:// in my fetch method.
fetch(`https://api.github.com/users/${login}`)
    .then(response => response.json())
    .then(setData)
    .catch(error => (console.log(error)));

A: I had the same error message following a tutorial. Our issue seems to be 'url: this.props.url' in the ajax call. In React.DOM when you are creating your element, mine looks like this:
ReactDOM.render(
    <CommentBox data="/api/comments" pollInterval={2000}/>,
    document.getElementById('content')
);

Well, this CommentBox does not have a url in its props, just data. When I switched url: this.props.url -> url: this.props.data, it made the right call to the server and I got back the expected data.
I hope it helps.

A: My problem was that I was getting the data back in a string which was not in a proper JSON format, which I was then trying to parse it. simple example: JSON.parse('{hello there}') will give an error at h. In my case the callback url  was returning an unnecessary character before the objects: employee_names([{"name":.... and was getting error at e at 0. My callback URL itself had an issue which when fixed, returned only objects.

A: On a general level this error occurs when a JSON object is parsed that has syntax errors in it. Think of something like this, where the message property contains unescaped double quotes:
{
    "data": [{
        "code": "1",
        "message": "This message has "unescaped" quotes, which is a JSON syntax error."
    }]
}

If you have JSON in your app somewhere then it's good to run it through JSONLint to verify that it doesn't have a syntax error. Usually this isn't the case though in my experience, it's usually JSON returned from an API that's the culprit.
When an XHR request is made to an HTTP API that returns a response with a Content-Type:application/json; charset=UTF-8 header which contains invalid JSON in the response body you'll see this error.
If a server-side API controller is improperly handling a syntax error, and it's being printed out as part of the response, that will break the structure of JSON returned. A good example of this would be an API response containing a PHP Warning or Notice in the response body:
Notice:  Undefined variable: something in /path/to/some-api-controller.php on line 99

{
    "success": false,
    "data": [{ ... }]
}

95% of the time this is the source of the issue for me, and though it's somewhat addressed here in the other responses I didn't feel it was clearly described. Hopefully this helps, if you're looking for a handy way to track down which API response contains a JSON syntax error I've written an Angular module for that.
Here's the module:
/**
 * Track Incomplete XHR Requests
 *
 * Extend httpInterceptor to track XHR completions and keep a queue
 * of our HTTP requests in order to find if any are incomplete or
 * never finish, usually this is the source  of the issue if it's
 * XHR related
 */
angular.module( "xhrErrorTracking", [
        'ng',
        'ngResource'
    ] )
    .factory( 'xhrErrorTracking', [ '$q', function( $q ) {
        var currentResponse = false;

        return {
            response: function( response ) {
                currentResponse = response;
                return response || $q.when( response );
            },
            responseError: function( rejection ) {
                var requestDesc = currentResponse.config.method + ' ' + currentResponse.config.url;
                if ( currentResponse.config.params ) requestDesc += ' ' + JSON.stringify( currentResponse.config.params );

                console.warn( 'JSON Errors Found in XHR Response: ' + requestDesc, currentResponse );

                return $q.reject( rejection );
            }
        };
    } ] )
    .config( [ '$httpProvider', function( $httpProvider ) {
        $httpProvider.interceptors.push( 'xhrErrorTracking' );
    } ] );

More details can be found in the blog article referenced above, I haven't posted everything found there here as it's probably not all relevant.

A: Make sure that response is in JSON format otherwise fires this error.

A: I got the same error while calling an API in React using the fetch API with the POST method.
Before:
fetch('/api/v1/tour',{
      method:"POST",
      headers:{"Content-type":"json/application"},
      body:JSON.stringify(info)
    })
    .then((response)=>response.json())
    .then((json)=>{
      if(json.status === 'success')
        alert(json.message)
      else
        console.log('something went wrong :(')
    }).catch(e=>console.log(e))

I resolved the error by changing the headers to {"Content-type":"application/json"}:
After:
fetch('/api/v1/tour',{
      method:"POST",
      headers:{"Content-type":"application/json"},
      body:JSON.stringify(info)
    })
    .then((response)=>response.json())
    .then((json)=>{
      if(json.status === 'success')
        alert(json.message)
      else
        console.log('something went wrong :(')
    }).catch(e=>console.log(e))

A: This ended up being a permissions problem for me. I was trying to access a url I didn't have authorization for with cancan, so the url was switched to users/sign_in. the redirected url responds to html, not json. The first character in a html response is <.

A: In my case, I was getting this running webpack. It turned out to be corrupted somewhere in the local node_modules dir.
rm -rf node_modules
npm install

...was enough to get it working right again.

A: I experienced this error "SyntaxError: Unexpected token m in JSON at position", where the token 'm' can be any other characters.
It turned out that I missed one of the double quotes in the JSON object when I was using RESTconsole for DB test, as {"name: "math"}. The correct one should be {"name": "math"}.
It took me a lot effort to figure out this clumsy mistake. I am afraid others will run into similar issues.

A: After spending a lot of time with this, I found out that in my case the problem was having "homepage" defined on my package.json file made my app not work on firebase (same 'token' error).
I created my react app using create-react-app, then I used the firebase guide on the READ.me file to deploy to github pages, realized I had to do extra work for the router to work, and switched to firebase. github guide had added the homepage key on package.json and caused the deploy issue.

A: For me, this happened when one of the properties on the object I was returning as JSON threw an exception.
public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
    get
    {
        var count = 0;
        //throws when Clients is null
        foreach (var c in Clients) {
            count += c.Value;
        }
        return count;
    }
}

Adding a null check, fixed it for me:
public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
    get
    {
        var count = 0;
        if (Clients != null) {
            foreach (var c in Clients) {
                count += c.Value;
            }
        }
        return count;
    }
}

A: just something basic to check, make sure you dont have anything commented out in the json file
//comments here will not be parsed and throw error

A: This might be old. But it just occurred in Angular where the content type for request and response were different in my code. So check headers for
 let headers = new Headers({
        'Content-Type': 'application/json',
        **Accept**: 'application/json'
    });

in React axios
axios({
  method:'get',
  url:'http://  ',
 headers: {
         'Content-Type': 'application/json',
        Accept: 'application/json'
    },
  responseType:'json'
})

jQuery Ajax:
 $.ajax({
      url: this.props.url,
      dataType: 'json',
**headers: {
          'Content-Type': 'application/json',
        Accept: 'application/json'
    },**
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

A: For some, this may help you guys:
I had a similar experience with Wordpress REST API. I even used Postman to check if I had the correct routes or endpoint. I later found out that I accidentally put an "echo" inside my script - hooks:
Debug & check your console
Cause of the error
So basically, this means that I printed a value that isn't JSON that is mixed with the script that causes AJAX error - "SyntaxError: Unexpected token r in JSON at position 0"

A: In my case (backend), I was using res.send(token);
Everything got fixed when I changed to res.send(data);
You may want to check this if everything is working and posting as intended, but the error keeps popping up in your front-end.

A: The possibilities for this error are overwhelming.
In my case, I found that the issue was adding the homepage filed in package.json caused the issue.
Worth checking: in package.json change:
homepage: "www.example.com"

to
hompage: ""

A: In my Case there was problem with "Bearer" in header ideally it should be "Bearer "(space after the end character) but in my case it was "Bearer" there was no space after the character. Hope it helps some one!

A: Malformed JSON or HTML instead of JSON is the underlying cause of this issue, as described by the other answers, however in my case I couldn't reliably replicate this error, as if the server was sometimes returning valid JSON, and other times returning something else like an HTML error page or similar.
In order to avoid it breaking the page altogether, I resorted to manually trying to parse the returned content, and share it in case it helps anyone else resolve it for them.
const url = "https://my.server.com/getData";

fetch(url).then(response => {
  if (!response.ok) return; // call failed

  response.text().then(shouldBeJson => { // get the text-only of the response
    let json = null;
    try {
      json = JSON.parse(shouldBeJson); // try to parse that text
    } catch (e) {
      console.warn(e); // json parsing failed
      return;
    };
    if (!json) return; // extra check just to make sure we have something now.

    // do something with my json object
  });
});

While this obviously doesn't resolve the root cause of the issue, it can still help to handle the issue a bit more gracefully and take some kind of reasonable action in instances when it fails.

A: If you receive this error in a Chrome extension it can be tough to track down, especially if it occurs when you install the extension. However, I found a way that makes it easier.
I had a Chrome extension that called some scripts from my web server on installation of the plugin, pulling down some default settings. I received the error:
SyntaxError: Unexpected token < in JSON at position 0 in _generated_background_page.html

When you get this go into Extensions, find your extension, click the "background page" hyperlink, and the inspector will open for it. Then, go to Network and press CTRL+R. Now, you'll see all the things that the background page had to load.
Click on each one, especially ones that connect back to a remote server. You'll see Headers in the Network tab, followed by a Preview. Look at the Preview for each of the items. If you see something other than the expected header for this data, or you see errors, then that's likely your cause.
In my case, my server script was calling another script and that script had a bug in it because of missing variables at runtime, which then made my application/json header not match with the data it was sending, resulting in the unexpected token error.

A: In my case, when sending the data in the test API node the JSON object had an extra comma at the end like:

POST   http://localhost:9000/api/posts/
Content-Type: application/json

{
    "title": "sokka",
    "description": "hope this works",
    "username": "sokka blog4",
}

so I only needed to remove the extra comma and send this kind of data:

POST   http://localhost:9000/api/posts/
Content-Type: application/json

{
    "title": "sokka",
    "description": "hope this works",
    "username": "sokka blog4"
}

I was using the RESTclient extension to test my API.

A: For the React app made by CRA there are two main problems we might face while fetching the JSON data of any <dummy.json>
file.
I have my dummy.json file in my project and am trying to fetch the JSON data from that file but I got two errors:
"SyntaxError: Unexpected token < in JSON at position 0 .

I got an HTML file rather than actual JSON Data in the response in the Network tab in Chrome or any browser.
Here are the main two reasons behind that which solved my issue.

*

*Your JSON data is invalid in your JSON file.

*It might be that the JSON file did not load properly for this so you just restart your React server. This is my issue, within React.

React direct running or access the public folder not the src folder.
How I solved it:
I moved my file into the public folder and access is directly in any file of the src folder.

Making a REST call in the Redux action.js:
export const fetchDummy = ()=>{
return (dispatch)=>{
        dispatch(fetchDummyRequest());
        fetch('./assets/DummyData.json')
        .then(response => {
            if (!response.ok) {
                throw new Error("HTTP error " + response.status);
            }
            return response.json();
        })
        .then(result => {
            dispatch(fetchDummySuccess(result))
        })
        .catch(function (err) {
          dispatch(fetchDummyFailure(err))
        })
    }
}

A: Protip: Testing json on a local Node.js server? Make sure you don't already have something routing to that path
'/:url(app|assets|stuff|etc)';

A: In python you can use json.Dump(str) before send result to html template.
with this command string convert to correct json format and send to html template. After send this result to JSON.parse(result) , this is correct response and you can use this.

A: In most cases, I get this error, when API throws an error with text format.
What I suggest is to see the error text content to figure out what is wrong going on.

*

*jQuery =>
set dataType: 'text'

*fetch =>
reponse.text() instead of reponse.json()

A: Check the end point address that you are making the request.
If it's misspelled this may be the reason of error because the end point returns HTML

A: Maybe some permission error would be there just try switching the browser and log in from an authorized account.

A: If anyone else is using fetch from the "Using Fetch" documentation on Web API's in Mozilla:
(This is really useful: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)
  fetch(api_url + '/database', {
    method: 'POST', // or 'PUT'
    headers: {
     'Content-Type': 'application/json'
    },
    body: qrdata //notice that it is not qr but qrdata
  })
  .then((response) => response.json())
  .then((data) => {
    console.log('Success:', data);
  })
  .catch((error) => {
  console.error('Error:', error);  });

This was inside the function:
async function postQRData(qr) {

  let qrdata = qr; //this was added to fix it!
  //then fetch was here
}

I was passing into my function qr what I believed to be an object because qr looked like this: {"name": "Jade", "lname": "Bet", "pet":"cat"} but I kept getting syntax errors.
When I assigned it to something else: let qrdata = qr; it worked.

A: If you try to run this line of code in the console:
JSON.parse(undefined);

you will get the same error message:
"SyntaxError: Unexpected token < in JSON at position 0"

Therefore, your app is trying to parse an invalid JSON undefined.

A:
Unexpected token < in JSON at position 0

A simple solution to this error is to write a comment in styles.less file.

A: Just to add to the answers, it also happens when your API response includes
<?php{username: 'Some'}

which could be a case when your backend is using PHP.

A: This might cause due to your javascript code is looking at some json response and you received something else like text.


text:
Q: How to stop creating instance of Singleton I have a Singleton class like this:
class Singleton {
    static class SingletonHolder {
        static final Singleton INSTANCE = new Singleton();
    }
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

Can I call like this from other class:
Singleton dummy = new Singleton();

if yes how can I disable it? if not, then why cannot i?

A: Sure.  Just make the constructor private to avoid that: just add private Singleton() {} to prevent the default constructor from being public.

A: I suggest you make it an enum (since they can't be instantiated anyway);
enum Singleton {
    INSTANCE;
    public static Singleton getInstance() {
        return INSTANCE;
    }
}


text:
Q: To become (a)... Usage of the indefinite article
His ambition is to become a musician.
  She became queen in 1952.
  How
  to be governor

In what cases do we use the indefinite article in expressions with "be", "become" and when we don't?

A: It is context based.
If for instance, the conversation was about England and the queen, "she became queen" is correct because there is only one queen. "she became the queen" would also be acceptable.
"How to be governor" or "How to be the governor" would both be as acceptable as "How to be a governor", but it's based on the context of the conversation.
Basically, if you can add "the" before the noun and it's still make sense, then you don't need "a". "His ambition is to become the musician" would not make sense, therefore you use "a".


text:
Q: The conditions in the definition of Poisson process (and a Lévy process generalization) Last week, George Lowther provided a rather sophisticated counter-example of a continuous process $\{W(t):t \geq 0\}$ with $W(0)=0$ and $W(t)-W(s) \sim {\rm N}(0,t-s)$ for all $0 \leq s < t$, yet not a Brownian motion; see link text.
Apparently, his approach relied heavily on special properties of BM.
Now, what about the analogue for a Poisson process: Can you find an example of a càdlàg (right-continuous with left limits) process $\{X(t):t \geq 0\}$ with $X(0)=0$ and $X(t)-X(s) \sim {\rm Poi}(t-s)$ for all $0 \leq s < t$, yet not being a Poisson process?
Bonus question: If the last question turns out to be too easy to answer (etc.), then what about the general Lévy process case? That is, given a Lévy process $X$ (defined below) with law $\mu_t$ at time $t>0$, does there exist a càdlàg process $\tilde X$ with $\tilde X(0) = 0$ and $\tilde X(t)-\tilde X(s) \sim \mu_{t-s}$  for all $0 \leq s < t$, which is yet not identical in law to $X$ (hence not a  Lévy process)? [Here, assume that $X$ is non-deterministic, equivalently, $\mu_t$ is not a $\delta$-distribution.]
Definition: A stochastic process $X=\{X(t):t \geq 0\}$ is a Lévy process (say, real-valued) if the following conditions are satisfied: (1) $X(0)=0$ a.s.; (2) $X$ has independent increments; (3) $X$ has stationary increments; (4) $X$ is stochastically continuous; (5) Almost surely, the function $t \mapsto X(t)$ is right-continuous (for $t \geq 0$) and has left limits (for $t>0$). [In fact, condition (4) is implied by (1), (3), and (5).]
PS: you are still welcome to try and find a simpler counter-example for the Brownian motion case.

A: You cannot define a Lévy process by the individual distributions of its increments, except in the trivial case of a deterministic process Xt − X0 = bt with constant b. In fact, you can't identify it by the n-dimensional marginals for any n.

1) Let X be a nondeterministic Lévy process with X0 = 0 and n be any positive integer. Then, there is a cadlag process Y with a different distribution to X, but such that (Yt1,Yt2,…,Ytn) has the same distribution as (Xt1,Xt2,…,Xtn) for all times t1,t2,…,tn.

Taking n = 2 will give a process whose increments have the same distribution as for X.
The idea (as in my answer to this related question) is to reduce it to the finite-time case. So, fix a set of times 0 = t0 < t1 < t2 < … < tm for some m > 1.
We can look at the distribution of X conditioned on the ℝm-valued random variable U ≡ (Xt1,Xt2,…,Xtm). By the Markov property, it will consist of a set of independent processes on the intervals [tk−1,tk] and [tm,∞), where the distribution of {Xt }t ∈[tk−1,tk] only depends on (Xtk−1,Xtk) and the distribution of {Xt }t ∈[tm,∞) only depends on Xtm. By the disintegration theorem, the process X can be built by first constructing the random variable U, then constructing X to have the correct probabilities conditional on U. Doing this, the distribution of X at any one time only depends on the values of at most two elements of U (corresponding to Xtk−1,Xtk). The distribution of X at any set of n times depends on the values of at most 2n values of U.
Choosing m > 2n, the idea is to replace U by a differently distributed ℝm-valued random variable for which any 2n elements still have the same distribution as for U. We can apply a small bump to the distribution of U in such a way that the m − 1 dimensional marginals are unchanged. To do this, we can use the following.

2) Let U be an ℝm-valued random variable with probability measure μ. Suppose that there exist (non-trival) measures μ1,μ2,…,μm on the reals such that μ1(A1)μ2(A2)…μm(Am) ≤ μ(A1×A2×…×Am) for all Borel subsets A1,A2,…,Am ⊆ ℝ.
  Then, there is an ℝm-valued  random variable V with a different distribution to U, but with the same m − 1 dimensional marginal distributions.

By 'non-trivial' I mean that μk is a non-zero measure and does not consist of a single atom.
By changing the distribution of U in this way, we construct a new cadlag process with a different distribution to X, but with the same n dimensional marginals.
Proving (2) is easy enough. As μk are non-trivial, there will be measurable functions ƒk on the reals, uniformly bounded by 1 and such that μk(ƒk) = 0 and μk(|ƒk|) > 0. Replacing μk by the signed measure ƒk·μk, we can assume that μk(ℝ) = 0.
Then
$$
\mu_V = \mu + \mu_1\times\mu_2\times\cdots\times\mu_m
$$
is a probability measure different from μ. Choosing V with this distribution gives
$$
{\mathbb E}[f(V)]=\mu_V(f)=\mu(f)={\mathbb E}[f(U)]
$$
for any function ƒ: ℝm → ℝ+ independent of one of the dimensions. So, V has the same m − 1 dimensional marginals as U.
To apply (2) to U = (Xt1,Xt2,…,Xtm), consider the following cases.

*

*X is continuous. In this case, X is just a Brownian motion (up to multiplication by a constant and addition of a constant drift). So, U is joint-normal with nondegenerate covariance matrix. Its probability density is continuous and strictly positive so, in (2), we can take μk to be a multiple of the uniform measure on [0,1].

*X is a Poisson process. In this case, we can take μk to be a multiple of the (discrete) uniform distribution on {2k,2k + 1} and, as X can take any increasing nonnegative integer-valued path on the times tk, this satisfies the hypothesis of (2).

*If X is any non-continuous Lévy process, case 2 can be used to change the distribution of its jump times without affecting the n dimensional marginals: Let ν be its jump measure, and A be a Borel set such that ν(A) is finite and nonzero. Then, X decomposes as the sum of its jumps in A (which occur according to a Poisson process of rate ν(A)) and an independent Lévy process. In this way, we can reduce to the case where X is a Lévy process whose jumps occur at a finite rate, with arrival times given by a Poisson process.
In that case, let Nt be the Poisson process counting the number of jumps in intervals [0,t]. Also, let Zk be the k'th jump of X. Then, N and the Zk are all independent and,
$$
X_t=\sum_{k=1}^{N_t}Z_k.
$$
As above, the Poisson process N can be replaced by a differently distributed cadlag process which has the same n dimensional marginals. This will not affect the n dimensional marginals of X but, as its jump times no longer occur according to a Poisson process, X will no longer be a Lévy process.

A: Based on the comments to this answer, I no longer believe what I initially wrote (still appearing at the bottom of the answer). It seems to me a construction should be possible. It is at least possible in the case of a Binomial point process.
Let $\{X_i\}_{i \in \mathbb{N},i\neq 4}$ be independent Bernoulli$(1/2)$ random variables.
Let $X_4'$ be Bernoulli$(1/2)$ and independent of the $X_i$. Then define $X_4$ as follows:

*

*$X_4 = 1$ if $(X_1,X_2,X_3)$ is either $(0,0,1)$ or $(1,1,0)$,

*$X_3 = 0$ if $(X_1,X_2,X_3)$ is either $(0,1,0)$ or $(1,0,1)$,

*$X_4=X_4'$ otherwise.

Then for all $j \geq 0$, $n \geq 1$, $X_{j+1}+\ldots+X_{j+n}$ has Binomial$(n,1/2)$ distribution but the family $(X_n)_{n \in \mathbb{N}}$ are not iid.

What appears below (where I suggested such a construction was impossible) is false.

For a standard Poisson process, this won't be possible. (See this question and its answer.)
Edit: Given the comments perhaps I should provide more detail.
With probability one, for every pair $0 < p < q$, $p,q$ rationals, $X(q)−X(p)$ is a non-negative integer. Since X is cadlag the same property must hold for every real pair $0 < s < t$, i.e. $X$ is increasing and integer-valued.
Let us also show that $X$ has no jumps of size more than one: with probability one, for all $x > 0$, $X(x^-) := \lim_{y \uparrow x} X(y) \geq X(x)-1$. If this failed to hold then there would be $\epsilon > 0$ and $t < \infty$ so that
$$
\mathbb{P}(\exists x \in [0,t), X(x)-X(x^-) \geq 2) > \epsilon/2.
$$
But since $X$ is increasing, for any positive integer $n$ we can bound this probability from above by
$$
\sum_{1 \leq i < 2n} \mathbb{P}(X((i+1)t/2n)-X((i-1)t/2n) \geq 2)
$$
the point being that these intervals are chosen to overlap so that a jump of size $\geq 2$ must fall in at least one of them. Each of the differences above is distributed as Poisson$(t/n)$,
so the associated probability is $o(n^{-1})$ as $n \to \infty$ and thus the whole sum tends to zero as $n \to \infty$.
We then know that a process $X$ such as you describe must be increasing and integer valued, with all jumps of size $1$. In other words, $X$ is a point process on $[0,\infty)$. Now the answer from the other thread implies that $X$ must be a rate one Poisson process.


text:
Q: Laravel factories being consumed by table seeders and tests. Best practices/How to do it I'm trying to write some Laravel factories so that we can seed all tables upfront and also use them for tests.
I'm not very experienced with testing and I have some doubts on which premises should factories be built.
Let's use this simple example, 2 tables:

*

*users

*notes

Notes have a user_id field with a FK.
Should I make the notes factory to be able to create users (calling users factory) or expect that in any test that I try to create notes I
 have already created users that can be associated with the notes?
Please give some practical example if you may.

A: Relationship while seeding can be done. Try this code in your NoteFactory.
'user_id' => function(){
      return App\User::all()->random();
}

Note that your UserFactory should run first and then NoteFactory.


text:
Q: SQL Search for records with missing values in the same table I have a table (t1) with multiple rows of statuses for different references,  one column being a ReferenceID and another column being a StatusID.
t1.ReferenceID - t1.StatusID
A1 - 1
A1 - 2
A1 - 3
A1 - 4
A2 - 1
A2 - 3
A3 - 1
A3 - 3
A4 - 1
A4 - 4
A5 - 2
A5 - 3
I have a second table (t2) which is the list of all available StatusID's
t2.StatusID
1
2
3
4
I need to be able to pull a list of ReferenceID's from t1 where StatusID '1' exists, however it is missing one or more of the other StatusID's in table 2.
i.e. using the above the following referenceID's would be returned:
A2
A3
A4

A: Don;t know if this will work on SQLAnywhere.
SELECT  DISTINCT r.ReferenceID
FROM    (SELECT ReferenceID FROM TableName WHERE StatusID = 1 GROUP BY ReferenceID) r
        CROSS JOIN (SELECT StatusID FROM TableName GROUP BY StatusID) d
        LEFT JOIN TableName a
            ON  d.StatusID = a.StatusID AND
                r.ReferenceID = a.ReferenceID
WHERE   a.StatusID IS NULL
ORDER   BY r.ReferenceID

*

*SQLFiddle Demo (running in MySQL)


text:
Q: Clean nulls from query pivot table in MySql I have the following dataset as an example in MySql engine version 5.x
+-----------+------------+
| name      | occupation |
+-----------+------------+
| Samantha  | Doctor     |
| Julia     | Actor      |
| Maria     | Actor      |
| Meera     | Singer     |
| Ashely    | Professor  |
| Ketty     | Professor  |
| Christeen | Professor  |
| Jane      | Actor      |
| Jenny     | Doctor     |
| Priya     | Singer     |
+-----------+------------+

I would like pivot the Occupation column in table so that each Name is sorted alphabetically and displayed underneath
its corresponding Occupation. The output column headers should be Doctor, Professor, Singer, and Actor, respectively.
I try this
SELECT CASE occupation WHEN 'Doctor' THEN name END AS Doctor,
       CASE occupation WHEN 'Professor' THEN name END AS Professor,
       CASE occupation WHEN 'Singer' THEN name END AS Singer,
       CASE occupation WHEN 'Actor' THEN name END AS Actor
FROM occupations;

output
+----------+-----------+--------+-------+
| Doctor   | Professor | Singer | Actor |
+----------+-----------+--------+-------+
| NULL     | NULL      | NULL   | Jane  |
| NULL     | NULL      | NULL   | Julia |
| NULL     | NULL      | NULL   | Maria |
| NULL     | NULL      | Meera  | NULL  |
| NULL     | NULL      | Priya  | NULL  |
| NULL     | Ashely    | NULL   | NULL  |
| NULL     | Christeen | NULL   | NULL  |
| NULL     | Ketty     | NULL   | NULL  |
| Jenny    | NULL      | NULL   | NULL  |
| Samantha | NULL      | NULL   | NULL  |
+----------+-----------+--------+-------+

but I would like this output
Doctor   Professor  Singer Actor
Jenny    Ashley     Meera  Jane
Samantha Christeen  Priya  Julia
NULL     Ketty      NULL   Maria

I am jammed with this, any help would be appreciate.

A: This is a little tricky.  You need aggregation, but have nothing to aggregate on.  For that, you need a row number:
SELECT MAX(CASE occupation WHEN 'Doctor' THEN name END) AS Doctor,
       MAX(CASE occupation WHEN 'Professor' THEN name END) AS Professor,
       MAX(CASE occupation WHEN 'Singer' THEN name END) AS Singer,
       MAX(CASE occupation WHEN 'Actor' THEN name END) AS Actor
FROM (SELECT o.*,
             ROW_NUMBER() OVER (PARTITION BY occupation ORDER BY occupation) as seqnum
      FROM occupations o
     ) o
GROUP BY seqnum;

Here is a db<>fiddle, illustrating that the above works.
EDIT:
In older versions, you can use a correlated subquery:
SELECT MAX(CASE occupation WHEN 'Doctor' THEN name END) AS Doctor,
       MAX(CASE occupation WHEN 'Professor' THEN name END) AS Professor,
       MAX(CASE occupation WHEN 'Singer' THEN name END) AS Singer,
       MAX(CASE occupation WHEN 'Actor' THEN name END) AS Actor
FROM (SELECT o.*,
             (SELECT COUNT(*)
              FROM occupations o2
              WHERE o2.occupation = o.occupation AND
                    o2.name <= o.name
             ) as seqnum
      FROM occupations o
     ) o
GROUP BY seqnum;


text:
Q: Trigger Before Insert Salesforce APEX to Update Field Not sure if my syntax is correct, what I'm trying to achive is updating a text field (X80_20__c), where the data is coming from a formula text field (X80_20_Yes_or_No__c). The output from the formula field produces a Yes or No value.
This is the Apex trigger I attempted but its not populating the X80_20__c field. Any help would be appreciated or would a Apex Class be better to do in this situation? Also, I'm avoiding in using a workflow trigger or process builder for this.
trigger a8020 on Account (before insert,before update) {
    List obj = [SELECT Id,Name,X80_20_Yes_or_No__c,X80_20__c FROM Account WHERE
 (X80_20_Yes_or_No__c = 'Yes' OR X80_20_Yes_or_no__c = 'No') AND
 Outlet_Type__c = 'Home Depot' AND Has_1_2_3x5_DULO__c = 'Yes' ];

    for (Account a: obj) {
        string s = a.X80_20_Yes_or_No__c;
        a.X80_20__c = s;
    }

    update obj;
}

A: Formula fields are not populated in before insert context, so your query is going to return a set of existing Accounts, not the ones being inserted. (This goes double because your query doesn't include any Id IN criterion in the WHERE clause, so it's running across the whole database).
Additionally, in a before insert context, you do not need to perform an update DML to commit changes you make to objects in the trigger.
In this case, since you're iterating over a set that will either be empty or a group of unrelated existing Accounts rather than Trigger.new, the overall outcome is that nothing happens to your newly inserted accounts, and you update some existing records in your database.
If you need to pre-populate this field, you may want to simply implement the formula logic in your trigger. You can iterate over Trigger.new, access the Account fields directly (no SOQL required), and update your field without needing DML.
Lastly, since List (rather than List<Account>) is not a valid type in Apex, I don't believe this will compile as written.


text:
Q: Removing empty plots with `facet_grid` I would like to remove empty plots while using facet_grid.
The names of the labels in columns is arbitrary (e.g. foo, baz), but I only have two columns.
I have an empty plot, like this:

I would like to remove empty plots, like this (thank you GIMP):

Contrary to the example, the names are not systematic, and the number of plots in the top and in the bottom does not necessarily match.
The plots can be ordered as:
+-----+-----+
| foo | bar |
+-----+-----+
| baz |     |
+-----+-----+

(with the last plot being empty.)
I guess I could use grid.arrange, but I would then have to split my plot into a list of plots.
Any other solution?

A: Here is an example where I try to reproduce your problem:
dts <- read.table(text="
x y  g1 g2
1 1  1 B
2 2  1 B
1 1  1 D
2 2  1 D
1 1  1 F
2 2  1 F
1 1  2 A
2 2  2 A
1 1  2 C
2 2  2 C
1 1  2 E
2 2  2 E
", header=T
)

library(ggplot2)
ggplot(data=dts, aes(x, y)) +
  geom_line() +
  facet_grid(g1~g2) +
  theme_bw()

My simple suggestion is to use facet_wrap instead of facet_grid:
library(ggplot2)
ggplot(data=dts, aes(x, y)) +
  geom_line() +
  facet_wrap(g1~g2) +
  theme_bw()


text:
Q: What is the best way to share only the getter methods to client? I am writing an API with a class like this:
public class NKMPMission {
    private String name;
    private int age;
    public NKMPMission(String name, int age)
    {
         this.name  = name;
         this.age   = age;
    }
    public String getName()
    {
       return name;
    }

    public int getAge()
    {
       return age;
     }
   }

My Questions:

*

*How can I make sure the user of this NKMPMission class accesses only the getters?

*How can I introduce setters for this function so that I as a developer can set, but the user cannot set?

A:
1) How can i make sure user of this NKMPMIssion class access only getters.

You can't.

2) How can i introduce setters for this function so that as a developer i should be able to set, but the user should not be able to set.

It sounds like you're writing an API. If you return a NKMPMIssion instance from a public method of that API, the setters can be called. Even if you mark them private or protected, they can still be called via reflection. That said, usually making them non-public is sufficient. It does, at the very least, say "If you call these, you're in unsupported territory."
If you want to make it harder, you can return an instance that wraps a facade around the NKMPMIssion instance. But that just makes it harder, not impossible, since the facade instance has to have a reference to the NKMPMIssion instance, which (even if it's private) can be accessed via reflection.

A: The easiest thing is to make the API use the interface only and make the class an implementation detail.
public interface INKMPMission {
    String getName();
    int getAge();
 }

public class SomeService{
    private class MyNKMPMission implements INKMPMission {
        //put getters and setters here
    }
    public List<INKMPMission> getMissions(){
        //put some MyNKMPMissions in a list
    }
}

Since MyNKMPMission is private the consumers will never be able do downcast and access the setters.

A: You can (in some kinda way), but you should not do it that way:

*

*In each setter construct a new Exception

*Inspect the generated Stacktrace

*If the caller class is not within your package (or hardcode some direct classnames / methodnames) throw an IllegalAccessError

This way is neither pretty, nor fast as you have to check every single access to a setter.
Another way would be using the @CallerSensitive Annotation, though it's propritary API and is therefore not available on all plattforms / jre implementations: https://stackoverflow.com/a/22627383/1164913
The clean, and in most cases sufficent way would be using an Interface which only provides getters to the client, and returning that to the client.

A: The usual way to do this is to not expose the class at all, just expose interfaces to that class. One interface for the general public and one for developers.
You then need a factory to create them.
/**
 * Expose this interface to the public.
 */
public interface INKMPMission {

    public String getName();

    public int getAge();

}

/**
 * Only expose this interface to developers.
 */
interface IDeveloperNKMPMission {

    public void setName(String name);

    public void setAge(int age);

}

public static class NKMPMissionFactory {

    /**
     * Expose only the INKMPMission construction.
     */
    public INKMPMission make(String name, int age) {
        return new NKMPMission(name, age);
    }

    /**
     * Protected version for developers.
     */
    IDeveloperNKMPMission forDeveloper(INKMPMission it) {
        return IDeveloperNKMPMission.class.cast(it);
    }

    /**
     * Private so no-one outside the factory knows about the inner workings.
     */
    private static class NKMPMission implements INKMPMission, IDeveloperNKMPMission {

        private String name;
        private int age;

        private NKMPMission(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public int getAge() {
            return age;
        }

        @Override
        public void setName(String name) {
            this.name = name;
        }

        @Override
        public void setAge(int age) {
            this.age = age;
        }
    }
}

For the truly paranoid you can even use a proxy. This will make it difficult (but not impossible) to use the setters through reflection.
    /**
     * Expose only the INKMPMission construction.
     */
    public INKMPMission make(String name, int age) {
        return new NKMPMissionProxy(new NKMPMission(name, age));
    }

    /**
     * Protected version for developers.
     */
    protected IDeveloperNKMPMission forDeveloper(INKMPMission it) {
        if (it instanceof NKMPMissionProxy) {
            it = ((NKMPMissionProxy) it).theMission;
        }
        return IDeveloperNKMPMission.class.cast(it);
    }

    /**
     * A proxy for the truly paranoid - makes using reflection more difficult (but not impossible)
     */
    private static class NKMPMissionProxy implements INKMPMission {
        private final NKMPMission theMission;

        private NKMPMissionProxy(NKMPMission theMission) {
            this.theMission = theMission;
        }

        @Override
        public String getName() {
            return theMission.getName();
        }

        @Override
        public int getAge() {
            return theMission.getAge();
        }

    }

A: It seems you trying to write an API. Assuming user means, developers who use your API.
In such cases, make the setter as protected and build some meaningful package structure, such that only child's and package members can see that.
If you want to protect that even from child's, there is no way other than making it private.

A: Answering the questions:
Q1. You can't as T.J. Crowder has said in his answer.
Q2. I would recommend you to try the following things in the following order from easiest to hardest, and take the option you consider the most suitable in terms of effort-return:

*

*Have a look to: Java access modifiers.

*Create an interface and expose that interface with the public methods to the "final" users of the "NKMPMission" class, as mentioned in Esben Skov Pedersen answer

*Finally you can do the proxy approach mentioned in OldCurmudgeon answer
What I would do:
If your set of classes is going to be used internally then I would take option 1 combined with a good javadoc and project standards, it should be enough.
In case you are creating a public API I would take the option 2.
IMHO the option 3 adds too innecessary complexity in this case, and very few benefit, since every class method or attribute can be accessed anyway throw reflection (as many people has mentioned). I think everybody is aware about the fact that access throw reflection to API's hidden methods is hacky, dangerous and not convenient for the manteinance of the projects, due to API providers are in their right to change hidden methods implementations without further notification to the final users.


text:
Q: Performance issues of containers in kubernetes pods We are trying to setup scalable jenkins on a kubernetes cluster to build and deploy our app.
Able to successfully scale jenkins slaves using kubernetes on a Dev Machine(Spec: CentoOS 7, 12 cpu/core, 16G).
However Application build time is being effected drastically.
Time taken to build an application on a debian docker image is 1.5hrs on a CentOS host. Whereas building the same application on the same image inside a slave pod takes ~5hrs.
Tried setting the CPU/Mem (limits, requests) on the slave pod and also tried setting multiple default values in limitrange. but it has no effect on build time.
https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/
What are we missing?
minikube node capacity
Capacity:
 cpu:     10
 memory:  9206328Ki
 pods:    110
Allocatable:
 cpu:     10
 memory:  9103928Ki
 pods:    110

Jenkins pipeline code
def label = "slave-${UUID.randomUUID().toString()}"

podTemplate(label: label, containers: [
  containerTemplate(name: 'todebian',
                    image: 'registry.gitlab.com/todebian:v1',
                    command: 'cat',
                    ttyEnabled: true,
                    resourceRequestCpu: '2',
                    resourceLimitCpu: '3',
                    resourceRequestMemory: '1024Mi',
                    resourceLimitMemory: '2048Mi')
  ],
volumes: [
  hostPathVolume(mountPath: '/workspace', hostPath: '/hosthome/workspace_linux1')
]) {
  node(label) {
      container('todebian'){
        sh """
           cd /workspace
           ./make
          """
      }
  }
  }

Please help me in troubleshooting.

A: Your problem may be exactly in using Minikube that uses full-blown virtualization.
My suggestion for you would be to setup single master cluster to get native performance and get rid of minikube.
As per experience - using this approach can dramatically increase performance.


text:
Q: Machine learning vector association mutually exclusive I have two sets of vectors representing points in three dimensional space. The first set is strictly smaller than second one. So I pick up all the vectors in the first set and I want to associate each one of them to just one vector from the second set. The association is binjective. So each point from the first set is associated to just one point in the second set, and the points in second set receive just one association each.
My question here is for which kind of algorithm should I use in order to succeed in such a task. I thought of several different approaches but couldn't find the right one.
At first I thought of using cluster assignment . But then I realised that using such an approach doesn't prevent the associations from being multiple ones. clusters might receive eventually more than one point from the first set which is specifically what I don't want to do.
The idea is that I need such an association so that the very shape depicted from the Vectors from the first set resembles the most the overall picture depicted from the Vectors in the second set. It's like as if the vectors from the first set has been subjected to some sort of 3D transformation into the Vectors in the second set but that for some reasons that transformation is recognisable.


text:
Q: I couldnt get datas from each html table which returns with PHP I am trying to build small projects to improve my skills. And im stuck at a poing. if someone can help me i will be glad. (I know there is SQL injection , its just practice)
Here is My Js function that is trying to get value from PHP side.
function selectUser(element){

  var customerid = $("td[data-form-id]", element).data("form-id");
  var customername = $("td[data-customer-name]", element).data("customer-name");
  var customertel = $("td[data-customer-tel]", element).data("customer-tel");
  var devicemodel = $("td[data-device-model]", element).data("device-model");
  var acceptdate = $("td[data-accept-date]", element).data("accept-date");

    console.log(customerid);
    console.log(customername);
    console.log(customertel);
    console.log(devicemodel);
    console.log(acceptdate);
  }

Here is my PHP Code and this is working fine like.
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$formId = $row['form_id'];
$customerName = $row['customer_name'];
$customerTel = $row['customer_tel'];
$deviceModel = $row['device_modal'];
$acceptDate = $row['accept_date'];

/*Here i give each row as id thats is shown customer's id. And when i click a row i can see in the console.*/

echo "
";
        echo "" . $formId . "	";
        echo "" . $customerName . "	";
        echo "" . $customerTel . "	";
        echo "" . $deviceModel . "	";
        echo "" . $acceptDate . "	";
        echo "Detail	";
echo "
";
}

But What i am trying to do is to read values when click on "Detail" part click not the row.
And i taking my function to  Like this and it returns in console "undefined values":
Detail

And here is the how it looks like all codes:
echo "
";
        echo "" . $formId . "	";
        echo "" . $customerName . "	";
        echo "" . $customerTel . "	";
        echo "" . $deviceModel . "	";
        echo "" . $acceptDate . "	";
        echo "Detail	";
echo "
";

A: Try this, this is using Jquery. also include the cdn jquery link.
echo "
";
    echo "" . $formId . "	";
    echo "" . $customerName . "	";
    echo "" . $customerTel . "	";
    echo "" . $deviceModel . "	";
    echo "" . $acceptDate . "	";
    echo "Detail	";
    echo "
";

$('.detail_btn').onClick(function(){
    var form_id = $(this).closest('tr').find('.form_id_class').val();
    console.log(form_id);
});


text:
Q: Button action is not fired for UIButton Inside UIView which is inside UIScrollview in IOS I want to load set of objects coming from array in vertical scrollview. I have UIScrollview at xib. Programmatically I added photo image, item name, item tags, comment button and likes label to UIView and added UIView to UIScrollview.
I added likes button to UIScrollview but the button action is not firing. Below is my code.
I think some Frames of subviews are over riding that makes button action (likes_ButtonPressed) not fired.
-(void)createScrollview
{

    NSArray *viewsToRemove = [scrollview subviews];
    for (UIView *v in viewsToRemove) [v removeFromSuperview];

    int x=7;
    int y=0;

    CGRect screenbounds=[[UIScreen mainScreen] bounds];

     for(int i=0;i<[array count];i++)
        {
            ProfileObjCls *profileObjRef = [self.array objectAtIndex:i];

            //NSLog(@"Button Tag is %@",profileObjRef.image_UserLoaded_objInArray);

            UIView *mainView=[[UIView alloc]initWithFrame:CGRectMake(x,y,310,400)];

            self.photoTagImgView=[[UIImageView alloc]initWithFrame:CGRectMake(x,y+20,294,320)];
            self.likesLabel.font=[UIFont fontWithName:@"BodoniStd-BoldItalic" size:13];
            self.itemNameLbl=[[UILabel alloc]initWithFrame:CGRectMake(x,y+340,100,30)];
            commentsButton=[[UIButton alloc]initWithFrame:CGRectMake(x+155+32, y+340, 40, 40)];
            [commentsButton setImage:[UIImage imageNamed:@"comment_icon.png"] forState:UIControlStateNormal];

            UIButton *photoLikeButton=[[UIButton alloc]initWithFrame:CGRectMake(x+100, y+340, 40, 40)];
            photoLikeButton.tag=i;
            [photoLikeButton setImage:[UIImage imageNamed:@"like_img_new.png"] forState:UIControlStateNormal];
            [photoLikeButton addTarget:self action:@selector(likes_ButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

            self.likesLabel=[[UILabel alloc]initWithFrame:CGRectMake(x+223+32,y+346,310,30)];

            if (profileObjRef.photoLikes==0)
            {
                self.likesLabel.text=@"0 likes";
            }
            else
            {
            self.likesLabel.text=[NSString stringWithFormat:@"%@ likes",profileObjRef.photoLikes];
            }

            [self.photoTagImgView setImageWithURL:[NSURL URLWithString:profileObjRef.image_UserLoaded_objInArray]
                              placeholderImage:[UIImage imageNamed:@"satisfashionplaceholder@568.png"]
                                     completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
             {
                 if (!error && image)
                 {

                 }
             }];

                self.imagetotweet=profileObjRef.image_UserLoaded_objInArray;

                //int y=335;

                //first label - PHOTO NAME
                self.itemNameLbl.text=profileObjRef.photoname;

                self.itemNameLbl.font = [UIFont fontWithName:@"BodoniStd-Poster" size:14.0];//BodoniStd-Bold
                self.itemNameLbl.textColor  = [UIColor blackColor];

                //second Label - PHOTO DESCRIPTION
                UIFont *cellFont=[UIFont fontWithName:@"BodoniStd-BoldItalic" size:13.0];

            [mainView addSubview:commentsButton];
            [mainView addSubview:likesLabel];
            [self.scrollview addSubview:photoLikeButton];
            [self.scrollview bringSubviewToFront:photoLikeButton];
            [mainView addSubview:self.photoTagImgView];
            [mainView addSubview:self.itemNameLbl];

            [mainView addSubview:self.detailsBgImgView];
            [self.scrollview addSubview:likesButton];
            [self.scrollview bringSubviewToFront:likesButton];
            mainView.userInteractionEnabled=YES;
            self.scrollview.backgroundColor=[UIColor clearColor];
            self.scrollview.userInteractionEnabled = YES;
            /*
            self.scrollview.exclusiveTouch = YES;
            self.scrollview.canCancelContentTouches = YES;
            self.scrollview.delaysContentTouches = YES;
            self.view.userInteractionEnabled=YES;*/
            //self.scrollview.backgroundColor=[UIColor colorWithRed:212.0f/255.0f green:213.0f/255.0f blue:214.0f/255.0f alpha:1.0f];
            [self.scrollview addSubview:mainView];
            [self.view addSubview:self.scrollview];
             y=y+200;
            //x=x+320;
        }
        self.scrollview.contentSize=CGSizeMake(320, 400*array.count);
        //self.scrollview.contentSize=(CGSizeMake(x, 320));
        self.scrollview.pagingEnabled=YES;
        //[self.scrollview setContentOffset:CGPointMake(320*tagValue, 0)];
        [self.scrollview setContentOffset:CGPointMake(0, 400*tagValue)];
        [self.view bringSubviewToFront:spinner];

       //[self.scrollview setContentOffset:CGPointMake(320*(tagValue-1), 0)];
    }

- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
    return ![view isKindOfClass:[UIButton class]];
}

Please suggest any ideas where I went wrong..
Thanks in Advance..


text:
Q: What cause sudden spike in the output voltage of transformer? What issues can cause the output voltage of a transformer to suddenly increase from 230 volts to 400 volts (in the case of any transformer and in the case of the delta to Y configuration of the transformer)? What would be the voltage between a phase and ground if a coil of the Y side (secondary) gets short because of heating or any other reason?

A:
The cause could be a broken neutral wire shorting with a line.


text:
Q: More elements in LinkedList than COUNT property can return in C# The count property of LinkedList<T>has return type of int. What if my LinkedList<T> has more elements than int can store and want to know the elements in it. Wont it cause an overflow ? I'm asking this because I am given to create a sequence whose upper bound is 10e15elements it means more elements than an int can store and I want to check that a certain value is less than total elements in my LinkedList<T> and that certain value can be greater than int but still less than the given upper bound.

A: There is a longCount extension method for LinkedList in System.Linq namespace which return Int64.
Note:
As Hans Passant says in the comment that it traverses the whole list having O(n) complexity and its use must be avoided with LinkedLists


text:
Q: How can I extend or overwrite component decorators in Angular Material 2? I am nesting a <mat-nav-list> inside of a <mat-expansion-panel> component. At runtime, Angular Material 2 is creating html, in my specific case:

...

Which also is getting styles assigned to it. I am unable to overwrite these styles using the component style sheet like I normally would.
Looking through the source, I am seeing this:
/node_modules/@angular/material/esm2015/expansion.js

MatExpansionPanel.decorators = [
{ type: Component, args: [{styles: [".mat-expansion-panel{transition:box-shadow 280ms cubic-bezier(.4,0,.2,1);box-sizing:content-box;display:block;margin:0;transition:margin 225ms cubic-bezier(.4,0,.2,1)}.mat-expansion-panel:not([class*=mat-elevation-z]){box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-expansion-panel-content{overflow:hidden}.mat-expansion-panel-body{margin:0 24px 16px;overflow:auto}
...

I'm sure this isn't the exact code that is creating the component, but it does contain the css I would like to override:
...
.mat-expansion-panel-body{margin:0 24px 16px;overflow:auto}
...

How can I modify the decorator to remove the margin?
Here is what my .ts file looks like so far:
@Component({
    selector: 'my-selector',
    templateUrl: './my-selector.component.html',
    styleUrls: ['./my-selector.component.scss']
})
export class MyComponent implements OnInit, OnDestroy {...}

Thank you for any suggestions!

A: I wish I could take credit for the solution that seems to work, but here is a thread with a similar problem.
I was able to remove the margin like this:
my-template.component.html
<mat-expansion-panel *ngFor="let foo of bar" class="my-sidenav">
    <mat-expansion-panel-header>
        ...
    </mat-expansion-panel-header>
    <mat-nav-list>
        <mat-list-item>...</mat-list-item>
    </mat-nav-list>
</mat-expansion-panel>

my-component.component.scss
/deep/ .my-sidenav {
    .mat-expansion-panel-body {
        margin: 0;
    }
}