text:
Q: How I can collect live data about football matches? I wonder about the ways of collecting live data about football matches like: scores, players, events (yellow, red cards, injuries).
I know that there is possibility of taking this data from pages like FlashScores using PHP, however I want to know how the FlashScores and similar services gets data to their databases. What way they collect data?
It is impossible to have person on each match :P
I wonder if they get scores from web pages of each league. Is it possible? If it doesn't generate too big network traffic?
If anyone has some ideas, please help me with this problem ;)

A: Companies like Opta indeed had (at least) 2 persons per match in the major football leagues to label events in football matches. One watched the game and announced the events to the other, who wrote them down (in a program that is optimized for that).
Recently they changed their procedure to 3 persons: 'Three expert analysts will cover each match, one collecting all of the home team actions, one the away team and a third analyst checking the data for consistency and adding additional layers of data.'

Doing this on your own seems like a pretty extensive idea. Afaik there is a lot of research going on, trying to automate this labeling process from videos alone.

As a side note: 1899 Hoffenheim, as an example, use sensors in shoes and balls, as well as multiple cameras (and even drones) to collect live training data automatically. But up to now, sensors are forbidden in all major football leagues I know.


text:
Q: Why were the Harkonnen risking using a lasgun to shoot down Idaho's ornithopter? Were the Harkonnen using lasguns in the new Dune movie to try and shoot down Duncan?
It looked like they were shooting lasguns at Duncan as he escaped at one point in the movie. Wouldn't this create an unhappy situation (the destruction of the two ships), or was Duncan's shield somehow deactivated?
I'm assuming this was just an oversight in regards to them not addressing the conflict of the weapons in the movie, and the value of having him flying all around with stuff blowing up, but at the same time maybe I am misremembering something about these mechanics.

A: Idaho's 'thopter is hit by a missile, evidently overloading (or disabling) the shield.

You see the shield flickering and then apparently failing a few seconds later.

It would appear that our lasgunner saw this shield failure and decided that it was worth the risk of shooting him down with a lasgun.

redpajama_set_name: RedPajamaStackExchange


text:
Q: dictionary of lists to tuples I am quite sure there must be a more pythonic way to do this rather than the one I used.
So a dictionary of dictionaries of lists ---> dictionary of lists of tuples
Say:
ff = {'one': {'aaa': [1, 2, 3], 'bbb': [3, 4, 5]}, 'two': {'ccc': [3, 2, 1]}}

to
test = {'one': [('aaa', 1, 2, 3), ('bbb', 3, 4, 5)], 'two': [('ccc', 3, 2, 1)]}

And this is the solution I found:
test = { k:[tuple(itertools.chain(itertools.repeat(ksub,1),(elements for elements in vsub))) for ksub,vsub in v.items()] for k,v in ff.items() }

Is there a clearer way to to do this?

A: I'd just use a list comprehension and concatenation for the nested dict items:
{k: [(nk,) + tuple(nv) for nk, nv in v.iteritems()] for k, v in ff.iteritems()}

Demo:
>>> ff = {'one': {'aaa': [1,2,3], 'bbb':[3,4,5] }, 'two': {'ccc' : [3,2,1] }}
>>> {k: [(nk,) + tuple(nv) for nk, nv in v.iteritems()] for k, v in ff.iteritems()}
{'two': [('ccc', 3, 2, 1)], 'one': [('aaa', 1, 2, 3), ('bbb', 3, 4, 5)]}


text:
Q: Heroku app shows up for a while and then gives `Application error` I have created a MERN app and deployed it on Heroku But it works for a while and then gives Application error. However, the code is fine and on the localhost both the frontend and the backend with MongoDB work perfectly fine and are up and running. I have tried everything I found on the internet. Here's the list of things I've done:

*

*Added the config vars on Heroku (in case someone thinks I forgot that)

*Checked the Procfile whether there's any space error

*Checked the package.json files and scripts

*Tried to update the node_modules and restart Heroku

*Made commits and tried to push on Heroku multiple times hoping it was a temporary error

But nothing seems to be working and it's still giving H10 errors. What can I try next?


text: Q: Could this imaginary cooling solution work? Imagine a perfectly insulated ideal closed cylinder. Inside, at the two ends there are two bodies, one with the temperature of T the other with temperature -T. Between the almost touching bodies with temperature difference we place a thermoelectric generator, that uses heat flux for electricity generation. If heat energy moves towards the colder object through the thermoelectric panel and assume it converts some percent of it to electrical energy, will the system cool down by that much? Will temperature go down in the chamber with equal amount to the electricity produced? (Assume we use up the electricity generated by the TEG and we actually do some work with lets say 99.999% efficiency.)


text:
Q: AssetManager libgdx i'm trying to make a loading page for my game.
my code its like this:
manager = new AssetManager();
game = new Game(level);
game.startLoadingTextures(manager);

public void startLoadingTextures(AssetManager manager){
    manager.load("data/background.png" ,Texture.class);
}

in a update function i have this:
if (manager.update()){
    game.setTexture(manager);
}

what is setTexture function ? i get all textures from manager.
public void setTexture(AssetManager manager) {
    System.out.println("entered here");
    background = manager.get("data/background.png" ,Texture.class);
}

and i get this error:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.smeurares.game.Loading.update(Loading.java:31)

line 31 is game.setTexture(manager), and i get this eror before entering in the function because System.out.println("entered here"); is not appearing in console.
what i've done wrong ?

A: oh.. ty noone, that was it, game wasn't declared.. because it should be this.game = new  Game(level), didint thinked about it...


text:
Q: xubuntu 14.04 running slow! I did a fresh install of xubuntu 14.04, 64bit, on my Kingston (ssdNOW 300), and OS is running slowly, occasional "temporary" freezes.
Here is my hardware:

*

*Intel(R) Core(TM) i5 CPU 750  @ 2.67GHz, 1197.000 MHz

*FC Gigabyte GA-P55-UD3 motherboard

*G94 nVidia Geforce 9600 GT

*4GB ram,

I am also using two monitors.
I also have dual boot option, with win8.1 being on physically separate disc.
When I login the whole screen is a bit noisy (random pixels, random colors), for a minute or so. Then the desktop loads and looks fine.
I expected xubuntu to run extremely fast, but it freezes sometimes even during simplest tasks like saving a gedit file, writing some text in the terminal. Applications very often "stop working properly" and want to close. After I click cancel, they continue to work ok... for some time and than freeze again.
I suspected nVidia graphic card, installed drivers from "additional drivers", rebooted and well, the whole thing slowed down even more.
Did anybody have similar issues?
I am getting quite desperate here.

A: Ok, so the problem was apparently my second hard disc, on which i installed my /home directory. The disc didn't report any errors with smart scan.
Something was wrong with it's response time.
How could i have detected this?
Trial and error saved me this time.
I unmounted my second hard drive just in case, and moved my /home directory to my solid state disc.
It works extremely fast now.
Thanks everybody, for your suggestions and time.

A: Restart your graphic card install
On screen login: Alt+Ctrl+F1
your login and your password

sudo apt-get remove --purge fglrx*
sudo dpkg-reconfigure xserver-xorg

Alt+Ctrl+F7


text:
Q: \chardef and underscore Could you explain to me why
a\_b {\ttfamily a\_b} \\
\chardef\_=`\_
a\_b {\ttfamily a\_b}

produces

?
I would like to have the short underscore in the normal text and the long one in fixed-width font. I cannot change {\ttfamily a\_b}. The other a\_b I can change.
Thanks for your help!

EDIT: I realized that a\textunderscore b solves my immediate problem in text. I would still like to know where the mysterious dot is comming from.
In math mode,
\chardef\_=`\_
$a\_b$

LaTeX stops compiling altogether on my installation (without error, it just halts).

A: Your \chardef defines \_ to be the character in position "5F (ASCII for the underscore character), and that position just happens to contain the mysterious dot. At least it does in cmr10, and apparently it does in the font you're using as well (run (pdf)tex testfont to make font tables for any font you're curious about). The standard definition of \_ in plain TeX just typesets a rule of some suitable width, as there isn't any underscore glyph in the cmr font. I assume something similar is true in LaTeX, though I haven't bother to dig my way past the \textunderscore magic.
I am not too sure about what you can do, though. The whole LaTeX font selection business is a weak point of my TeX foo.

A: In a fix-width font every symbol should have the same width. So a long underscore is a bit unusual. In any case: in OT1-encoding (which you are obviously using) \_ calls internally \textunderscore, which in turn is define as a rule of width 0.3em and some space. You can redefine \_ to get a longer rule and use \textunderscore at other places:
\documentclass{book}
\DeclareTextCommand{\_}{OT1}{%
  \leavevmode \kern.06em\vbox{\hrule width.6em}}

\begin{document}
a\textunderscore b  {\ttfamily a\_b}
\end{document}


text:
Q: Set an image as a background on a circle I have a some local images such as calendar.svg, I have about 10 of these SVG images, I want to append them to the background of some circles.
There's a way to do it using patterns which uses a lot of code! I was wondering if there was a quick and easy way to just use the local images!
what my code looks like:
The first two blocks of circle code are me appending patterns, using that method for the images, but the third and final block is me trying to actually just access the local image and use that, but this isnt working!
  circle
    .filter(node => node.depth !== 0 && node.type === EngagementType.Event)
    .append('circle')
    .classed('Engagement-GraphNode', true)
    .classed('Engagement-GraphNodeBackground', true)
    .classed('Engagement-GraphLeaf', node => node && (node.depth === 4 && !node.isExtraNode))
    .style('fill', d => `url(#insightImageEvents-${d.id})`)
    .style('opacity', node => (node.visible) ? 1 : 0)
    .style('visibility', node => (node.visible) ? 'visible' : 'hidden')
    .on('click', node => onClick(node));
  circle
    .filter(node => !node.parent)
    .append('circle')
    .classed('Engagement-GraphNode', true)
    .classed('Engagement-GraphNodeBackground', true)
    .classed('Engagement-GraphLeaf', node => node && (node.depth === 4 && !node.isExtraNode))
    .style('fill', node => 'white')
    .style('opacity', node => (node.visible) ? 1 : 0)
    .style('visibility', node => (node.visible) ? 'visible' : 'hidden')
    .on('click', node => onClick(node));
  circle
    .filter(node => node.name === 'Annual Meetings')
    .append("svg:image")
    .attr('width', 20)
    .attr('height', 24)
    .attr("xlink:href", "/calendar.svg") <---- trying
    // .classed('Engagement-GraphNode', true)
    // .classed('Engagement-GraphNodeBackground', true)
    // .classed('Engagement-GraphLeaf', node => node && (node.depth === 4 && !node.isExtraNode))
    // .style('fill', node => 'red')
    .style('opacity', node => (node.visible) ? 1 : 0)
    .style('visibility', node => (node.visible) ? 'visible' : 'hidden')
    .on('click', node => onClick(node));

any help would be greatly appreciated!

A: You can use image masking to achieve this as such:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
    <defs>
        <mask id="image-mask">
            <circle id="outer" cx="50" cy="50" r="50" fill="white"/>
            <circle id="inner" cx="50" cy="50" r="25"/>
        </mask>
    </defs>
    <image width="100%" height="100%" preserveAspectRatio="xMidYMid slice" xlink:href="https://images.unsplash.com/photo-1472195870936-d88b0d4c1b41?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=f1abbd4d59a9b448813cb48769806ada" mask="url(#image-mask)"></image>
</svg>


text:
Q: android: providing resources I have read the documentation and some questions but I can't find any answer. This is my first full-blown app and I want it to at least render properly on different screen sizes so I used dp for units and sp for textviews. I have tried it on different devices and different avd's. I have observed that that on most devices, screen size is directly proportional to density. (small screen has ldpi, normal screen has mdpi, large screen has hdpi, xlarge screen has xhdpi) With this, my default layout renders on devices that follows this trend. However, there are devices that doesn't follow this trend (e.g. Samsung Galaxy Tab which has, if I'm not mistaken, large-mdpi), so when I tried my layout, the splash screen (Yes, I know splash screens are annoying and not recommended) is pixelated, and the texts are small.
What I want to happen is that the splash screen would depend on the screen size and the text sizes would depend on the screensize & density. How do I achieve this? Thanks.

A: Check out this page: Android Devices
It shows the many devices and what their corresponding stats are.  Then you need to decide how to best target a device that is not displaying things correctly.
I think the best approach is with different values folders, where you can make different folders based on API level (like values-v11 for all devices using API 11 or less) or by screen size (like values-small thru values-xlarge).  Then you create different styles.xml, dimens.xml, and even colors.xml.
In the layouts, you give each widget a style that uses different dimens or you can just put the dimension values in the styles, or you can set the values from the dimens.xml file in the layout file.
You're only supposed to use dpi qualifiers on the drawable folders (like drawable-hdpi), since bitmaps don't scale with dpi as well as fonts and other drawables.
As for different layout folders, I think you should limit them to portrait versus landscape, where the position of the widgets varies.
The Galaxy Tab is a tablet with 1024 X 600 screen size.  This is where you want to have a different values folder (values-xlarge).  You may also want to define special styles for it using dimensions that work for a tablet.  You put the styles.xml, dimens.xml files for it in the values-xlarge folder.
So, yea a tablet is going to really stretch any bitmap you would use for a background.  In this case you could have a different drawable for it.


text:
Q: Latex won class and macros I'm writing my own simple template, what I have so far is a new, redefined make title command:
\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{myclass}[2016/06/22 My custom class]
\LoadClass{article}

\usepackage{cmap}
\usepackage[T1]{fontenc}
\usepackage{longtable}
\usepackage{multirow}
\usepackage{fancybox}
\usepackage{rotating}
\usepackage{hyperref}
\usepackage{framed}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{graphicx}
\usepackage{pdfpages}
\usepackage{enumitem}

\newcommand{\LOGO}{logo.png}
\newcommand{\FIRST}[1]{#1}
\newcommand{\SECOND}[1]{#1}
\newcommand{\THIRD}[1]{#1}

\renewcommand{\maketitle}{
    \begin{titlepage}
        \vspace{10pt}
        \hbox{
            \mbox{
                \hspace{-20pt}
                \fbox{ \includegraphics{\LOGO}}
                \hspace{4pt}
            }
            \vrule depth 0.9\textheight
            \mbox{\hspace{2em}}
            \vtop{
                \vspace{20pt}
                \begin{flushleft}
                    \Large \FIRST \par
                \end{flushleft}
                \vspace{80pt}
                \begin{flushleft}
                    \Huge \bfseries \SECOND \par
                \end{flushleft}
                \begin{flushleft}
                    \large \bfseries \THIRD  \par
                \end{flushleft}
                \vfil
            }
        }
    \end{titlepage}
    \setcounter{footnote}{0}
}

In the new maketitle I'm using macros \FIRST, \SECOND, \THIRD which I defined as :
\newcommand{\FIRST}[1]{#1}

However, I would like the user using this template to be able to upload during writing the tex while any value to \FIRST is such a way that when the user is calling my \maketitle, in place of \FIRST appears the value selected by the user. How can I do that, when I define \FIRST macro in the .cls file?

A: You could define your commands like given below:
\newcommand{\FIRST}[1]{\gdef\@FIRST{#1}}
\newcommand{\SECOND}[1]{\gdef\@SECOND{#1}}
\newcommand{\THIRD}[1]{\gdef\@THIRD{#1}}
\let\@FIRST\@empty
\let\@SECOND\@empty
\let\@THIRD\@empty

Then later inside \maketitle you could replace \FIRST, \SECOND and \THIRD to \@FIRST, \@SECOND and \@THIRD respectively.
Now user can give:
\FIRST{one}
\SECOND{two}
\THIRD{three}

Hope this helps.


text:
Q: How to avoid NullPointerException when re-back to FragmentActivity? My STACK_TRACE when I came back to FragmentActivity from another activity.
I searched lot for how to solve this, and I found a clue that I need to save state of fragment.
But in that clue article said, when I use FragmentPagerAdapter, I do not need to save state.
So, I confussed. Am I use FragmentPagerAdapter correctly?
Please Help me...
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test20140320/com.example.test20140320.MainActivity}: java.lang.NullPointerException
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
   at android.app.ActivityThread.access$700(ActivityThread.java:168)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:137)
   at android.app.ActivityThread.main(ActivityThread.java:5493)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:525)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
   at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
   at com.example.test20140320.MainActivity_Fragment_Tab_02.<init>(MainActivity_Fragment_Tab_02.java:98)
   at java.lang.Class.newInstanceImpl(Native Method)
   at java.lang.Class.newInstance(Class.java:1130)
   at android.support.v4.app.Fragment.instantiate(Fragment.java:402)
   at android.support.v4.app.FragmentState.instantiate(Fragment.java:97)
   at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1801)
   at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:213)
   at com.example.test20140320.MainActivity.onCreate(MainActivity.java:47)
   at android.app.Activity.performCreate(Activity.java:5372)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
   ... 11 more
java.lang.NullPointerException
   at com.example.test20140320.MainActivity_Fragment_Tab_02.<init>(MainActivity_Fragment_Tab_02.java:98)
   at java.lang.Class.newInstanceImpl(Native Method)
   at java.lang.Class.newInstance(Class.java:1130)
   at android.support.v4.app.Fragment.instantiate(Fragment.java:402)
   at android.support.v4.app.FragmentState.instantiate(Fragment.java:97)
   at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1801)
   at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:213)
   at com.example.test20140320.MainActivity.onCreate(MainActivity.java:47)
   at android.app.Activity.performCreate(Activity.java:5372)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
   at android.app.ActivityThread.access$700(ActivityThread.java:168)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:137)
   at android.app.ActivityThread.main(ActivityThread.java:5493)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:525)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
   at dalvik.system.NativeStart.main(Native Method)

at com.example.test20140320.MainActivity_Fragment_Tab_02.<init>(MainActivity_Fragment_Tab_02.java:98)

My code:
public MainActivity_Fragment_Tab_02()
    {
        super();
        mContext = getActivity().getApplicationContext(); //This is line 98
        tab2 = this;
    }

I think the cause is at savedInstanceState, but don't know how, and how, and how....
Below is what i use FragmentPagerAdapter.
I think this is the most doubtful part.
public class SectionsPagerAdapter extends FragmentPagerAdapter
    {

        public SectionsPagerAdapter(FragmentManager fm)
        {
            super(fm);
        }

        @Override
        public Fragment getItem(int position)
        {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.

            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);

            switch(position)
            {
            case 0:
                Fragment fragment_tab1 = new MainActivity_Fragment_Tab_02(getApplicationContext());
                fragment_tab1.setRetainInstance(true);

                return fragment_tab1;
            case 1:
                Fragment fragment_tab2 = new MainActivity_Fragment_Tab_01(getApplicationContext());
                fragment_tab2.setRetainInstance(true);
                return fragment_tab2;
            case 2:
                Fragment fragment_tab3 =  new MainActivity_Fragment_Tab_03(getApplicationContext());
                fragment_tab3.setRetainInstance(true);
                return fragment_tab3;

            }
            return fragment;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

Is this code leaky??
Am I use FragmentPagerAdapter correctly? OTL....
How can I fix it....?
Please Help me!
P.S. First create fragmentActivity is successful.

A: Move
mContext = getActivity().getApplicationContext();

to onAttached or onActivityCreated

A: The problem with your code is that your activity is crashing some where else and hence you are not able to get activity reference in your fragment class. Go through the stack trace, the entire log, somewhere prior to the log that you have posted here, will be some other exception that is causing the activity to stop.
In order to use activity reference in the fragment class create on mActivity variable in your fragment and before using it check for NP if(mActivity!=null). Initialize mActivity in onAttached method of fragment class
@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    mActivity = activity;
}


text:
Q: nodeJS - fix SyntaxError: Cannot use import statement outside a module I've used in past this npm repo, it's a simple wrapper around guerrilla mail API. I've added it in past to my projects by using the ´require()´ function without any problem. At the moment I want to use the same library inside a node CLI script that I'm creating but I always get this error:
/Users/b/Sites/Te/node_modules/guerrillamail-api/src/index.js:1
import axios from 'axios';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at compileFunction (<anonymous>)
    at Object.compileFunction (node:vm:353:18)
    at wrapSafe (node:internal/modules/cjs/loader:1039:15)
    at Module._compile (node:internal/modules/cjs/loader:1073:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
    at Module.load (node:internal/modules/cjs/loader:989:32)
    at Function.Module._load (node:internal/modules/cjs/loader:829:14)
    at Module.require (node:internal/modules/cjs/loader:1013:19)
    at require (node:internal/modules/cjs/helpers:93:18)
    at Object.<anonymous> (/Users/b/Sites/Te/followBot.js:9:23)
    at Module._compile (node:internal/modules/cjs/loader:1109:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
    at Module.load (node:internal/modules/cjs/loader:989:32)
    at Function.Module._load (node:internal/modules/cjs/loader:829:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47

I's very strange, is there any solution to fix it?

A: Try adding "type": "module" to your package.json file.


text:
Q: ZipArchive alternative for iOS? Looking for a ZipArchive alternative for iOS that allows me to see the progress of the unzipping of a large file. Looked at ZipKit and Objective-Zip, but neither seem to give me any form of progress of the unzipping process. Do I have to roll my own or is there something out there that I've missed?

A: And of course shortly after posting this I come across SSZipArchive which does exactly what I need.


text:
Q: OSX semop does not queue processes I have recently developed a test project in C++ to learn mutual exclusion.
I've created two wraper functions:
void Semaphore::semaphore_await(int sem_cluster_id, unsigned short which) //semaphore_p
{
    int zmien_sem;
    sembuf bufor_sem;
    bufor_sem.sem_num = which;
    bufor_sem.sem_op = -1;
    bufor_sem.sem_flg = SEM_UNDO;
    zmien_sem = semop(sem_cluster_id, &bufor_sem, 1);
    if (zmien_sem == -1) {
        printf("Nie moglem zamknac semafora.\n");
        exit(EXIT_FAILURE);
    } else {
//        printf("Semafor S%d zostal zamkniety.\n", which);
    }
}

void Semaphore::semaphore_unlock(int semid, unsigned short which) //semaphore_v
{
    int zmien_sem;
    sembuf bufor_sem;
    bufor_sem.sem_num = which;
    bufor_sem.sem_op = 1;
    bufor_sem.sem_flg = SEM_UNDO;
    zmien_sem = semop(semid, &bufor_sem, 1);
    if (zmien_sem == -1) {
        printf("Nie moglem otworzyc semafora.\n");
        exit(EXIT_FAILURE);
    } else {
//        printf("Semafor S%d zostal otwarty.\n", which);
    }
}

I spawned few processes to compete over the resource and the have following bodies:
void critical_section(int semid, unsigned short semaphor_number){
    Semaphore::semaphore_await(semid, semaphor_number);
    std::cout<<"I am process:"<<getpid()<<" and I am in critical section!"<<std::endl;
//    sleep(1);
    Semaphore::semaphore_unlock(semid, semaphor_number);
}

And the problem is that I can't reproduce mutual exclusion phenomena. Once a single prcoess gets into the section it doesn't let another process to the section, but most of the time same process executes critical section...
I am process:32339 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32341 and I am in critical section!
I am process:32341 and I am in critical section!

And what is even more worriyng under Linux platform such as Manjaro or Ubuntu it works perfectly fine.


text:
Q: Column ambigously defined when using Pivot with subquery I am trying to run this pivot query to show the dates as columns which are in this format: "MM/DD/YYYY" and the occurrences of some kind of ID's in each date:
The column which contains the dates is "DATE_POSTED" -- DATA TYPE date
The column which contains the ID's is "ID_INST" -- DATA TYPE varchar2
Query:
SELECT *
FROM (SELECT ID_INST, DATE_POSTED
      FROM total.table1) PIVOT XML (COUNT (DATE_POSTED)
                                           FOR (DATE_POSTED)
                                           IN  (SELECT distinct DATE_POSTED
                                                  FROM total.table1));

The error which i'm receiving is ORA-00918: column ambiguously defined, I did some searches but I keep getting this error. Not sure if my approach is totally correct. P.S im using XML keyword due to the fact that it prompted: missing keyword
Current table:
Expected result:

A: Try the following:
SELECT *
  FROM (SELECT ID_INST, TO_CHAR(DATE_POSTED, 'DD-Mon')  DATE_POSTED
          FROM TOTAL.TABLE1)
  PIVOT XML (COUNT(DATE_POSTED)
             FOR DATE_POSTED IN (ANY))

The poblem might be caused by the fact, that date also stores time information additional to the date.
So you get different values for DATE_POSTED, but the conversion to char leads to the same column name as the date format mask cuts the time information.


text:
Q: Button inside the Datagrid not getting Fired due to PreviewMouseLeftButtonDown I am working on a WPF application.
As per requirement I want  to show  list of item in data grid. Each row also having a "DELETE" button, using this button we can deleted the corresponding item.
I  also want Drag and Drop feature for the Grid. That is user can move the  rows  up/down.
I am using "PreviewMouseLeftButtonDown" and "Drop" event of the  datagrid to implement the Drag and Drop feature.
For DELETE button  , I have bind the Delete Command.
Command="{Binding ElementName=viewName,Path=DataContext.DeleteCommand}"

I also tried
 Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.DeleteCommand}"

Now the issue is , when I click  the  "DELETE" button, the delete command handler not getting fired. But if I remove the   "PreviewMouseLeftButtonDown" and "Drop" events of the data grid , the delete command handler working perfectly.
Also I noticed that ,Even if commented all code inside the "PreviewMouseLeftButtonDown"  after add the PreviewMouseLeftButtonDown event, it also block the execution of  Delete command handler.

                    <DataGridTemplateColumn Width="35"  >
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Width="30" Content="X"     Command="{Binding ElementName=viewCSW,Path=DataContext.DeleteCommand}"    HorizontalAlignment="Center" Margin="0,0,0,0" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>

                </DataGrid.Columns>
                <DataGrid.RowStyle>
                    <Style TargetType="DataGridRow">
                        <Setter Property="Height" Value="25"/>
                    </Style>
                </DataGrid.RowStyle>

Code of PreviewMousedown
  private void dgEmployee_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            prevRowIndex = GetDataGridItemCurrentRowIndex(e.GetPosition);

            if (prevRowIndex < 0)
                return;
            dgEmployee.SelectedIndex = prevRowIndex;

            var selectedEmployee = dgEmployee.Items[prevRowIndex];//as Employee;

            if (selectedEmployee == null)
                return;
            //Now Create a Drag Rectangle with Mouse Drag-Effect
            //Here you can select the Effect as per your choice
            DragDropEffects dragdropeffects = DragDropEffects.Move;

            if (DragDrop.DoDragDrop(dgEmployee, selectedEmployee, dragdropeffects)
                                != DragDropEffects.None)
            {
                //Now This Item will be dropped at new location and so the new Selected Item
                dgEmployee.SelectedItem = selectedEmployee;
            }

            //      sourceElement.CaptureMouse();
            //  return;

        }

I am struggling with this issue.
If any one have a solution, Please let me know.
Thanks,
Ranish

A: Move the DragDrop.DoDragDrop call to the datagrid's MouseMove event:
private void dgEmployee_MouseMove(object sender, MouseEventArgs e)
    {
        if(e.LeftButton == MouseButtonState.Pressed)
        {
            Employee selectedEmp = dgEmployee.Items[prevRowIndex] as Employee;
            if (selectedEmp == null)
                return;

            DragDropEffects dragdropeffects = DragDropEffects.Move;
            if (DragDrop.DoDragDrop(dgEmployee, selectedEmp, dragdropeffects)
                            != DragDropEffects.None)
            {
                //Now This Item will be dropped at new location and so the new Selected Item
                dgEmployee.SelectedItem = selectedEmp;
            }
        }
    }

The updated PreviewMouseLeftButtonDown handler:
void dgEmployee_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        prevRowIndex = GetDataGridItemCurrentRowIndex(e.GetPosition);

        if (prevRowIndex < 0)
            return;

        dgEmployee.SelectedIndex = prevRowIndex;
    }

Not only does it fix your problem but it provides a better user experience. The drag should be initiated when I move the mouse instead of when I press the row.
Next time please link the tutorial that you are using - it will make it much easier for others to reproduce the issue that you are encountering.


text:
Q: Access, Change all dates to Mondays is there a quick way to nest an if (IIF?) in an UPDATE string to change all dates to the appropriate monday day of that week? So, if a date read TUESDAY 30 JULY, i would want it to be automatically updated to MONDAY 29 JULY. I figured an UPDATE TABLE, but unsure where to go from there. Thanks!

A: You need something similar to this:
UPDATE tablename SET fieldname = fieldname-Weekday(fieldname,2)+1

Weekday() returns a number 1..7 indicating the day of the week. By default, 1 is Sunday. The argument 2 says to starting counting from Monday, so Monday is 1 and Sunday is 7.
So, for example, if the field's date is a Monday it subtracts 1 then adds 1, remaining Monday; if it's Tuesday it subtracts 2 (0) then adds 1 = 1, Monday.


text:
Q: Digitalize old diagrams and tables Reading old science papers I found nomograms with chemical content, as for my example a nomogram of sulfuric acid and its enthalpy:

Is there a possibility to mathematical correctly digitalize this nomogram if one does not have the correct table of numbers which created it?
My approach would be "giving" a program the grid and its values and then "read" the curvature of the individual data.
Is this possible or am I here on the wrong forum for such a question?

A: You can try to use tesseract-ocr. This tool is giving you ejected text and box boundaries of each word/letter. They might solve your problem, you can try this approach.
I used this tool to detect, wether words belong to same line, are on the same level on the page.


text:
Q: SQLite JSON1 example for JSON extract\set SQLite has now an experimental JSON1 extension to work with JSON fields. The functions to choose from look promising, but I don't get how to use them in the context of a query.
Suppose I created the following table:
sqlite> create table user(name,phone);
sqlite> insert into user values('oz', json_array(['+491765','+498973']));

The documentation shows how to use json_each in a query, but all other functions lack some in context documentation.
Can someone with SQLite experience provide a few examples of how to use:

*

*json_extract

*json_set

A: So, here is a first example of how to use json_extract. First, the data is a inserted in a bit different way:
insert into user (name, phone) values("oz", json('{"cell":"+491765", "home":"+498973"}'));

Now, we can select all the users phone numbers as in normal sql:
sqlite> select user.phone from user where user.name=='oz';
{"cell":"+491765","home":"+498973"}
sqlite>

But, what if we don't care about land lines and we want only cell phones?
Enter json_extract:
sqlite> select json_extract(user.phone, '$.cell') from user;
+491765

And this is how to use json_extract.
Using json_set is similar. Given that the we want to update the cell phone:
sqlite> select json_set(user.phone, '$.cell', 123) from \
        user;
{"cell":123,"home":"+498973"}

You can combine those function calls in other SQL queries. Thus, you can
use SQLite with structured data and with unstructured data in the form of
JSON.
Here is how to update the user cell phone only:
sqlite> update user
   ...> set phone =(select json_set(user.phone, '$.cell', 721) from user)
   ...> where name == 'oz';
sqlite> select * from user;
oz|{"cell":721,"home":"+498973"}


text:
Q: How can I solve this situation about encoding with awt? public static void main(String [] args) throws Exception {
        setUp();

        prepareGUI();

        Label con=new Label("Entered Context :",Label.RIGHT);
        Label encode=new Label("Encoded text :",Label.RIGHT);
        Label decode=new Label("Decoded text :",Label.LEFT);
        Label head=new Label("Test");

        final TextField userText=new TextField(20);
        final TextField tencode=new TextField(20);
        final TextField tdecode=new TextField(25);

        byte [] encryptionBytes = null;

        Font headFont=new Font("Dialog",Font.PLAIN,20);
        Font labelFont= new Font("SansSerif",Font.PLAIN,15);
        head.setFont(headFont);
        con.setFont(labelFont); encode.setFont(labelFont); decode.setFont(labelFont);

        Button encoding=new Button("Encoding");
        Button decoding=new Button("Decoding");

        input=userText.getText();

        encryptionBytes = encrypt( input );
        BASE64Encoder encoder = new BASE64Encoder();
        BASE64Decoder decoder = new BASE64Decoder();
        final String encodeString = encoder.encode(encryptionBytes);
        final String decodeString = decrypt( decoder.decodeBuffer(encodeString) );

        encoding.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tencode.setText(encodeString);
            }
        });

        decoding.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tdecode.setText(decodeString);
            }
        });

        headerPanel.add(head);
        controlPanel.add(con);
        controlPanel.add(userText);
        controlPanel.add(encoding);
        encodePanel.add(encode);
        encodePanel.add(tencode);
        encodePanel.add(decoding);
        decodePanel.add(decode);
        decodePanel.add(tdecode);
        frame.setVisible(true);
    }

    private static byte [] encrypt(String input) throws InvalidKeyException, BadPaddingException,
    IllegalBlockSizeException {
        cipher.init( Cipher.ENCRYPT_MODE, key );
        byte [] inputBytes = input.getBytes();
        return cipher.doFinal( inputBytes );
    }

    private static String decrypt(byte [] encryptionBytes) throws InvalidKeyException, BadPaddingException,
            IllegalBlockSizeException {
        cipher.init( Cipher.DECRYPT_MODE, key );
        byte [] recoveredBytes = cipher.doFinal( encryptionBytes );
        String recovered = new String( recoveredBytes );
        return recovered;
    }

}

This is not completed source.
It starts coding without input value.
I hope to start encryption and decryption after I fill in the text field of context.
How can I do to solve this problem?

A: Encode and decode should be called by some AWT method like 'actionPerformed' instead in main method


text:
Q: Using Masonry.JS and Vue.JS I know how to use masonry.js apart from vue. However, I'm having issue getting it to function and be called correctly inside of the vue framework. I called it inside of the created or ready but neither seem to get the grid to form correctly. How can i get this to work inside the framework? Oh and I do have jquery called in the html before this script. Here is what I have inside the component :
Edit:
I can see that the masonry is effecting the grid by assigning its height with JS and changing the items to position absolute. However, its not placing them correctly. Its stacking them ontop eachother instead of sideby side like it should be in the grid.

<template>

</template>

A: I guess the vue-way of doing this is by using refs. Just assign a ref property to your html element inside the template and access it using the vm.$ref instance property inside the mounted callback.
A sample code may look like this:
<template>

</template>

A: As I saw it, most mv* frameworks like vue keep DOM elements (view) in sync with js (model), in the other hand, frameworks like masonry just need valid DOM to work.
So, the tricky part is to tell one to another when DOM has changed.
So the first change is when vue finished to render all DOM, as mentioned in other answers, we are notified on mounted lifecycle hook, here is where we can initialize masonry
mounted() {
    let grid = document.querySelector('.grid');
    this.msnry = new Masonry(grid, {
        columnWidth: 25
    });
},

In any other change to our view need also update masonry as well, if you change items size use layout() method, if you add or remove items use reloadItems() method
    methods: {
        toggle(item) {
            item.isGigante = !item.isGigante;
            Vue.nextTick(() => {
                // DOM updated
                this.msnry.layout();
            });
        },
        add() {
            this.items.push({
                isGigante: false,
                size: '' + widthClasses[Math.floor(Math.random() * widthClasses.length)] + ' ' + heightClasses[Math.floor(Math.random() * heightClasses.length)]
            });
            Vue.nextTick(() => {
                // DOM updated
                this.msnry.reloadItems();
                this.msnry.layout();
            });
        }
    }

Please note that those methods are called after vue has completed DOM update using Vue.nextTick function.
Here is a working fiddle.

A: In Vue2, there is no such thing as a ready lifecycle hook. Instead, the mounted lifecycle hook is triggered once the instance is "ready" in the way you think of.
Reference: https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

A: It could be that the vertical stack just indicates that masonry is not working (It's hard to tell without a codepen/plunkr).  @riyaz-ali has the right idea though.

A: you must call masonry inside mounted() event to make it work.
i am using this on my project (with imagesloaded) its work perfectly
massonryApply (container, context, selector) {
  container = $(`#${container}`)
  const $grid = container.imagesLoaded(function () {
    $grid.masonry({
      itemSelector: `.${selector}`,
      percentPosition: true,
      columnWidth: `.${selector}`
    })

    $grid.masonry('reloadItems')
  })
}


text:
Q: How to set correct offset of dots in pager of RecyclerView I have implemented a class that creates and manages a pager that I have to use with a recyclerView. It works correctly but I have two problems:

Offset is wrong and the inactive dot of the first page disappear when I pass to second page etc... How can I properly manage offset? I have this problem because I have to learn about canvas in java :)
public class CirclePagerIndicatorDecoration extends RecyclerView.ItemDecoration {

    private int colorActive = 0x727272;
    private int colorInactive = 0xF44336;

    private static final float DP = Resources.getSystem().getDisplayMetrics().density;

    /**
     * Height of the space the indicator takes up at the bottom of the view.
     */
    private final int mIndicatorHeight = (int) (DP * 16);

    /**
     * Indicator stroke width.
     */
    private final float mIndicatorStrokeWidth = DP * 2;

    /**
     * Indicator width.
     */
    private final float mIndicatorItemLength = DP * 16;
    /**
     * Padding between indicators.
     */
    private final float mIndicatorItemPadding = DP * 4;

    /**
     * Some more natural animation interpolation
     */
    private final android.view.animation.Interpolator mInterpolator = new AccelerateDecelerateInterpolator();

    private final Paint mPaint = new Paint();

    public CirclePagerIndicatorDecoration() {
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(mIndicatorStrokeWidth);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);

        int itemCount = parent.getAdapter().getItemCount();

        // center horizontally, calculate width and subtract half from center
        float totalLength = mIndicatorItemLength * itemCount;
        float paddingBetweenItems = Math.max(0, itemCount - 1) * mIndicatorItemPadding;
        float indicatorTotalWidth = totalLength + paddingBetweenItems;
        float indicatorStartX = (parent.getWidth() - indicatorTotalWidth) / 2F;

        // center vertically in the allotted space
        float indicatorPosY = parent.getHeight() - mIndicatorHeight / 2F;

        drawInactiveIndicators(c, indicatorStartX, indicatorPosY, itemCount);

        // find active page (which should be highlighted)
        LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
        int activePosition = layoutManager.findFirstVisibleItemPosition();
        if (activePosition == RecyclerView.NO_POSITION) {
            return;
        }

        // find offset of active page (if the user is scrolling)
        final View activeChild = layoutManager.findViewByPosition(activePosition);
        int left = activeChild.getLeft();
        int width = activeChild.getWidth();

        // on swipe the active item will be positioned from [-width, 0]
        // interpolate offset for smooth animation
        float progress = mInterpolator.getInterpolation(left * -1 / (float) width);

        drawHighlights(c, indicatorStartX, indicatorPosY, activePosition, progress, itemCount);
    }

    private void drawInactiveIndicators(Canvas c, float indicatorStartX, float indicatorPosY, int itemCount) {
        mPaint.setColor(Color.GRAY);

        // width of item indicator including padding
        final float itemWidth = mIndicatorItemLength + mIndicatorItemPadding;

        float start = indicatorStartX;
        for (int i = 0; i < itemCount; i++) {
            // draw the line for every item
            c.drawCircle(start + mIndicatorItemLength, indicatorPosY, itemWidth / 6, mPaint);
            //  c.drawLine(start, indicatorPosY, start + mIndicatorItemLength, indicatorPosY, mPaint);
            start += itemWidth;
        }
    }

    private void drawHighlights(Canvas c, float indicatorStartX, float indicatorPosY,
                                int highlightPosition, float progress, int itemCount) {
        mPaint.setColor(Color.RED);

        // width of item indicator including padding
        final float itemWidth = mIndicatorItemLength + mIndicatorItemPadding;

        if (progress == 0F) {
            // no swipe, draw a normal indicator
            float highlightStart = indicatorStartX + itemWidth * highlightPosition;
         /*   c.drawLine(highlightStart, indicatorPosY,
                    highlightStart + mIndicatorItemLength, indicatorPosY, mPaint);
        */
            c.drawCircle(highlightStart, indicatorPosY, itemWidth / 6, mPaint);

        } else {
            float highlightStart = indicatorStartX + itemWidth * highlightPosition;
            // calculate partial highlight
            float partialLength = mIndicatorItemLength * progress;
            c.drawCircle(highlightStart + mIndicatorItemLength, indicatorPosY, itemWidth / 6, mPaint);

            // draw the cut off highlight
           /* c.drawLine(highlightStart + partialLength, indicatorPosY,
                    highlightStart + mIndicatorItemLength, indicatorPosY, mPaint);
*/
            // draw the highlight overlapping to the next item as well
           /* if (highlightPosition < itemCount - 1) {
                highlightStart += itemWidth;
                *//*c.drawLine(highlightStart, indicatorPosY,
                        highlightStart + partialLength, indicatorPosY, mPaint);*//*
                c.drawCircle(highlightStart ,indicatorPosY,itemWidth/4,mPaint);

            }*/
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.bottom = mIndicatorHeight;
    }
}

And here, when I active the second page . First page inactive dot disappear:

A: I solved whit this:
    public class CirclePagerIndicatorDecoration extends RecyclerView.ItemDecoration {

    private int colorActive = 0xFF607D90;
    private int colorInactive = 0xFFCFD8DC;

    private static final float DP = Resources.getSystem().getDisplayMetrics().density;

    /**
     * Height of the space the indicator takes up at the bottom of the view.
     */
    private final int mIndicatorHeight = (int) (DP * 16);

    /**
     * Indicator stroke width.
     */
    private final float mIndicatorStrokeWidth = DP * 2;

    /**
     * Indicator width.
     */
    private final float mIndicatorItemLength = DP * 16;
    /**
     * Padding between indicators.
     */
    private final float mIndicatorItemPadding = DP * 4;

    /**
     * Some more natural animation interpolation
     */
    private final android.view.animation.Interpolator mInterpolator = new AccelerateDecelerateInterpolator();

    private final Paint mPaint = new Paint();

    public CirclePagerIndicatorDecoration() {
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(mIndicatorStrokeWidth);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);

        int itemCount = parent.getAdapter().getItemCount();

        // center horizontally, calculate width and subtract half from center
        float totalLength = mIndicatorItemLength * itemCount;
        float paddingBetweenItems = Math.max(0, itemCount - 1) * mIndicatorItemPadding;
        float indicatorTotalWidth = totalLength + paddingBetweenItems;
        float indicatorStartX = (parent.getWidth() - indicatorTotalWidth) / 2F;

        // center vertically in the allotted space
        float indicatorPosY = parent.getHeight() - mIndicatorHeight / 2F;

        drawInactiveIndicators(c, indicatorStartX, indicatorPosY, itemCount);

        // find active page (which should be highlighted)
        LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
        int activePosition = layoutManager.findFirstVisibleItemPosition();
        if (activePosition == RecyclerView.NO_POSITION) {
            return;
        }

        // find offset of active page (if the user is scrolling)
        final View activeChild = layoutManager.findViewByPosition(activePosition);
        int left = activeChild.getLeft();
        int width = activeChild.getWidth();

        // on swipe the active item will be positioned from [-width, 0]
        // interpolate offset for smooth animation
        float progress = mInterpolator.getInterpolation(left * -1 / (float) width);

        drawHighlights(c, indicatorStartX, indicatorPosY, activePosition, progress, itemCount);
    }

    private void drawInactiveIndicators(Canvas c, float indicatorStartX, float indicatorPosY, int itemCount) {
        mPaint.setColor(Color.GRAY);

        // width of item indicator including padding
        final float itemWidth = mIndicatorItemLength + mIndicatorItemPadding;

        float start = indicatorStartX;
        for (int i = 0; i < itemCount-1; i++) {
            // draw the line for every item
            c.drawCircle(start , indicatorPosY, itemWidth / 6, mPaint);
            //  c.drawLine(start, indicatorPosY, start + mIndicatorItemLength, indicatorPosY, mPaint);
            start += itemWidth;
        }
    }

    private void drawHighlights(Canvas c, float indicatorStartX, float indicatorPosY,
                                int highlightPosition, float progress, int itemCount) {
        mPaint.setColor(Color.RED);

        // width of item indicator including padding
        final float itemWidth = mIndicatorItemLength + mIndicatorItemPadding;

        if (progress == 0F) {
            // no swipe, draw a normal indicator
            float highlightStart = indicatorStartX + itemWidth * highlightPosition;

         /*
            c.drawLine(highlightStart, indicatorPosY,
                    highlightStart + mIndicatorItemLength, indicatorPosY, mPaint);
        */
            c.drawCircle(highlightStart, indicatorPosY, 20, mPaint);

        } else {
            float highlightStart = indicatorStartX + itemWidth * highlightPosition;
            // calculate partial highlight
            float partialLength = mIndicatorItemLength * progress;

            // draw the cut off highlight
           /* c.drawLine(highlightStart + partialLength, indicatorPosY,
                    highlightStart + mIndicatorItemLength, indicatorPosY, mPaint);
*/
            // draw the highlight overlapping to the next item as well
           if (highlightPosition < itemCount - 1) {
                highlightStart += itemWidth;
                /*c.drawLine(highlightStart, indicatorPosY,
                        highlightStart + partialLength, indicatorPosY, mPaint);*/
                c.drawCircle(highlightStart ,indicatorPosY,20,mPaint);

            }
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.bottom = mIndicatorHeight;
    }
}


text:
Q: Xcode debugging (breakpoint) issue I'm writing an iOS app in Objective-C for iOS 8.4 with Xcode 6.4. I have a variable (actually an item in an array) changing in unexpected ways.
In order to find out what is going on, I would like to have a way to make the program pause when a change on the variable is about to happen (or just happened), using some kind of "special break point".
Is this possible, if YES how?

A: What you want is a Watchpoint (see "Setting Watchpoints" here).
Basically they monitor memory for writes and break the program when that happens.
I think you can only set them from the debugging console, not the Xcode UI, with:
(lldb) watchpoint set variable myinstancevar

or
(lldb) w s v myinstancevar


text:
Q: Why do higher level players move between each attack? I always see players move between every attack, even if they are attacking a stationary target (for instance a tower) and there is no theat close that would make their current position worth changing?
I think this practice is called "kiting".
So why are they doing this, is there any advantage to modifying your position between every attack?

A: This is actually not only with ranged characters but with every character.This is called "Stutter-Stepping" and is more or less a habit of high elo players that actually comes with some benefits:
Training

*

*Training your Timing: You should always Click the turret at the exact same time as your AA timer resets.

*Training positioning: You reposition yourself every 0.7 seconds.

Real Benefits

*

*Dodging skillshots: It's easier to not get hit by anything if you constantly move when attacking a turret.

*Stay in the flow of the game: If you attack a turret and you do pretty much nothing for 10 seconds that's fatal! You need to be focussed for 100% of the time if you want to win and always clicking helps doing so.

Now the 4th point is pretty much the most important one. High elo players usually stutter step because of this point. Also the habit exists because of this need of focus. A high elo player will have a lot more APM than a mid-low elo one and if he doesn't do anything for 2-5 seconds his playstyle won't be as good as before for a certain amount of time.
So this is not kiting. Kiting is running away from a target while damaging it. For league champions Ashe/Vayne/Ezreal would be a good example for excellent kiters but you cannot kite a stationary target like a turret.


text:
Q: Autolayout aligning stack fixed 3x3 buttons I need some help with Auto layout. I'm trying to achieve the following:
What I'm trying to achieve
But when I run the app I get this
The end result should be:

*

*three buttons on top

*three buttons below

*fixed width and height 80x80

*centered of the screen.

This is how I used Autolayout for the above
When I fix the width and checked off top, right, bottom, and left
This is the results I get.
I hope someone can shed some light. I thought I knew how to use Autolayout but I guess I don't lol.

A: Just use another view as the container. Position it centred horizontally and centred vertically, and pin its width and height. Now you can position your child views how you like.


text:
Q: How to set acceptable number values for .equals(); command? I have here a problem regarding my program. I want to accept a range of values regarding on my edittext.
What I want to happen is to accept values ranging from 1-50. But i dont know how will i do it. I've set int, but it does not work. Can anyone help me?
Here is my simple code:
REDIRECT.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String Amount = txtbox1.getText().toString();

                if(Amount.equals(Here is the range of values that i want to accept from 1-50 numbers only))
                {

                final Intent i = new Intent(MainActivity.this, Redirect.class);
                startActivity(i);
                }
                else
                {
                    Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_LONG).show();
                }
            }
        });

A: Don't use equals for this:
try{
    int a=Integer.parseInt(txtbox1.getText().toString());
    if(i<=50&&i>=1){
        //it's in the range. Handle it
    }
}catch(NumberFormatExcepion e){
    //handle invalid input
}

A: String.equals() will only check for equality against one String argument. You can't change that. If you want to match on one of many Strings, perhaps write a loop over .equals() like so:
private boolean matchesOneOf(String string, String[] strings) {
    for(String thisString : strings) {
        if(string.equals(thisString)) {
            return true;
        }
    }
    return false;
}

Or better yet use an existing library class method such as List.contains()
List<String> strings = new ArrayList<String>();
strings.add("1");
strings.add("2");
strings.add("3");
...
strings.add("50");

if(strings.contains(txtbox1.getText().toString())){
    // do stuff if value is in the list of strings you specified
}

Anyway from the looks of this example you don't want a String but a numeric type (probably int) for amount. Then range checking becomes vastly simpler with the < > <= >= operators for example.


text:
Q: Ubuntu server ssh - works on one network, not another I'm very new to server management. I've set up a ubuntu 22.04 server on an old laptop. Up 'till now, I've been able to successfully ssh into it using my new laptop. Thinking that was that, I packed up my new laptop, left the old laptop at home with ethernet plugged in, and went off to visit a friend.
Now I'm on my friend's wifi, and I'm trying to ssh back into my old laptop, but I'm getting an error when attempting to do that:
ssh: connect to host xxx.xxx.xx.xx port 22: Connection timed out
Am I missing something? My assumption was that ssh would allow my new laptop to log in to my old laptop from anywhere. Is the fact that I'm attempting this from a different network than the host machine to blame? How can I remotely diagnose and fix this issue?


text:
Q: Does Serilog have a way to limit the overall size of a logEvent? I have a custom Sink which writes to an Azure Queue Storage, and for some events, especially when destructuring large instances, we are reaching the size limit of the message which Azure has on queued messages (64KB or 48KB for Base64 encoded messages). I get an exception when placing the message on the queue. I need to avoid the exception and truncate the message to fit.
Does Serilog have a built in way to help limit the overall size of a LogEvent, or do we have to code that limiter ourselves?

A: This needs to be implemented at the sink level because different representations have different size requirements. There is an example of size limiting for JSON in: https://github.com/serilog/serilog-sinks-seq/blob/dev/src/Serilog.Sinks.Seq/Sinks/Seq/SeqSink.cs#L147
Serilog also has Destructure.ToMaximumDepth(n), but this isn't precise enough for the kind of control you're looking for.


text:
Q: Crawling through Web-pages that have categories I'm trying to scrap a website that has a uncommon web-page structure, page upon page upon page until i get to the item i'm trying to extract data from,
edit(Thanks to the answers, I have been able to extract most data I require, however I need the path links to get to the said product)
Here's the code I have so far:
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class MySpider(CrawlSpider):

    name = 'drapertools.com'
    start_urls = ['https://www.drapertools.com/category/0/Product%20Range']

    rules = (
        Rule(LinkExtractor(allow=['/category-?.*?/'])),
        Rule(LinkExtractor(allow=['/product/']), callback='parse_product'),
    )

    def parse_product(self, response):

        yield {
            'product_name': response.xpath('//div[@id="product-title"]//h1[@class="text-primary"]/text()').extract_first(),
            'product_number': response.xpath('//div[@id="product-title"]//h1[@style="margin-bottom: 20px; color:#000000; font-size: 23px;"]/text()').extract_first(),
            'product_price': response.xpath('//div[@id="product-title"]//p/text()').extract_first(),
            'product_desc': response.xpath('//div[@class="col-md-6 col-sm-6 col-xs-12 pull-left"]//div[@class="col-md-11 col-sm-11 col-xs-11"]//p/text()').extract_first(),
            'product_path': response.xpath('//div[@class="nav-container"]//ol[@class="breadcrumb"]//li//a/text()').extract(),
            'product_path_links': response.xpath('//div[@class="nav-container"]//ol[@class="breadcrumb"]//li//a/href()').extract(),
        }

I don't know if this would work or anything, can anyone please help me here?
I would greatly appreciate it.
More Info:
I'm trying to access all categories and all items within them
however there is a categories within them and even more before I can get to the item.
I'm thinking of using Guillaume's LinkExtractor Code but i'm not sure that is supposed to be used for the outcome I want...
rules = (
        Rule(LinkExtractor(allow=['/category-?.*?/'])),
        Rule(LinkExtractor(allow=['/product/']), callback='parse_product'),
    )

A: You have the same structure for all pages, maybe you can shorten it?
import scrapy

class DraperToolsSpider(scrapy.Spider):
    name = 'drapertools_spider'
    start_urls = ["https://www.drapertools.com/category/0/Product%20Range"]

    def parse(self, response):
        # this will call self.parse by default for all your categories
        for url in response.css('.category p a::attr(href)').extract():
            yield scrapy.Request(response.urljoin(url))

        # here you can add some "if" if you want to catch details only on certain pages
        for req in self.parse_details(response):
            yield req

    def parse_details(self, response):
        yield {}

A: Why not using a CrawlSpider instead! It's perfect for this use-case!
It basically gets all the links for every page recursively, and calls a callback only for the interesting ones (I'm assuming that you are interested in the products).
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class MySpider(CrawlSpider):

    name = 'drapertools.com'
    start_urls = ['https://www.drapertools.com/category/0/Product%20Range']

    rules = (
        Rule(LinkExtractor(allow=['/category-?.*?/'])),
        Rule(LinkExtractor(allow=['/product/']), callback='parse_product'),
    )

    def parse_product(self, response):

        yield {
            'product_name': response.xpath('//div[@id="product-title"]//h1[@class="text-primary"]/text()').extract_first(),
        }


text:
Q: How to listen to bootstrap modal close event in react I want to listen to bootstrap modal close event in react, because I have a form in modal and want to clear fields when modal close. I know how to do it in jquery like this,
$('#modal-form').on('hidden.bs.modal', fnClearForm);

But here I want to bind a function in the component.
Note: I can't use react-bootstrap.
This is a similar question but it doesn't address my problem.
Here is my component,
class MyModal extends Component {

clearForm = () => {
  -- code here --
}

render() {
    return (

              -- form goes here --

    )
}

Here is how I open the modal,
..

A: I was looking for the same thing without using react-bootstrap, but I REALLY wanted to know when the modal was opened and then closed (keypress, click outside or close) so I could run my this.props.onClose function. I finally made a sort of hack using a MutationObserver and attaching it to the Bootstrap modal div. I also included a "catch" if an onClose prop isn't provided.

state = {
    isOpen: false
  }

  modalRef = React.createRef()

  // Check if already open and handle onClose if closing
  observer = new MutationObserver(mutation => {
    const hasShowClass = mutation[0].target.classList.contains('show')
    const { isOpen } = this.state

    if(hasShowClass && !isOpen) {
      this.setState({
        isOpen: true
      })
    } else if(!hasShowClass && isOpen) {
      this.props.onClose()
      this.setState({
        isOpen: false
      })
    }
  })

  componentDidMount() {
    this.props.onClose &&
      this.observer.observe(this.modalRef, {
        attributes: true,
        attributeFilter: ['class']
      })
  }

  componentWillUnmount() {
    this.props.onClose && this.observer.disconnect()
  }

 this.modalRef = e} className="modal fade" id={this.props.id} tabIndex="-1" role="dialog" aria-labelledby={`user-form-modal-label`} aria-hidden="true">

A: IMHO, Since you can't use the react package for bootstrap and only using the cdn.
I think there is no accurate way to listen the closing of the modal.
Another thing is there are few way to close a boostrap modal. (Escape Key, Clicking the background will also close the modal).
The best way I can think of on the spot is to clear the form each time it is opened.
We may not be able to listen the closing of the modal but atleast we can know when it will be opened.
Here is the sample snippet I made
Fiddle : https://jsfiddle.net/keysl183/69z2wepo/318595/
class MyModal extends React.Component {
        constructor(props){
        super(props);
      this.handleOnChange = this.handleOnChange.bind(this);
      this.state= {
        testInput:""
      }
    }

    handleOnChange(e){
        this.setState({
            [e.target.name] : e.target.value
        })
    }

    ClearForm =() =>{
      this.setState({testInput:""});
    }

  render() {
      return (

                   Hi

                   Test Modal
                   <input type="text"  onChange={this.handleOnChange} name="testInput" value={this.state.testInput}  ></input>

      )
  }
}

class Hello extends React.Component {
  constructor(props){
    super(props);
        this.MyModal = React.createRef();
  }

  render() {
    return

      <MyModal ref={this.MyModal}></MyModal>
    {this.MyModal.current.ClearForm()}}className="btn" data-toggle="modal" data-target="#add-user-modal">SHOW MODAL

;
  }
}

ReactDOM.render(
  <Hello />,
  document.getElementById('container')
);

This will clear the input inside the modal component each time it is opened.
Also, I find it easier to create a ref instead of props when toggling a modal.
You can avoid messy props and just declare a single function inside the modal component and reuse it anywhere.


text:
Q: Udt as SQL Server SP parameter coming through empty I've got a bit of a problem that I just cannot fathom. I'm passing a user defined table type as a parameter from C# to a SQL Server stored procedure and always end up with 0 rows in the table once it reaches the SP. The .NET code is Framework 4.7, the SQL Server is hosted in Azure.
The SP definition is
CREATE PROCEDURE [dbo].[sp_ImportData]
    @ImportData udt_ImportData READONLY
AS
    INSERT INTO dbo.DEBUG ([Key], [Value])
         SELECT 'IMPORTDATA',
                (SELECT COUNT(1)
                   FROM @ImportData);

    ...
RETURN 0

The udt is defined as
CREATE TYPE [dbo].[udt_ImportData] AS TABLE
(
    RecordId INT,
    RecordName NVARCHAR(100)
);

The code I'm calling the SP with is
var table = new DataTable();
table.Columns.Add("RecordId", typeof(int));
table.Columns.Add("RecordName", typeof(string));

foreach (DataRow row in data.Rows)
{
    table.Rows.Add(row["RecordId"], row["RecordName"]);
}

using (var connection = new SqlConnection(_connectionString))
{
    var command = new SqlCommand("sp_ImportData", connection);
    SqlParameter tvpParam = command.Parameters.AddWithValue("@ImportData", table);
    tvpParam.SqlDbType = SqlDbType.Structured;
    tvpParam.TypeName = "dbo.udt_ImportData";

    connection.Open();
    command.ExecuteNonQuery();
}

Whilst debugging, I've checked that there actually are data rows in the table variable before it's attached as a parameter value. I've also inserted some debugging code into the SP to log out the number of rows in the @ImportData table once it's passed in. This always comes out as zero. I've tried using and not using the @ symbol in the parameter name, I've tried renaming the parameter (in case it was a reserved word that I wasn't aware of). I've tried adding and removing the "dbo." prefix to the udt name in C# but none of these have worked.
If anyone could help, I'd be very appreciative; this is driving me mad! I'm sure it's something quite small that I'm not seeing!

A: As I wrote in my comment - you didn't specify the command type in your c# code. The default value of the CommandType property is CommandType.Text - that fits inline sql but not stored procedures, so you need to specify CommandType.StoredProcedure. While we are at it, you don't have to specify the parameter's type name, and you really should avoid using AddWithValue.
One more thing - SqlCommand also implements the IDisposable interface, so it also should be used inside a using statement:
using (var connection = new SqlConnection(_connectionString))
{
    using(var command = new SqlCommand("sp_ImportData", connection))
    {
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add("@ImportData", SqlDbType.Structured).Value = table;
        connection.Open();
        command.ExecuteNonQuery();
    }
}


text:
Q: How to visualize all the decision tree of the random forest using graphviz I want to visualize each of the Decision Tree in the Random Forest. For which the code is as below:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split

boston=load_boston()
boston_df=pd.DataFrame(boston.data,columns=boston.feature_names)
boston_df['Price']=boston.target
newX=boston_df.drop('Price',axis=1)
newY=boston_df['Price']
X_train, X_test, y_train, y_test = train_test_split(newX, newY, test_size=0.2)

from sklearn.ensemble import RandomForestRegressor
original_regressor = RandomForestRegressor(n_estimators = 10, random_state = 0)
original_regressor.fit(X_train, y_train)

from sklearn.tree import export_graphviz
from sklearn.externals.six import StringIO
from IPython.display import Image
import pydotplus

dot_data = StringIO()
for tree_in_forest in original_regressor.estimators_:
export_graphviz(tree_in_forest, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = ['CRIM', 'ZN','INDUS','CHAS','NOX','RM','AGE','DIS','RAD','TAX','PTRATIO','B','LSTAT'], node_ids = True)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
Image(graph.create_png())

The error I am getting is:
AttributeError: 'list' object has no attribute 'create_png'
Most of the solutions is updating the package from pydot to pydotplus. In my case, I am already using pydotplus. Here the function pydot.graph_from_dot_data returns a list if there are multiple graphs. I am assuming the error is because of this. If so, how do we solve this problem?


text:
Q: PHP Connection Receives Error on Load I'm receiving an error message when I load my page. This is the code:
$conn=mysql_connect("localhost","","");
    if(!$conn)
    {
        die("died");
    }
        $db=mysql_select_db("kart",$conn);
        if(!$db)
        {
            echo(mysql_error($conn));
        }
        $query="select * from category";
        $result=mysql_query($query,$conn);
        if($result)
        {
            $row=mysql_num_rows($result);
            echo($row);
        }
        else
        {
            echo(mysql_error($conn));
        }

What's the cause for the error message and what should I do to resolve it?
Error Message:  database not selected

A: Check your username and password , if your are using WAMP or easy PHP , default user is ('root','') and MAMP ('root,'root')
Syntax :
mysql_connect("localhost", "mysql_user", "mysql_password");

Try this :
$conn=mysql_connect("localhost","root","");

or this :
$conn=mysql_connect("localhost","root","root");

A: You haven't set the user, the default user is root
$conn=mysql_connect("localhost","root","");
                                 ^Here


text:
Q: SQL query: joins+condition+order I have 3 tables:
user(use_id, use_role),
message(mes_id, from_use_id[fk->user.use_id], mes_create_at),
message_user(mes_use_id, mes_id[fk->message.mes_id], to_use_id[fk->user.use_id])
User can be use_role=1(student) or use_role=2(teacher).
I have to get all Users that are use_type=1(student) sorted by last contact with teacher. No matter if student write to teacher or teacher write to student.

A: I assume you use ms sql:
select *
from
(
    select student.use_id, Message.mes_create_at, Message.from_use_id, Message_User.to_use_id
    from User student
    join Message on Message.use_id = student.use_id and student.use_role = 1
    join Message_User on Message_User.mes_id = Message.mes_id
    where Message_User.to_use_id in (select use_id from User where use_role = 2)

    union

    select Message_User.to_use_id, Message.mes_create_at, Message.from_use_id, Message_User.to_use_id
    from User teacher
    join Message on Message.use_id = teacher.use_id and teacher.use_role = 2
    join Message_User on Message_User.mes_id = Message.mes_id
    where Message_User.to_use_id in (select use_id from User where use_role = 1)
) as temp
order by mes_create_at desc


text:
Q: How to properly retain NSArray or basic use I have an nsarray that when I NSLog it from one of my methods I can see its contents, but when I try to look inside it from elsewhere it seems to be empty. I am aware that my memory management needs some work, could anyone help explain whats happening here?
NEW CODE
WorkOutList.h
#import <UIKit/UIKit.h>

@interface WorkOutList : UIViewController {

    NSManagedObjectContext *managedObjectContext;
    NSMutableArray *customWorkouts;
    NSArray *passedWorkout;
}

@property(nonatomic, retain)NSManagedObjectContext *managedObjectContext;
@property(nonatomic, retain)NSMutableArray *customWorkouts;
@property(nonatomic, retain)NSArray *passedWorkout;

-(IBAction)customWorkouts:(id)sender;

-(void)passWorkoutBack:(NSArray *)workout;

@end

WorkOutList.m
@implementation WorkOutList

@synthesize managedObjectContext, customWorkouts, passedWorkout;

- (void)viewDidLoad {
    [self setupContext];
    NSLog(@"View Did Load");
    customWorkouts = [[NSMutableArray alloc] init];
    passedWorkout = [[NSArray alloc] init];
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self fetchWorkoutList];
    NSLog(@"View will Appear");
    NSLog(@"Array from View Will Appear : %@", passedWorkout);

}

-(IBAction)customWorkouts:(id)sender{
    CoCoachAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    SelectedWorkout *selectedWorkout = [[SelectedWorkout alloc] initWithStyle:UITableViewStyleGrouped];

    [selectedWorkout recieveNeededData:customWorkouts];

    [appDelegate.practiceNavController pushViewController:selectedWorkout animated:YES];
    [selectedWorkout release];
}

-(void)passWorkoutBack:(NSArray *)workout{
    passedWorkout = workout;
    [passedWorkout retain];
}

- (void)dealloc {
    [super dealloc];
}

SelectedWorkout.h
#import <UIKit/UIKit.h>

@interface SelectedWorkout : UITableViewController {

    NSMutableArray *workoutListForTable;
}

@property(nonatomic,retain)NSMutableArray *workoutListForTable;

-(void)recieveNeededData:(NSMutableArray *)workoutList;

@end

SelectedWorkout.m(aside from all the stuff to set up the tableView)
    @implementation SelectedWorkout

    @synthesize workoutListForTable;

    -(void)recieveNeededData:(NSMutableArray *)workoutList{

        if (workoutListForTable != workoutList) {
            workoutListForTable = workoutList;
        }

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];

        CoCoachAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        WorkOutList *workoutListView = [[WorkOutList alloc]init];

        [workoutListView passWorkoutBack:[workoutListForTable objectAtIndex:indexPath.row]];
        [appDelegate.practiceNavController popViewControllerAnimated:YES];
    }

    - (void)dealloc {

        [workoutListForTable release];
        [super dealloc];
    }

    NSLog(@"other table : %@", workoutListForTable);
    [workoutListForTable retain];
}

A: Your memory management is fine albeit a bit awkward—you could just declare a retained property and avoid that retain at the bottom. Your issue though comes from the fact that 'viewWillAppear:' is being called before 'passWorkoutBack:', so it's blank at 2 because 2 is being called before 1. If you're expecting something at 2, then your 'fetchWorkoutList' method isn't working properly.

A: Your setter method should release the previous value and retain the new one, e.g.
– (void)passWorkoutBack:(NSArray *)workout {

    if (passedWorkout != workout) {

        [passedWorkout release];

        passedWorkout = [workout retain];

    }

}

Here, the if statement ensures that you don't accidentally release workout before it is retained.
Finally, since you call alloc in viewDidLoad, you should call release in viewDidUnload.

Since you are calling alloc and init in viewDidLoad, whatever value passedWorkout may have had is getting erased when this method is called. If you wish to retain its value even if the view is unloaded and reloaded, then you should allocate passedWorkout in the init method of the ViewController and, of course, release it in the dealloc method.

A: This is what I think I understand about the flow of your app:

*

*passWorkoutBack gives your view controller an NSArray, which it places in 'passedWorkout'.

*viewDidLoad is called and your 'passedWorkout' is reinitialised as an empty array.

*viewWillAppear is called and you realise your array is empty.

To be honest, I think this comes from a lack of understanding of designing robust code (don't worry, it's the hardest thing to learn in programming). Here are a few tips that I think would make this app flow smoother:

*

*Create a new init method for your viewController class and, in it, include an argument to give pass this workout array.

*If you get an array from somewhere, all you need to do is retain it (either by using a property as Inspire48 said, or by calling retain on the object as you've already done), you don't even need to allocate or initialise the array before you get it from wherever you get it.

*Understand the viewController lifecycle. Do you know the difference between viewDidLoad and viewWillAppear? If you don't, learn, because they are both good tools when utilised properly.

Anywho, I hope this helped and that I wasn't too 'preachy'. I'm assuming a lot about your app and you, so correct me on anything I'm wrong about. Cheers.


text:
Q: Xamarin Forms Binding - access parent property I cannot access the Page's ViewModel property in order to bind it to IsVisible Property. I can only bind it if I don't set the BindingContext. Is there a way I can access the page's viewmodel/root property while also setting the BindingContext?
Page XAML:
<eventViews:EventInfoWidget BindingContext="{Binding EventViewModel}" IsVisible="{Binding IsEventInfoWidgetEnabled}" />
<eventViews:AvailableShiftInfoWidget BindingContext="{Binding EventViewModel}" IsVisible="{Binding IsAvailableShiftInfoWidgetEnabled}"></eventViews:AvailableShiftInfoWidget>

ViewModel:
public EventViewModel EventViewModel { get; }
public bool IsEventInfoWidgetEnabled => _IsEventInfoWidgetEnabled.Value;
public bool IsAvailableShiftInfoWidgetEnabled => _IsAvailableShiftInfoWidgetEnabled.Value;

The IsVisibile Property can only be bind to the EventViewModel Object Properties, but I would like to bind it to the page's viewmodel

*

*IsEventInfoWidgetEnabled

*IsAvailableShiftInfoWidgetEnabled

A: Found the solution, you have to specify the source and then set the path to the property.
First set the name of the page
<pages:AppContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
x:Name="ShiftPage">

After that just bind IsVisible Property to the right source
IsVisible="{Binding Source={x:Reference ShiftPage}, Path=BindingContext.IsEventInfoWidgetEnabled }"


text:
Q: different compare funcs for bsearch Either cmp func seems to work; cant understand how an arg1 of type int* is being resolved in the case of qsort_cmp.
As far as I can figure: int* is passed to qsort_cmp where it is changed to void*, then in return statement cast to struct s*. So far no problem, but then cast object is supposed to have a member called b, which its cast type does but its instance does not...
struct s { int a, b; };

int qsort_cmp(const void *r1, const void *r2) {
     return ((struct s*) r1)->b - ((struct s*) r2)->b;
}

int bsearch_cmp(const void *key, const void *r2) {
     return *(int*) key - ((struct s*) r2)->b;
}

/* themap is already qsorted */
int k = 'w'//hatever;
void *ret = bsearch(&k, themap, thenumber_ofelements, sizeof(one_element), qsort_cmp);

A: These comparison function are not interchangeable: one compares the b fields of both arguments, the other compares an int pointed to directly by the first argument and the b field of the structure pointed to by the second argument. They would be equivalent if the a field was used instead of b, as the a field is at the beginning of the structure.
Here is the specification:

7.22.5.1 The bsearch function
[...]
The comparison function pointed to by compar is called with two arguments that point to the key object and to an array element, in that order. The function shall return an integer less than, equal to, or greater than zero if the key object is considered, respectively, to be less than, to match, or to be greater than the array element.

Hence the first argument can be a pointer to an int and the second a pointer to an array of structures, as long as the comparison function is consistent with the bsearch calling scheme
Conversely, the comparison function used in qsort is called with 2 pointers to elements of the array, so both are pointers to s structures.
Note however that subtracting 2 int values is not a reliable way to produce the comparison result as this subtraction can overflow for many values: INT_MIN - 1 for example. A better method is this:
struct s { int a, b; };

int qsort_cmp(const void *r1, const void *r2) {
    const struct s *s1 = r1;
    const struct s *s2 = r2;
    return (s2->b < s1->b) - (s1->b < s2->b);
}

int bsearch_cmp(const void *key, const void *r2) {
    const int *ip = key;
    const struct s *s2 = r2;
    return (s2->b < *ip) - (*ip < s2->b);
}

Modern compilers generate branchless code for this: https://godbolt.org/z/sW3dn6


text:
Q: Extra bytes are added when I run my compressed file in my decompression method I'm working with text files here. My LZW decompression doesn't seem to work correctly. Something is wrong when I try to decompress my compressed file back: I get extra bytes added to the text file after decompression. As of now, I found the sequence of values that's causing the issue, it's the * (star character)
For example, When I have a text file containing this following sentence:
*** Hello ***

Here's how my decompression works (I'm showing only 2 iterations):
#1 iteration
priorword = 42
currword = 256
Added in dict: 256: **

Wrote in file: **

#2 iteration
priorword = 256
currword = 32
Added in dict: 257: **_     (_ means space)
Write in file: **

We know have in file: ****_

What could be wrong here, an extra star gets added because as you can see the original file has three stars.
After decompression, I get: **** Hello **
A star * from the right is added to the left, how could this be?
Decompression method:
public void LZW_Decompress(String input) throws IOException {
        // DictSize builds up to 4k, Array_Char holds these values
        Array_char = new String[4096];

        for (int i = 0; i < 256; i++) {
            dictionary.put(i, Character.toString((char) i));
            Array_char[i] = Character.toString((char) i);
        }

        // Read input as uncompressed file & Write out compressed file
        RandomAccessFile in = new RandomAccessFile(input, "r");
        RandomAccessFile out = new RandomAccessFile(input.replace(
                ".lzw", ""), "rw");

        try {
            // Gets the first word in code and outputs its corresponding char
            buffer[0] = in.readByte();
            buffer[1] = in.readByte();
            priorword = getvalue(buffer[0], buffer[1], onleft);
            onleft = !onleft;
            out.writeBytes(Array_char[priorword]);

            // Reads every 3 bytes and generates corresponding characters
            while (true) {
                if (onleft) {
                    buffer[0] = in.readByte();
                    buffer[1] = in.readByte();
                    currword = getvalue(buffer[0], buffer[1], onleft);
                } else {
                    buffer[2] = in.readByte();
                    currword = getvalue(buffer[1], buffer[2], onleft);
                }
                onleft = !onleft;

                if (currword >= dictSize) {
                    if (dictSize < 4096) {
                        Array_char[dictSize] = Array_char[priorword]
                                + Array_char[priorword].charAt(0);
                    }
                    dictSize++;
                    out.writeBytes(Array_char[priorword]
                            + Array_char[priorword].charAt(0));
                } else {
                    if (dictSize < 4096) {
                        Array_char[dictSize] = Array_char[priorword]
                                + Array_char[currword].charAt(0);
                    }
                    dictSize++;
                    out.writeBytes(Array_char[currword]);
                }
                priorword = currword;
            }
        } catch (EOFException e) {
            in.close();
            out.close();
        }
    }


text:
Q: Where can I find the description documents of these metrics? Where can I find the description documents of these metrics?
example:
alertmanager_cluster_pings_seconds_sum
apiserver_request_total
certificate_depth

Are there metrics documents to explain?
I'don't know where to get it.

A: As @weibeld said in a comment you should find metrics' description in the target that you fetch them from. By now, please find description of metrics that you are looking for:

*

*alertmanager_cluster_pings_seconds - histogram of latencies for ping messages.

*apiserver_request_total - accumulated number of apiserver requests broken out for each verb API resource client and HTTP response contentType and code (Only present from kubernetes 1.15 to replace apiserver_request_count).

*certificate_depth - current depth of workqueue - certificate.

I hope it will helps you.


text:
Q: Selenium WebDriverException: Reached error page I am following a Django TDD tutorial at:
http://www.marinamele.com/taskbuster-django-tutorial/taskbuster-working-environment-and-start-django-project
I get the following error when running 'all_users.py' before and after I start the development server 'python manage.py runserver':

Traceback (most recent call last):
   File "functional_tests/all_users.py", line 15, in test_it_worked
     self.browser.get('http://localhost:8000')
   File "/Users/samgao/.virtualenvs/tb_test/lib/python3.6/site->packages/selenium/webdriver/remote/webdriver.py", line 264, in get
     self.execute(Command.GET, {'url': url})
   File "/Users/samgao/.virtualenvs/tb_test/lib/python3.6/site->packages/selenium/webdriver/remote/webdriver.py", line 252, in execute
     self.error_handler.check_response(response)
   File "/Users/samgao/.virtualenvs/tb_test/lib/python3.6/site->packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
     raise exception_class(message, screen, stacktrace)
  selenium.common.exceptions.WebDriverException: Message: Reached error page: >about:neterror?e=connectionFailure&u=http%3A//localhost%3A8000/&c=UTF->8&f=regular&d=Firefox%20can%E2%80%99t%20establish%20a%20connection%20to%20the%20s>erver%20at%20localhost%3A8000.

Basically the connection to localhost cannot be established.
The settings and configurations are identical to the tutorial in the previous link.
I have been struggling with the issue for two days, and would thank you most kindly if you could provide any help.

A: I got the same error and what solved for me was changing from localhost to 127.0.0.1:

*

*old: self.browser.get('http://localhost:8000')

*better: self.browser.get('http://127.0.0.1:8000')

A: I encountered the same problem, the final solution is: re-install again geckodriver

*

*Unzip the geckodriver.zip

*Move the file to /usr/bin directory sudo mv geckodriver /usr/bin

*Goto /usr/bin directory cd /usr/bin,then you would need to run something like sudo chmod a+x geckodriver to mark it executable.

A: this might not be your situation, but I got the same error message when running a test (same book, hehe) without having anything actually listening on the targeted port (8000, in my case). Make sure there's something listening for a request by manually opening your browser and going to localhost:8000. In my case - silly me - I didn't have the server up at all =)

A: I also followed the same tutorial and came across the same error. I noticed that I am not running the django server. The following is what helped.
python manage.py runserver
python functional_test.py

A: Being that this is a snapshot (around Django 1.8's time) of "Obey The Testing Goat" - perhaps the instructions there are no longer relevant. I suggest going straight to the goat's mouth and starting over!
The issue could be related to virtualenvwrapper (which is no longer necessary) or it could be related to the port/address that you were trying to access. Depending on your version of Selenium and Firefox there may be issues related to that as well.

A: It depends on the situation.
Based on mine, after I changed the target URL, I can get the browser to load the URL normally, which means the original URL is not available.
Another way to check:
import requests
html = request.get(url)

Print the HTML, if you get the 503, which means the website is reachable.

A: Since this is probably a common search result for those working through Obey the Testing Goat, I wanted to share the solution that worked for me. I had written self.browser.get('http://localhost:8000') and needed to use http instead of https to resolve the error.

A: I got this problem in this situation: the application put the computer name to the proxy host,so the proxy like this:
theComputerName:proxyPort

but the theComputerName:proxyPort can not be visit,so I put this into the host:
127.0.0.1 theComputerName

then restart the application,the problem resolved perfect

A: I learning TDD tutorial too. My problem was that inputed uncorrect url
http://http://mysite insted of http://mysite


text:
Q: Criar caixa de procura no google docs Boas,
tenho este código VBA e precisava de construir um Javascript para o Google Docs que faça a mesma coisa.
É possível converter o VBA em Javascript?
Obrigado.
Private Sub CommandButton1_Click()
Dim F1 As Worksheet
Dim intervalo As Range
Dim LastRow As Long
'Declara a Planilha pelo nome
Set F1 = ThisWorkbook.Worksheets("Folha1")
'Última Linha
LastRow = F1.Cells(F1.Rows.Count, "A").End(xlUp).Row

Set intervalo = F1.Range("A2:A" & LastRow)
'Caso não encontre TextBox2
If TextBox2 = "" Then
    MsgBox "Insira o nº da ficha a consultar."
'Se os campos de TextBox estiverem preenchidos
ElseIf TextBox2 > "" And TextBox1 > "" Then
'Realiza a procura
    With intervalo
        Set cellFound = .Find(TextBox1, LookIn:=xlValues)
        If Not cellFound Is Nothing Then
            FirstAddress = cellFound.Address
            Do
                'Realiza Ação após encontrar, faz offset de uma coluna para direita e segue o hyperlink. Então após encontrar na Coluna A, segue o hyperlink da coluna B.
                cellFound.Offset(0, 1).Hyperlinks(1).Follow
                Set cellFound = .FindNext(cellFound)
            Loop While Not cellFound Is Nothing And cellFound.Address <> FirstAddress
        End If
    End With
End If
TextBox2.SetFocus

End Sub

Private Sub TextBox1_Change()
    Dim intervalo As Range
    Dim texto As String
    Dim codigo As Integer
    Dim pesquisa
    Dim mensagem
    Dim F1 As Worksheet
    Set F1 = ThisWorkbook.Worksheets("Folha1")
    LastRow = F1.Cells(F1.Rows.Count, "A").End(xlUp).Row
   On Error Resume Next
    codigo = TextBox1.Text

    Set intervalo = F1.Range("A2:B" & LastRow)
    pesquisa = Application.WorksheetFunction.VLookup(codigo, intervalo, 2, False)

    TextBox2.Text = pesquisa

End Sub

'Private Sub UserForm_Terminate()
'ActiveWorkbook.Close Savechanges:=False
'End Sub

A: Fiz uma solução em App Script que seria uma conversão do seu VBA. Espero que seja o que você precisa.
O link do arquivo funcionando é esse:
https://docs.google.com/document/d/1Kl7v3NnIBxOB_V6sIMiIyzFRN-CGsizq8_iZEtQVeBM/edit?usp=sharing
Foram criados dois arquivos no App Script, sendo eles:
Código.gs
function onOpen(e) {
   DocumentApp.getUi()
       .createMenu('Pesquisar')
       .addItem('Documentos', 'showSidebar')
       .addToUi();
}

function onInstall(e) {
  onOpen(e);
}

function showSidebar() {
  var ui = HtmlService.createHtmlOutputFromFile('Sidebar')
      .setTitle('Pesquisar Documentos');
  DocumentApp.getUi().showSidebar(ui);
}

function BuscarCodigo(codigo) {

  if(codigo != null) {
    DocumentApp.getUi().alert(codigo);
  }

  var table = DocumentApp.getActiveDocument().getBody().getTables();

  var codigos = [];
  var links = [];
  var x = 1;
  while(x < table[0].getNumRows()) {
    codigos.push(table[0].getCell(x, 0).getText());
    links.push(table[0].getCell(x, 1).getText());
    x++;
  }

  var y = 0;
  var link = "";
  while(y < codigos.length) {
    if(codigo == codigos[y]) {
      DocumentApp.getUi().alert(links[y]);
      link = links[y];
      break;
    }
    y++;
  }

  AbrirLink(link);

}

function AbrirLink(link) {
  var ui = HtmlService.createHtmlOutput(
  "<!DOCTYPE html> " +
  " " +
  " " +
    " " +
  " " +
  " " +
  " " +
  " "
  );
  DocumentApp.getUi().showSidebar(ui);
}

Sidebar.html
<!DOCTYPE html>

    <base target="_top">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <form role="form" id="formulario" name="formulario" align="center">

        Código
        <input type="text" class="form-control" name="codigo" id="codigo" placeholder="Insira o código do Documento">

      <button class="btn btn-success hidden" align="center" id="pesquisaroculto">
        Pesquisar
      </button>

      <button class="btn btn-success" align="center" id="pesquisar">
        Pesquisar
      </button>

    </form>

É somente a lógica sem validação de campos em branco que pode ser feita no html normalmente. Todos novos valores inseridos na tabela irão funcionar.
Não tem como fazer um campo de pesquisa dentro do Google Docs.
O que eu fiz foi um menu de Pesquisa de documentos no menu chamado "Pesquisar > Documentos" que abre um sidebar com um campo para digitar o código do documento e um botão para Pesquisar o documento.
Ao clicar nesse botão o link do documento pesquisado é aberto em uma nova guia.