text:
Q: $\lim_{x\rightarrow x_0} \frac{\langle v - x, x-x_0 \rangle}{||x-x_0||}=?$ Let $v$ and $x_0$ be fixed points in $\mathbb R^n$,  I don't know how to compute the limit $$\lim_{x\rightarrow x_0} \frac{\langle v - x, x-x_0 \rangle}{||x-x_0||}=?$$
Where $x\in \mathbb R^n$ and $||x-x_0||$ is the Euclidean distance between $x$ and $x_0$, here $x\rightarrow x_0$ means $||x-x_0||\rightarrow 0$. We may further assume that $\langle v - x, x-x_0 \rangle\geq 0$ if needed.
I guess that the limit should be $||v-x_0||$. But how to prove that?

Edit. Let me add my attempt.
Without loss of generality, we may assume that $x_0=0$, thus
the quantity is equal to $\frac{\langle v, x\rangle}{||x||} -||x||$. We have $x\rightarrow 0$, then $||x||\rightarrow 0$. So the remaining is to find
$$\lim_{||x||\rightarrow 0} \frac{\langle v, x\rangle}{||x||}=?$$

A: If $v\neq 0$, there is no limit for
$$ \lim_{||x||\rightarrow 0} \frac{\langle v, x\rangle}{||x||}$$
Since when taking $x = tv$ we have
$$ \frac{\langle v, x\rangle }{\|x\| } = \begin{cases} \|v\| & t >0, \\ -\|v\| & t<0.\end{cases}$$
So the limit does not exist as $t\to 0$.


text:
Q: Assert workaround in JUnit I've seen today a non standard way of writing unit tests with JUnit,
instead of using the framework checks
Assert.assertTrue("Unexpected response encoding", text.length() >= 1);

a generic exception is thrown
if (text.length() < 1) {
    throw new Exception("Unexpected response encoding");
}

I want to to convince the author to adopt the first style. Beside reason like verbosity, clarity of intent do you know what else can differ in these approaches?

A: JUnit reports will show the first style as a "failure" whereas the second is shown as an "error" since an uncaught exception is thrown.
It depends on if you care about this type of labeling and is completely subjective, but personally I would prefer to see this as a "failure".

A: Their treatment in report is different in two ways:

*

*As mentioned by @Matt, one is failure while other is error.

*Imagene Assert.assertEquals, when failed, it reports both expected and found values in the report along with the message.

A: If your primary goal is to convince someone to use the first approach over the second and you need more ammo (I agree with Jon Skeet's comment that you shouldn't need more ammo.) then use some code coverage tool over your test code.
Good developers will effortlessly get 100% coverage on their unit tests.  Bad developers will not get 100% coverage without going into the if condition.  Either way you can nag the bad developer.  Why isn't your coverage 100%? or why do you have failing unit tests?
It s not fair, but it will motivate the desired behavior.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Transpose column with duplicates to unique columns I wonder if it's possible to transpose column with grouped duplicate fields, like for example:
+---------+------+
| field_1 | 1    |
| field_2 | 2    |
| field_3 | 3    |
| field_4 | 4    |
| field_1 | 5    |
| field_2 | 6    |
| field_3 | 7    |
| field_4 | 8    |
| field_1 | 9    |
| field_2 | 10   |
| field_3 | 11   |
| field_4 | 12   |
+---------+------+

to unique columns, like this:
+---------+---------+---------+---------+
| field_1 | field_2 | field_3 | field_4 |
+---------+---------+---------+---------+
| 1       | 2       | 3       | 4       |
| 5       | 6       | 7       | 8       |
| 9       | 10      | 11      | 12      |
+---------+---------+---------+---------+

Is this possible without scripting?

A: Enter the formula below in E3 (using Ctrl+Shift+Enter) then fill down and then across.
=OFFSET($C$1,LARGE((ROW($B$2:$B$13)-1)*($B$2:$B$13=E$2),ROW()-2),0) & ""

Values are not in the listed order but are at least in the correct column.
Will try to explain:

*

*All of the values we want for each of the distinct "field" values are offset by some "x" number of rows from C1

*Taking "field_1" as an example (ROW($B$2:$B$13)-1)*($B$2:$B$13=E$2) will return an array of row numbers multiplied by either 1 (TRUE) or zero (FALSE) depending on whether the "B" cell value matches "field_1" (from E2). The -1 is an adjustment because we're starting on row 2.  The returned array looks like:
[1,0,0,0,5,0,0,0,9,0,0,0]

*Given that array, we need to find some way to get at the non-zero values one by one: we can use LARGE() to do that, incrementing the second argument to LARGE using ROW()-2 (-2 because we want that second argument to begin at 1 and the formula is being entered in row 3).  This gives us an ordered array of values:
[9,5,1,0,0,0,0,0,0,0,0,0]

*We pass this ordered array as the "row offset" argument to OFFSET(), counting  down from C2: all non-zero values give us the value we want from Col C, whereas all the zero values just return C2 (which is empty, and would show as 0 without that last & ""

*All cell references in the formula use $ where needed so it adjusts as needed on dragging to fill down/across

A: This only gets you so far. You still need to remove duplicates. In D2:
=INDEX($B1:$B$12,MATCH(D$1,$A1:$A$12,0))

A: My answer is very similar to Tim's but avoids the CSE part and internalizes it within the AGGREGATE function.  Also believe it will preserve the vertical order in which the element in B occurs (not tested though).
In D1 use the following formula and copy right to get your unique list of headers.
=INDEX($A$1:$A$12,MATCH(0,INDEX(COUNTIF($C1:C1,$A$1:$A$12),0,0),0))

Then in D2 use the following to pull your information from column B.  It can be copied to the right and down.  When an item is not found it will display not found.  you can change this to "" if you prefer.
=IFERROR(INDEX($B$1:$B$12,AGGREGATE(15,6,ROW($A$1:$A$12)/($A$1:$A$12=D$1),ROW(1:1))),"Not found")

Proof of Concept

Note on OFFSET
OFFSET is a volatile function meaning that it will recalculate anytime anything on the worksheet changes, not just the cells it works with.  As such if you are only using it a couple of times, no big deal.  However if you are using it repeatedly you may experience a slow down with your worksheet.


text:
Q: CSS3 Transform causing text to flicker in Safari and Firefox Mac Yosemite I'm having this weird issue on Safari and Firefox (Mac/Yosemite) that causes almost all of the text on the page to flicker when hovering over the transforming element.
Example gif: (Firefox, Yosemite)

.usp {
   //USP has an icon that is defined below
    opacity: .4;
    @include transition(all .3s ease-in-out);

    &:hover {
        opacity: 1;
        @include transition(all .3s ease-in-out);

        .icon {
            @include transform(scale(1.1));
            @include transition(all 1.7s ease-in-out);
        }
    } // :hover
}

.usp .icon {
    display: block;
    height: 75px;
    width: 75px;
    // Insert background-image sprite (removed from this example)
    @include transition(all .3s ease-in-out);
    @include transform(scale(1.0));
}

I've tried the following things:
Add every possible combination of these styles to the body, the transforming element and/or his parent
-webkit-transform-style:preserve-3d;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
 backface-visibility: hidden;
-webkit-filter: opacity(.9999);
-webkit-font-smoothing: antialiased;
-webkit-transform: translate3d(0, 0, 0);
-moz-transform: translate3d(0, 0, 0);
-webkit-transform: translate3d(0, 0, 0);
 transform: translate3d(0, 0, 0);
-webkit-font-smoothing: subpixel-antialiased;
-webkit-text-stroke: 0.35px;

If (styles below) are applied to the body, the problem is fixed in Safari but not in Firefox as it is not a webkit browser.
-webkit-transform: translate3d(0, 0, 0);
-webkit-text-stroke: 0.35px;

I have literally no idea what causes this and how I can fix it!

A: Note to OP: you seem to be at least aware of most of these concepts, but I've included plenty of detail in this answer for anyone else who might have a similar problem.
In modern browsers running on a computer that has a dedicated GPU (processor for rendering graphics), the browser will sometimes shift the task of rendering the webpage from your CPU (the "normal" processor) to the GPU. The CPU and GPU each have their own strengths and weaknesses -- the nature of the GPU is that it can render 3-dimensional transformations very efficiently, but might not be able to render plain text as crisply as the CPU does.
Your hover effect is using a transformation that your browser has deemed appropriate for hardware-accelerated GPU rendering (most probably triggered by the scale(1.1) transformation), and so it has shifted rendering temporarily to the GPU while the hover animation/transition occurs. After the animation is done, the CPU takes over rendering again. Because of the different rendering strategies used by the different pieces of hardware, the text looks different (less crisp) while the GPU is in charge.
Unfortunately, we don't (yet) have explicit control of hardware acceleration via the CSS -- the browser sets that whenever it wants to. What we can do, however, is set some properties that we suspect will put the browser in hardware-accelerated GPU mode. The theory here is that we will keep the browser in GPU mode even when the animation isn't occurring, so that we don't see a "flicker".
This strategy has some downsides: users visiting your website will experience slightly increased RAM memory usage while your page is open, and mobile / laptop users will experience slightly increased battery drain. On devices that don't have a dedicated GPU, hardware acceleration won't be triggered (but then again, those devices wouldn't be seeing the "flicker" that you're seeing anyway).
It looks like you've attempted to do this already by adding the scale(1.0) property to the un-hovered element -- my best guess is that your browser(s) got "clever" and detected that this rule does nothing and ignored it. The most dependable way of triggering hardware-acceleration is typically a transformation on the Z-axis. Try changing your transformation to the following:
@include transform(scale(1.00001), translateZ(0.00001));

Rather than using the values "1" and "0", I'm using infinitesimally close values; hopefully this will prevent the browser from getting "clever" and ignoring the rule.
I'm assuming your Sass include there is doing vendor-prefixing. Double-check that the final output includes not only the -webkit-transform: and -moz-transform:, but that it also contains the un-prefixed transform: syntax. If you want to be certain (for the purposes of debugging), just type them out manually:
.usp .icon {
  transform: scale(1.00001), translateZ(0.00001);
  -webkit-transform: scale(1.00001), translateZ(0.00001);
  -moz-transform: scale(1.00001), translateZ(0.00001);
}

On my end, I didn't experience any flicker to start with on your fiddle (I suspect that my browser/OS/hardware configuration doesn't think that a 2-dimensional scale is appropriate for the GPU), so I'm unable to test this code. However, I have used similar techniques to solve similar problems quite often.

A: Ahhh, but have you tried
.usp .icon {
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
}

http://jsfiddle.net/j04mayvb/4/

I honestly have no idea why this works, but I can see it stopping the flickering on your Fiddle in Safari.

A: Alright!
After a week of testing, removing and adding CSS rules I finally found the solution that fixed my problem. I originally had this problem in both Firefox 39 and Safari 9 but Firefox mysteriously fixed itself with the latest update. Safari however, did not. The problem has to do with the 3D rendering of elements on the page. The element I tried to scale had to be transformed into 3D context, the flickering elements on the page switched between 2D and 3D as explained by @Woodrow-Barlow in the other answers.
By adding
-webkit-transform: translate3d(0, 0, 0);

to the flickering elements, and thus rendering them in 3D on page load, they no longer had to switch!
EDIT 1: For people who have this issue in other browsers, take a look at the CSS 'will-change' property:
https://dev.opera.com/articles/css-will-change-property/

A: OK!
So, the problem i faced was in a custom popup where i had a wheel effect on the cross button using css transition. But that caused flicker issue in the popup.
After visiting various online portals, i got to know that transition property:
webkit-backface-visibility: hidden;

on the transitioned element really works and stops the flickering. But using this property blurred the whole component (popup) in my case and to stop that, i had to use another property on the root element of the component:
webkit-transform: translate3d(0, 0, 0);

but as i was using it in a custom popup which was already translated -50% in y-direction to keep it in centre, i was restricted not to use it.
After playing with css properties for days and trying out various solutions, i came to a conclusion that total height of the component in which transitioned element is used must be EVEN and in case of dynamic data, we need to adjust the margins and paddings in such a way that total height remains EVEN.
This resolved my issue. Just make sure total height remains EVEN and adjust margins and paddings accordingly.
Hope it helps anyone in need too. :)

A: -webkit-transform: translate3d(0, 0, 0);
-webkit-text-stroke: 0.35px;

These codes are written for support multiple browser.
try this for mozila
-moz-transform: translate3d(0, 0, 0);
-moz-text-stroke: 0.35px;

A: I've found this mainly occurs on elements that have been transformed (ie: a modal that slides in).  Is there a transform on any of the parent elements?
There are a ton of fixes around the web for webkit based browsers, but nothing for Firefox.


text:
Q: how to remove previous result list immediately when updating recycler view? here is the short video of my problem:
https://drive.google.com/file/d/108Tk9rmJtF3Ir7Nj9hheW2JkvlqXggcj/view
so, I have a vertical recycler view that can be refreshed when the tab layout is tapped.
If I tap the first index of the tab, it will fetch some data from the server and populate the adapter and recycler view. but if I tap the second index, the data from server is actually empty.
here is the problem...
as you can see from the short video above. when I tap the second tab (from previously in the first tab), it still shows the list from the first tab appears for a second before eventually show an empty recycler view.
I want to make after the loading the data from server, that previous result will not show, and it should immediately show the result as per the tab selected.
I am using ListAdapter and using submitList() to update the data
here is the adapter I use:
class GeneralEventRecyclerViewAdapter(val mContext: Context): ListAdapter<Event, RecyclerView.ViewHolder>(DIFF_CALLBACK) {

    lateinit var mOnEventKMListener : OnEventKMListener

    fun setOnItemClickListener(listener: OnEventKMListener) {
        mOnEventKMListener = listener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_general_event, parent, false)
        return GeneralEventViewHolder(itemView, mOnEventKMListener)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

        val currentEvent = getItem(position)
        val generalEventViewHolder = holder as GeneralEventViewHolder

        Glide.with(mContext).load(currentEvent.thumbnailDownloadPath)
            .apply(RequestOptions.bitmapTransform(BlurTransformation(25, 3)))
            .into(generalEventViewHolder.blurThumbnailImageView)

        Glide.with(mContext).load(currentEvent.thumbnailDownloadPath).into(generalEventViewHolder.thumbnailImageView)

        generalEventViewHolder.eventNameTextView.text = currentEvent.title
        generalEventViewHolder.eventVenueTextView.text = currentEvent.venue
        generalEventViewHolder.eventDateTimeTextView.text = DateTimeService.changeDateToString("EEEE, d MMMM. HH:mm zzz",currentEvent.dateTimeStart)

    }

    companion object {

        private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Event>() {
            override fun areItemsTheSame(oldItem: Event, newItem: Event): Boolean {
                return oldItem.eventID == newItem.eventID
            }

            override fun areContentsTheSame(oldItem: Event, newItem: Event): Boolean {
                return oldItem == newItem
            }

        }
    }

}

and here is the simplified my fragment class:
class SearchResultFragment : Fragment() {

    lateinit var titleTextView: TextView
    lateinit var progressBar : ProgressBar
    lateinit var fragmentView : View
    lateinit var tabLayout : TabLayout
    lateinit var recyclerView : RecyclerView

    lateinit var mContext : Context
    lateinit var mActivity : FragmentActivity
    lateinit var eventAdapter : GeneralEventRecyclerViewAdapter

    private var eventList = ArrayList<Event>()
    private var selectedEventType = EventType.kajianUmum
    private var selectedCity = City.defaultCityName
    private var selectedTime = EventTimeUserSelection.Weekend
    lateinit var userData : User

    private var startingDate = Date()
    private var endingDate = Date()

    override fun onAttach(context: Context) {
        super.onAttach(context)

        mContext = context
        activity?.let { mActivity = it }

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        fragmentView = inflater.inflate(R.layout.fragment_search_result, container, false)

        setUpSafeArg()
        setUpViewsDeclaration()
        setUpListeners()
        updateUI()
        setHasOptionsMenu(true)

        initRecyclerView()
        searchEvents()

        return fragmentView
    }

    private fun setUpViewsDeclaration() {
        titleTextView = mActivity.findViewById(R.id.destination_label_text_view)
        progressBar = mActivity.progressBar_main_activity
        recyclerView = fragmentView.findViewById(R.id.recyclerView_search_result)
        tabLayout = fragmentView.findViewById(R.id.tabLayout_time_search_result)

    }

    private fun setUpListeners() {

        tabLayout.addOnTabSelectedListener(object: TabLayout.OnTabSelectedListener {

            override fun onTabSelected(tab: TabLayout.Tab?) {

                selectedTime = when(tab?.position ?: 0) {
                    0 -> EventTimeUserSelection.All
                    1 -> EventTimeUserSelection.Today
                    2 -> EventTimeUserSelection.Tomorrow
                    3 -> EventTimeUserSelection.Weekend
                    4 -> EventTimeUserSelection.ThisWeek
                    5 -> EventTimeUserSelection.NextWeek
                    else -> EventTimeUserSelection.All
                }

                searchEvents()

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

        })

    }

    private fun initRecyclerView() {

        eventAdapter = GeneralEventRecyclerViewAdapter(mContext)
        val layoutManager = LinearLayoutManager(mContext, RecyclerView.VERTICAL,false)
        recyclerView.adapter = eventAdapter
        recyclerView.layoutManager = layoutManager

        eventAdapter.setOnItemClickListener(object: OnEventKMListener {

            override fun eventKMClicked(position: Int) {
                val selectedEvent = eventList[position]
                val eventDetailDestination = SearchResultFragmentDirections.actionGlobalDestinationEventDetail(selectedEvent)
                Navigation.findNavController(fragmentView).navigate(eventDetailDestination)
            }

        })

    }

    private fun searchEvents() {

        setStartingAndEndingDateForSearching()
        progressBar.visibility = View.VISIBLE
        recyclerView.visibility = View.GONE

        FirestoreKMClient.getFreeEvents(startingDate,endingDate,selectedCity,selectedEventType.getEventTypeInString(),10) { errorMessage, events ->

            errorMessage?.let {
                mActivity.toast(it)
            } ?: run {

                val theEvents = events ?: ArrayList()
                eventList = theEvents
                eventAdapter.submitList(eventList)
            }

            progressBar.visibility = View.GONE
            recyclerView.visibility = View.VISIBLE

        }

    }

}

Java is ok

A: I'm not good in kotlin but the my logic might work;
upon reading your code;
i guess you can try to set your adapter into null first so that it will clear all previous data that is been fetch on your first tab.

eventAdapter.submitList(null)

you can try to put it here :
 private fun searchEvents() {

        setStartingAndEndingDateForSearching()
        progressBar.visibility = View.VISIBLE
        recyclerView.visibility = View.GONE
        eventAdapter.submitList(null)

A: You should have to clear the list on a time of calling your data from database.
Try setting up empty list before call of new data i.e. In searchEvents() function below this line recyclerView.visibility = View.GONE.
recyclerView.visibility = View.GONE
eventList = arrayOf< Event>()
eventAdapter.submitList(eventList)


text:
Q: How to get current position of animating uiview in ios I want current position of animating UIView during animation and I am using this code.
CABasicAnimation * m_pAnimationObj = [CABasicAnimation animationWithKeyPath:@"transform.translation"];
[m_pAnimationObj setFromValue:[NSValue valueWithCGPoint:CGPointMake(0,-50)]];
[m_pAnimationObj setToValue:[NSValue valueWithCGPoint:CGPointMake(0,[UIScreen mainScreen].bounds.size.height+100)]];
m_pAnimationObj.duration = 2.0;
m_pAnimationObj.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[DropImage.layer addAnimation:m_pAnimationObj forKey:@"animations"];

Please answer if anyone knows about this.
Thank you in advance!

A: Use this code:
CGRect currentCenter = [drawingView.layer.presentationLayer center];

or
CGRect currentFrame = [DropImage.layer.presentationLayer frame];


text:
Q: How to get the grayscale pixel value for a given point (x,y) on an image? I have been trying to use the code below to extract the grayscale value associated with a given pixel of my image. I thought it was working but then I noticed my results were inconsistent with my image.
How can I get the correct grayscale value for a given pixel of my image at (x,y) from the 1D array that my pixelValues function returns?
I tried using index = x * width of image +y but this does not seem to be working.
func pixelValues(fromCGImage imageRef: CGImage?) -> (pixelValues: [UInt16]?, width: Int, height: Int)
{
    var width = 0
    var height = 0
    var pixelValues: [UInt16]?
    if let imageRef = imageRef {
        width = imageRef.width
        height = imageRef.height
        let bitsPerComponent = imageRef.bitsPerComponent
        let bytesPerRow = imageRef.bytesPerRow
        let totalBytes = height * width

        let colorSpace = CGColorSpaceCreateDeviceGray()
        var intensities = [UInt16](repeating: 0, count: totalBytes)

        let contextRef = CGContext(data: &intensities, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: 0)
        contextRef?.draw(imageRef, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height)))

        pixelValues = intensities
    }

    return (pixelValues ,width, height)
}

//Returns grayscale value of image at pixel (x,y)
func getGrayValue(pixelValues: [UInt16], width: Int, x: Int, y: Int) -> UInt16 {
    let i = x*width + y
    return pixelValues[i]
}

A: Your calculation

index = x * width of image +y

is off, if you are storing a 2D image in a 1D array, the correct way to access a value at [x,y] is:
index = x + width of image * y

A: Wow.   This is not good for several reasons.

*

*Why return width and height when they are passed to the code in the first place?   The calling code already has that info.

*No need to convert the entire image to greyscale.  Convert the original RGB image to a buffer in memory.  The bytes will probably be in RGBA order depending on the method used.  Then just accurately calculate the position of the first byte of the pixel.  Then bytePosition is usually ( xPos * 4 ) + ( yPos * rowWidthInBytes )
If the bytes are in RGBA sequence, then bytePosition will point to the red byte.  Add that byte to the following two bytes, then divide by 3.... you now have a grey value for that pixel.  Easy as that.


text:
Q: Laravel Connect To Wamp Phpmyadmin in windows I am new in laravel framework and I have no idea on how to view my saved data in laravel. I already edited the .env to the correct values
APP_ENV=local
APP_DEBUG=true
APP_KEY=base64:YfTvtpSEf86ZR0K+MiruFqbIrmfYzMUVT4XWtj5ovLM=
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=application
DB_USERNAME=admin
DB_PASSWORD=admin

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

am I doing something wrong? whenever i try to manipulate the database in my code it says SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES). for user "homestead"? but I already set the username into admin in my DB_USERNAME i'm so confused. Any help would be much appreciated. Thank you.

A: Fixed it :D Just needed to restart my laravel server. maybe its some caching issue.

A: Execute the following command:
composer dump-autoload -o

and also please restart your laravel application
or please check config/database.php
'mysql' => [
    'driver'    => 'mysql',
    'host'      => env('DB_HOST', 'localhost'),
    'database'  => env('DB_DATABASE', 'application'),
    'username'  => env('DB_USERNAME', 'admin'),
    'password'  => env('DB_PASSWORD', 'admin'),
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'strict'    => false,
]


text:
Q: Segregate Array base on Months I want to segregate an array based on months.
Here is a sample of an array and the output I wish to get:
Array
{
    [1] => 1:"Fruit";
    [2] => 2:"Mangoe";
    [3] => 3:"2015-2-5";
}

Array
{
    [1] => 1:"Fruit";
    [2] => 2:"Banana";
    [3] => 3:"2015-4-11";
}

Array
{
    [1] => 1:"Fruit";
    [2] => 2:"Orange";
    [3] => 3:"2015-2-10";
}

Array
{
    [1] => 1:"Fruit";
    [2] => 2:"Pineapple";
    [3] => 3:"2015-8-3";
}

Target Output:
February
Fruit:Banana
Fruit:Orange

April
Fruit:Banana

August
Fruit:Pineapple

This is my code:
<?php

    foreach ($results as $key => $value)
    {
        $value = get_object_vars($value);
        $raw_slice = explode('s:', $value['rawdata']);

        //VARIABLES
        //GET TITLE
        $title_cut = explode(':"', str_replace('";', '', $raw_slice[2]));
        $title = $title_cut['1'];

        //GET DATE
        $date_cut = explode(':"', str_replace('";', '', $raw_slice[3]));
        $date_text = $date_cut['1'];

        $month = "01";
        $year = "2015";

        $start_date = "01-".$month."-".$year;
        $start_time = strtotime($start_date);

        $end_time = strtotime("+1 month", $start_time);

        for($i=$start_time; $i<$end_time; $i+=86400)
        {
           $list[] = date('Y-m-d-D', $i);
        }

        echo "
";

        echo "
";
        echo $title.'
';
        echo "
";

        echo "
";
        echo date('F \ j,\ Y',strtotime($date_text));
        echo "
";

        echo "
";
    }

?>

A: It's a strange array and if possible, you'd do well to restructure it. Not sure how it's being built. But if that's all you have to work with, here's one way to get the output you want:
$arrays = array
(
    array
    (
        1 => '1:"Fruit"',
        2 => '2:"Mangoe"',
        3 => '3:"2015-2-5"',
    ),
    array
    (
        1 => '1:"Fruit"',
        2 => '2:"Banana"',
        3 => '3:"2015-4-11"',
    ),
    array
    (
        1 => '1:"Fruit"',
        2 => '2:"Orange"',
        3 => '3:"2015-2-10"',
    ),
    array
    (
        1 => '1:"Fruit"',
        2 => '2:"Pineapple"',
        3 => '3:"2015-8-3"',
    ),
);
$months = array();
foreach($arrays as $a)
{
    preg_match('/\"([^\"]*?)\"/', $a[1], $category);
    preg_match('/\"([^\"]*?)\"/', $a[2], $item);
    preg_match('/\"([^\"]*?)\"/', $a[3], $date);
    list($Y,$M,$D) = explode('-', str_replace('"', '', $date[0]));
    $M = str_pad($M, 2, 0, STR_PAD_LEFT);
    $D = str_pad($D, 2, 0, STR_PAD_LEFT);
    $unix = strtotime($Y.'-'.$M.'-'.$D);
    $key = date('m', $unix);
    $months[$key]['month'] = date('F', $unix);
    $months[$key]['categories'][str_replace('"', '', $category[0])][] = str_replace('"', '', $item[0]);
}
ksort($months);
echo '
';
foreach($months as $m)
{
    echo "
";
    echo $m['month'];
    echo "
";
    ksort($m['categories']);
    foreach($m['categories'] as $cat => $items)
    {
        foreach($items as $item)
        {
            echo "
";
            echo $cat.':'.$item;
            echo "
";
        }
    }
    echo '
';
}
echo '
';


text:
Q: Netty - How to implement the Fan-Out pattern is there any example that shows how to implement the fan-out pattern? basically in my Handler I want to send out multiple requests and then handle the result of those.

A: For multiple targets I believe you can use PromiseAggregator and/or PromiseCombiner. If I understand your use case correctly, then these abstractions were designed to do just that: join multiple futures/promises and await for their aggregated result. Details may differ depending on your requirements, you may want to fail if at least one promise fails or you may be fine if at least one completes. Anyway, some examples may be found in the docs or here: PromiseCombiner example.
final PromiseCombiner combiner = new PromiseCombiner(eventExecutor);
combiner.add(makeAsyncCall1());
combiner.add(makeAsyncCall2());
final DefaultPromise<Void> promise = new DefaultPromise<>(eventExecutor);
promise.addListener(new GenericFutureListener<Future<? super Void>>() {
    @Override
    public void operationComplete(Future<? super Void> future) throws Exception {
        // handle
    }
});
combiner.finish(promise);


text:
Q: What instructions can be allowed to execute or prohibited from executing in user mode? There are instructions that the CPU can never be able to execute in user mode (for example: the HLT instruction).
And there are instructions that the CPU will always be able to execute in user mode (for example: the MOV instruction).
And there are instructions that the CPU can be allowed to execute or prohibited from executing in user mode (for example: the IN and OUT instructions).
My question is: what are the other instructions (other than IN and OUT) that can be allowed to execute or prohibited from executing in user mode?

A: Originally there were three groups:

*

*instructions that can be executed at any privilege level

*instructions that are sensitive to "IOPL" (IO Privilege Level"). These are IN (and variations - byte, word, dword, string), OUT (and its variations), HLT, CLI and STI. If IOPL (in eflags) is set to 3 then these instructions can be used in user code (CPL=3); and if IOPL is set to a numerically lower value these instructions can't be used in user code.

*supervisor instructions (e.g. LGDT, WRMSR, INVD, ..., MOV to/from debug registers). These can never be executed at CPL=3.
Since then they (CPU manufacturers - Intel, AMD, VIA, ..) have added (in "approximate chronological order"):

*

*the "alignment check" feature, which disallows misaligned reads and writes at CPL=3

*the RDTSC instruction and a flag (in CR4) to disallow it at CPL=3.

*the "protected mode virtual interrupt" feature that effects the behavior of CLI and STI at CPL=3 (mostly intended for virtual8086 but not limited to that).

*a flag in an MSR that allows CPL=0 code to disable CPUID leaves > 2 (make the CPU pretend these leaves don't exist), which is something that was originally a misguided work-around ("software is soft, hardware is hard") for a bug in an old version of WindowsNT, but still hangs around 20+ years later for no sane reason at all.

*all kinds of virtualisation stuff (e.g. VMENTER, VMEXIT, ...)

*the RDTSCP instruction (access at CPL=3 still controlled by the earlier flag in CR4)

*the RDPMC instruction

*the SWAPGS instruction

*alternatives to/extensions of SWAPGS (RDFSBASE, RDGSBASE, WRFSBASE, etc)

*an extension called "UMIP" (User Mode Instruction Prevention") that (if enabled) mostly prevents user code from using instructions to find out the virtual addresses of kernel data structures (so that "KASR" is slightly less of a joke). The instructions disallowed by this are SGDT, SIDT, SLDT, SMSW and STR.

*a hidden/undocumented flag in an MSR that allows some kernels (if they're written by developers that are able to find out about it) to disable access to a few more instructions that user code should never have been able to execute (CPUID and I don't know what else).

A: There are several flags in cr4 that control the availability of specific instructions in user mode:

*

*TSD (bit 2): RDTSC and RDTSCP

*PCE (bit 8): RDPMC

*OSFXSR (bit 9)*: FXSAVE, FXRSTOR, and SSE instructions

*UMIP (bit 11): SGDT, SIDT, SLDT, SMSW, STR

*FSGSBASE (bit 16)*: RDFSBASE, RDGSBASE, WRFSBASE, WRGSBASE
Flags marked with * affect execution of the corresponding instructions in ring 0 also.


text:
Q: Can I attach NX to an existing X session? I run an NX server on my ubuntu work computer and use an NX client on my ubuntu home computer to work from home.
The problem with this set up is that I have to create a new X session whenever I do this-- I can't log into my existing locked session I have running at work.
This requires me to either log off at work before going home if I know I'm going to want to work from home, or, once I've created a new X session at home, going through in process explorer and killing trouble processes from the other X session.
So, is there a way using the NX Client to connect to an existing X session on a computer running NX server?

A: Short answer : Yes.
Longer answer : This update added support for "shadowing", which allows exactly what you are asking for.
I'm not sure if this also exists in the FreeNX server, or the NeatX version.
[Edit: Updated from answer being "no", as there is "shadowing" support in NX now.  So this "yes" depends on which version of NX is being used...]

A: You can now, simply select 'Shadow' in the Desktop dropdown in the client configuration.
Note that it doesn't play well with compositing. If you have to connect to a composited window do this:
Click System,
Resize the NX window to get the screen to update,
Preferences,
Resize
Appearance
Resize
Visual Effects
Resize
None.
Then it should work. Actually I also just discovered if you go to 'Settings' in the connection config window there is a 'Disable Composite extension' option. That might have the same effect.
It also seems to behave weirdly with dual screen (TwinView).

A: if its individual apps, xpra might do the trick.

A: *

*No one else mentioned x0vncserver which can be used to shadow any X11 session

*Xpra can shadow existing displays on MS Windows, MacOS and Linux

*NX (mentioned above) is another popular choice

Beware that shadowing an existing X11 display does little more than screenscraping and compressing the screen updates before sending them, so the performance of both NX and VNC shadowing will not be as good as native NX/VNC sessions... (which use much more advanced performance optimizations)
There is also the option of loading the vnc.so module into the X server, documentation is a bit scarce though and AFAIK you can't unload the module (whereas you can just kill nxagent/x0vncserver when not in use)

A: It isn't NX, but x11vnc can do what you're trying to do:
http://liquidat.wordpress.com/2008/11/13/short-tip-access-a-running-x-session-via-x11vnc/

A: I just always use an NX client to connect, whether at the office or home. Then one does not have this issue.


text:
Q: twitter posting from ssl to tlsv1 I am using twitter and posting from command line. The code I was using before was
loginpage=curl -s -b "cookie.txt" -c "cookie.txt" -3  -L --sslv3 -A "$uagent" -d "authenticity_token=$token&username=$username&password=$password" "https://mobile.twitter.com/session"
But now it is no longer working since twitter change sslv3 to tlsv1
I try to replace -3 --sslv3 with -1 tlsv1 but can't post any tweet. Earlier it was working fine.


text:
Q: Is possible to update the firmware of the PN532 chip? I want to know if is possible to update the firmware of the NFC chip PN532 from NXP. If it is, how can this be done?
If this isn't the appropriate Stack exchange site please move the question.

A: I searched for "firmware" in the datasheet and this word pops up in only a few locations in the datasheet.
It mentions for example that the current consumption depends on the version of the firmware. That tells me that NXP determines what firmware is used on a particular chip.
Although a micro controller is used in this chip, I do not see how the end user can make use of that uC. As far as I can determine the uC is used to control reading/writing of data and generally controlling the IC. I do not see the possibility mentioned to load your own software into the uC.
Having that option to load your own software into the uC would require flash memory which would add cost to the manufacturing of these ICs. Since NXP sells these chips cheap and in huge quantities, my bet is that they use mask ROM and not flash ROM.
Updating the contents of a mask ROM should require only one mask change so despite not being cheap the cost becomes much lower as more chips are sold with the new firmware version.
Using mask ROM will also save the cost of programming each chip before it leaves the factory as would be needed when using flash ROM.
So my answer is: No, you cannot update the firmware in this chip.

A: I would assume so. It's expensive to use masked ROM for software you might change in the future.
There are 3 pins that are NC. My money is on those being a programming interface.
However, the chip might not contain all the boost circuitry required for erasing and programming flash. Which is why it's advertised as ROM.


text:
Q: SQLite simplify union of left outer join I inherited some monster SQL queries and I would like to simplify/ shorten them as much as possible.
One of them is:
SELECT
              *
            FROM
              (
                SELECT
                  $columnsFromBothTables
                FROM
                  table_abc
                  left outer join table_xyz using profile_id
                union
                select
                  $columnsFromBothTables
                from
                  table_xyz
                  left outer join table_abc using profile_id
              )

It looks weirdly redundant.
Is there a way to simplify it to sth like?
SELECT * FROM (
    SELECT $columns FROM table_abc MAGIC_OPERATION table_xyz
)

Isn't it a FULL OUTER JOIN?
Updates:
My understanding is that both tables have M-1 relationship to "profile" table.
They do not have direct relationship to each other

A: This is similar to but not exactly a full outer join.  I would recommend this approach for the full outer join:
select $columns
from abc left join
     xyz
     on . . .
union all
select $columns
from xyz left join
     abc
     on . . .
where abc.? is null;  -- some column to validate that there is no match

Note:  This does not remove duplicates -- which your code does.  That is why this version should perform better.  But it might not do exactly what you want.


text:
Q: How to integrate the feature of third party app (django-avatar) in my app? I developed the user profile setting page. I don't know how to include the change avatar feature in the setting page ?
I use {% include avatar/add.html %} in the userprofile.html . I know it is wrong but I didn't find out any solution. Please help me.
Thank you in advance
Update: I want to change avatar feature on the same setting page. . Thanks

A: INSTALLED_APPS = (
    # ...
    'avatar',
)

just put below code in your page
Change your avatar


text:
Q: HTML - form tag bringing you to a website How would you do this with form ()?
Make a text box and a Submit button.
You type anything in the textbox and Submit will open a website in your browser with a link of: (example) test.com/TextTheyPutHere.
Basically, if I put 'lol' in the textbox, it would open a website test.com/lol.
Please help.

A: Try this:
<!DOCTYPE html>

<html>
<head>
<script>
function newDoc() {
window.location.assign("http://www.yourVeryOwnSitez.com/"+document.myForm.myDestination.value)
}
</script>
</head>

<body>
<form method="post" name="myForm">
<input type="text" name="myDestination">
<input type="button" value="Gogogo" onclick="newDoc()">
</form>
</body>
</html>

Then edit line 7 and put your particular url in the place of "www.yourVeryOwnSitez.com".


text:
Q: Quartz Arcs, Fill, Stroke and paths )
I've got to create a few custom buttons that will be on the side of a circle (like this example on the right hand side image : http://dribbble.com/shots/352571-Game-UI-Bottom-Left)
I tried to create the basic shape using this code :
CGContextSetLineWidth(context, 2.0);
CGContextAddArc(context, 200, 200, 100, -M_PI_4, M_PI + M_PI_4, 1);
CGContextAddArc(context, 200, 200, 60, M_PI + M_PI_4,-M_PI_4 , 0);
CGContextClosePath(context);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextFillPath(context);
CGContextAddArc(context, 200, 200, 100, -M_PI_4, M_PI + M_PI_4, 1);
CGContextAddArc(context, 200, 200, 60, M_PI + M_PI_4,-M_PI_4 , 0);
CGContextClosePath(context);
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextStrokePath(context);

I've never done some Core Graphics yet (only small stuff like drawing a circle and stuff...). It seems surprising tha in order to stroke the shape and pain it, I have to recreate the path.
I guess there are some much clever ways to do this right? ;)
Since I'm here, I will have to draw some gradients in this shape, just in case it complicates the whole stuff ;)
Thanks for you help

A: Check out the following functions to create a single path:
CGPathCreateMutable()
CGPathAddRect()/CGPathAddRects()
CGContextAddPath()

...and for performance, remember to cache this path if you're going to draw it multiple times!


text:
Q: how to get the full path of a page in javascript I know that var pathname = window.location.pathname; returns path only and var url      = window.location.href; returns full URL.
Now suppose i have page MyPageName.aspx in the root of my site and my site can be deployed on servers serverone, servertwo & serverthree.

*

*On Serverone, i want to display http://example.com/MyPageName.aspx

*On servertwo, i want to display http://example.net/MyPageName.aspx

*On serverthree, i want to display http://example.org/MyPageName.aspx
So how do i get the full URL path of a page in i'ts current environment with out browising to that page but knowing in advance that the page exists.
I want to display the URL some where on a master page.

A: You can use window.location.origin to return everything up to and including the .com:
var url = window.location.origin;
-> "http://example.com"

As MyPageName.aspx appears to be static, you can then just use string concatenation to append it to the end:
url += "/MyPageName.aspx";
-> "http://example.com/MyPageName.aspx"

Demo

var url = window.location.origin + "/MyPageName.aspx";
document.write(url);

A: Did you try
document.URL

read http://www.w3schools.com/jsref/prop_doc_url.asp


text:
Q: Ionic 3 exibe "App not installed. The package appears to be corrupt." Eu estou tentando instalar o apk em 2 dispositivos diferentes (Galaxy e LG), mas ambos estão exibindo "App not installed. The package appears to be corrupt.".
Antes eu estava tentando incluir o Login do Google no app, mas estava exibindo o erro 10. Após ler vários posts, atualizei alguns pacotes e alterei algumas configurações. O resultado é que não consigo mais instalar meu app.
Como estou gerando o apk:

Passo 1:
Acesso C:\Program Files (x86)\Java\jdk1.8.0_131\bin (JAVA_HOME no meu caso), e rodo:
 keytool -genkey -v -keystore platforms\android\my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000`

Passo 2:
Crio um arquivo release-signing.properties em platforms/android
 keyAlias=alias_name
 keyPassword=password
 storeFile=my-release-key.keystore
 storePassword=password`

Passo 3:
Vou para o diretório do projeto e rodo (para gerar o apk):
 cordova build android --release -- --keystore=platforms\android\my-release-key.keystore --storePassword=password --alias=alias_name --password=password`

Passo 4:
Volto em C:\Program Files (x86)\Java\jdk1.8.0_131\bin (JAVA_HOME), e rodo o comando abaixo para validar o apk:
 jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore platforms\android\my-release-key.keystore platforms\android\app\build\outputs\apk\release\app-release.apk alias_name`

Passo 5:
Copio o apk para o Samsung S8+ e LG Stylus 2, tento instalar, mas ambos exibem "App not installed. The package appears to be corrupt."
O que eu já tentei:

*

*Defini as variáveis de ambiente do sistema

*Atualizei as versões do Android Studio, do Android SDK Tools, do Cordova, do NPM e do Node.js

*Atualizei o plugin cordova-plugin-ionic-webview

*Fiz o downgrade do build.gradle para 2.3.3 (e wrapper para 3.3), mas ocorreu um erro durante o build, então voltei ao original

*Alterei os arquivos config.xml epackage.json, para que não contenham  ^ ou ~ na spec do android e cordova-android
Ionic info:
 Ionic:

    ionic (Ionic CLI)  : 4.10.2
    Ionic Framework    : ionic-angular 3.9.2
    @ionic/app-scripts : 3.2.2

 Cordova:

    cordova (Cordova CLI) : 8.1.2 (cordova-lib@8.1.1)
    Cordova Platforms     : android 7.0.0, ios 4.5.5
    Cordova Plugins       : cordova-plugin-device 2.0.2, cordova-plugin-googleplus 7.0.0, cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 4.0.0, cordova-plugin-splashscreen 5.0.2, cordova-plugin-statusbar 2.4.2, cordova-plugin-whitelist 1.3.3

 System:

    Android SDK Tools : 26.1.1
    NodeJS            : v8.4.0
    npm               : 6.8.0
    OS                : Windows 10

Outras informações:

*

*Android Studio 3.3.1

*ANDROID_HOME=C:\Users\xxxxx\AppData\Local\Android\sdk

*JAVA_HOME=C:\Program Files\java\jdk1.8.0_131

*platforms\android\app\build.gradle:
dependencies {
   classpath 'com.android.tools.build:gradle:3.0.0'
}

*platforms\android\gradle\wrapper\gradle-wrapper.properties:
distributionUrl = https\://services.gradle.org/distributions/gradle-4.1-all.zip

Emulador
Tentei ainda rodar o emulador, ionic cordova run android -l -c, mas também exibiu o seguinte erro:
Runtime Error
Unexpected Identifier
Stack
SyntaxError: Unexpected Identifier

Assim, o resultado é o mesmo, e até agora eu não sei se meu primeiro problema (erro 10 no login do Google) estaria resolvido...
EDIÇÃO 1
Tentei fazer o downgrade do Cordova para a versão 7.0.0 e 6.5.0, e android@6.4.0, mas o problema persistiu.


text:
Q: how to get results from a controller with parameters enabled This is how I get a list of staff.
public class StaffController {
    private static final Logger logger = LoggerFactory.getLogger(StaffController.class);

    @Inject
    private StaffService service;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String listAll(@Param("branchId") Integer branchId,
                      @Param("page") Integer page,
                      @Param("rowsPerPage") Integer rowsPerPage,
                      Model model,
                      HttpServletRequest request) throws Exception {
        logger.info("Staff information list page.");
        model.addAttribute("context", request.getContextPath());

        Map<String, Object> keys = new HashMap<String, Object>();
        keys.put("branchId", branchId);
        keys.put("page", page);
        keys.put("rowsPerPage", rowsPerPage);
        //List<StaffVO> list = service.listAll(1, 1, 10);
        List<StaffVO> list = service.listAll(keys);

        model.addAttribute("list", list);

        return "/staff/list";
    }
}

And then in JSP, I get the result like below:
<% List<StaffVO> list = (List<StaffVO>)request.getAttribute("list"); %>

Ok, great.
but where in earth should I pass parameters like branchId, page and rowsPerPage. So that the controller can query exactly what I want.
For now, I just ignore parameters and just query everything because branchId, page, rowsPerPage are all null.
And here's my StaffMapper:
public interface StaffMapper {

    final String SELECT_STAFF =
        "SELECT staff.id, staff_level, staff.name, cell, date_join, employment, status, allow_absence_control, branch.id as branch_id, branch.name as branch_name " +
        "FROM staff " +
        "LEFT JOIN branch " +
        "ON staff.branch_id=branch.id " +
        "WHERE branch.id=1";

    @Select(SELECT_STAFF)
    public List<StaffVO> listAll(Map<String, Object> keys) throws Exception;
}

SO, assume that now I have keys that actually has keys and values. Then, How can I insert that information into the SELECT string?
I tried WHERE branch.id = #{keys[branchId]} and many more but didn't work unfortunately.

A: If i understand you correct, you need to get data in your controller. You can achieve this by two ways:
1) @PathVariable
@RequestMapping("/foo/{bar}/{bazz}")
public String getEvent(@PathVariable Long bar,@PathVariable String bazz) {
model.addAttribute(...);
return model;
}

Url example:
hostname:port/foo/2/Hello
hostname:port/foo/3/Bye
Two last variables will be treated as path variables and can be used in controller.
2) @RequestParam
@RequestMapping(value = "/balance", method = RequestMethod.POST)
public String addBalance( @RequestParam Double bar){
...
}

Here you need to use html form, e.g.
<form name="foo" action="/balance" method="post">
Add money:
  <input type="number" name="bar" /></br>
  <input type="submit" value="Save" />
</form>

This will put variable from < input> to request parameters. Names in input and controller should be the same.
p.s. scriptlets are not the best way to get data in JSP. I believe that it's bad to mix HTML and JAVA. You should consider using JSTL.


text:
Q: Wait for QGLWidget to finish rendering I'm developing an OpenGL benchmark for a Qt application using VBOs and not glBegin/glEnd stuff.
I call the the class GLWidget (that inherits from public QGLWidget and protected QGLFunctions) from the MainWindow and I want to wait for the rendering to finish and get the value of the variable that stores the time elapsed. Problem is I don't find a suitable SIGNAL / method of waiting for the finish of a QGLWidget, so I get wrong variable values from MainWindow even if I use glFinish() at the end of the rendering.
void GLWidget::initializeGL() {
  // VBO, glGenBuffers, glBindBuffer, glBufferData stuff
}

void GLWidget::paintGL()
{
    QGLFunctions::glEnableVertexAttribArray(0);
    QGLFunctions::glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    QGLFunctions::glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,(void*)0);

    // Start Time
    startTime = clock();
    glDrawArrays(GL_TRIANGLES, 0, numVertices);
    // Wait for the rendering
    glFinish();
    // Finish Time
    finishTime = clock();
    relativeTime = finishTime - startTime;
    totalTime = (float) relativeTime / CLOCKS_PER_SEC;
    QGLFunctions::glDisableVertexAttribArray(0);
}

A: You can create your own two signals
        void startPaint() and void endPaint()
Than catch them somwhere(MainWindow maybe) and void startPaint() will start timer, and void endPaint() will stop timer and store value somewhere. Qt class QElapsedTimer should do the job.


text:
Q: How do you inject in dotnet core project in static method an IConfiguration object? I have a Redis store similar to this one. My problem is, since I am using .Net Core, on line 15, I should use configuration object that I normally inject in the constructor.
However, one cannot inject the configuration object in the static constructor, as static constructor should be parameterless in C#.
I tried adding a static method to initialise the config object, but then the constructor throws NullReferenceException because obviously the ctor is still called first, before the Init method, and it needs the config object... so what to do?
Doesn't seem like a good workaround.

A: Instead of doing all that work with statics and trying to get it to work (hint: it'd never work with a static constructor), I'd suggest you to move to newer patterns and use DI correctly.
If you don't really need the lazyness, this is as simple as injecting IConnectionMultiplexer:
services.AddScoped<IConnectionMultiplexer>(s => ConnectionMultiplexer.Connect(configuration["someSettings"]));

If you do need the lazyness:
// public interface IRedisStore { IConnectionMultiplexer RedisConnection { get; } }
public class RedisStore : IRedisStore
{
    private readonly Lazy<ConnectionMultiplexer> LazyConnection;

    public RedisStore(IConfiguration configuration)
    {
        var configurationOptions = new ConfigurationOptions
        {
            EndPoints = { configuration["someSettings"] }
        };

        LazyConnection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(configurationOptions));
    }

    public IConnectionMultiplexer RedisConnection => LazyConnection.Value;
}

and you'd inject it with:
services.AddScoped<IRedisStore, RedisStore>());


text:
Q: How can I move a object twice in a IEnumerator function I want to move my object from one place to another at certain time, after a while i want to move it to another place. can I do it in one IEnumerator function?
Here is my code, btw, the start here is the start trigger, which works fine.
void Start()
{
    StartCoroutine(Begin());
}

IEnumerator Begin()
{
    while (!start)
    {
        yield return null;
    }
    StartCoroutine(goDown());
}

IEnumerator goDown()
{
    yield return new WaitForSeconds(62);

    while ( transform.position.x < -1.4f
        || transform.position.y > -1.3f
        || transform.position.z < 9.33f)
    {

        if(transform.position.x < -1.4f)
        {
            transform.position = new Vector3(transform.position.x + Time.deltaTime * 0.6f,
                transform.position.y, transform.position.z);
        }

        if (transform.position.y > 1.3f)
        {
            transform.position = new Vector3(transform.position.x,
                transform.position.y - Time.deltaTime * 0.6f,
                transform.position.z);
        }

        if (transform.position.z < 9.33f)
        {
            transform.position = new Vector3(transform.position.x ,
                transform.position.y,
                transform.position.z + Time.deltaTime * 0.6f);
        }

        yield return null;
    }

    yield return new WaitForSeconds(25);

    while (transform.position.x > -8.79f
        || transform.position.y < 1.67f
        || transform.position.z < 9.86f)
    {

        if (transform.position.x > -8.79f)
        {
            transform.position = new Vector3(transform.position.x - Time.deltaTime * 0.6f, transform.position.y, transform.position.z);
        }

        if (transform.position.y < 1.67f)
        {
            transform.position = new Vector3(transform.position.x, transform.position.y + Time.deltaTime * 0.6f, transform.position.z);
        }

        if (transform.position.z < 9.86f)
        {
            transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z - Time.deltaTime * 0.6f);
        }

        yield return null;
    }
}

I did that, the object can only move to the first place but cannot mover to the next. I don't know whats wrong with it?

A: It's because your while loop and your if condition don't match:
    || transform.position.y > -1.3f

is different than
    if (transform.position.y > 1.3f)

So your coroutine gets stuck in the first loop because the transform's y is stuck between -1.3 and 1.3.
As a sidenode, you can assign the transform's current goal to a variable and use Vector3.MoveTowards to avoid this sort of copy-paste error:
IEnumerator goDown()
{
    yield return new WaitForSeconds(62);

    Vector3 goal = new Vector3(-1.4f, -1.3f, 9.33f);

    while (transform.position != goal)
    {
        transform.position = Vector3.MoveTowards(transform.position, goal,
                                                 1.03f * Time.deltaTime);
        yield return null;
    }

    yield return new WaitForSeconds(25);

    goal = new Vector3(-8.79f, 1.67f, 9.86f);

    while (transform.position != goal)
    {
        transform.position = Vector3.MoveTowards(transform.position, goal,
                                                 1.03f * Time.deltaTime);
        yield return null;
    }
}


text:
Q: RecyclerView insert / remove animations When you watch carefully, the insert animation in a RecyclerView works in 2 steps :
1) White space expands to make room for the new item
2) The item is animated in
Same thing for removal, reverse order
Examples :
https://github.com/wasabeef/recyclerview-animators
http://www.grokkingandroid.com/first-glance-androids-recyclerview/
The second step can be customized easily with the ItemAnimator class, but I cannot find any information on the first step. It happens to be very ugly with my layout (continuous color on the side).
LayoutAnimationController seems like a possible candidate to manage the first step, but adding a new one does not change anything, and following it with logs in setLayoutAnimationListener stays silent.
I cannot even disable this step, which would allow me to manage the animation manually in onBindViewHolder.
Actually sometimes the first step does not seem to fire, but I cannot explain why. I manage all the operations with notifyItem*, no notifyDataSetChanged.


text:
Q: Hyperlink is not clickable on mobile, works fine on deskop I'm trying to replace a caption in nextgen-gallery (WordPress plugin) lightbox with a hyperlink.
Hyperlink works just fine on desktop but unclickable on mobile.
Some element is blocking it in responsive mode but I can't seem to find it.
I've tried increasing the z-index, making entire div clickable by adding .attr('onclick',"location.href... Even tried image clickable.
All of above works in desktop mode and not in responsive. Could use a couple fresh pair of eyes before I give up.
link: http://cnc-kamieniarstwo.pl/index.php/galerias/
Original html:

DSC_0366small

Modified html, link is hidden behind some element in responsive, I can't seem to find:

Ask a Question

Thank you

A: Add this tag and check 'javascript: void(0)'


text:
Q: What set ebooks or evergreen online resources is sufficent for self-study of the topics in an undergraduate math program? What set ebooks or evergreen online resources is sufficent for self-study of the topics in an undergraduate math program?
There are many lists on stack exchange, but they invariably include physical books I can't get shipped to this region.
MIT OCW is fantastic, but it also works with the assumption that learners are in the US and can buy the physical text books the previous MIT classes used.
Edx and Coursera are also fine resources but much of their content is time-boxed and subject coverage is very poor past the freshman/sophomore level.
What ebooks or other set of resources will take a self-paced online learner through a full BA curriculum?


text:
Q: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock' (2) - XAMPP Mac OSX How to fix MySQL not starting in XAMPP for Mac OSX?

A: This seems like mysql isn't running at all. Try this in terminal and try again :
sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start

A: I have encountered this issue multiple times on OSX I believe it is something to do with an error during installation.
There are a few potential points of failure:

*

*The first is checking your configuration files point to the correct location of your socket file. To check this Open your /etc/my.cnf file and check/edit these two configurations.
[mysqld] socket=/var/mysql/mysql.sock
[client] socket=/var/mysql/mysql.sock

*If this doesn't work it could also be that the correct access
privileges have not been granted to the files during installation.
You can try to change the ownership of the files like so:
sudo chown -R _mysql:_mysql /usr/local/var/mysql

*Another potential point of failure is that an error file has become
inaccessible or corrupted so its worth stopping your server deleting
it and then starting your server again.
Check in directory /usr/local/var/mysql for a file which is named
(your-computer-name).local.err if it is owned my _mysql (or similar)
delete it and then try start the server again with sudo /usr/local/mysql/bin/mysqld_safe
Hope this helps.

A: Got it working by reinstalling XAMPP like so:
1. Uninstall XAMPP using the unistaller found at /Applications/XAMPP/uninstall.app,
2. Delete the leftovers from  /Applications/XAMPP/,
(backup /Applications/XAMPP/xamppfiles/htdocs and databases if necessary) then
3. Install XAMPP using installer again.
Afterwards, the missing mysql.sock and proper links to it are back to normal and $ mysql works.

A: In MacOS:
Step 1:
Go to your Finder and edit the file as the following path below. /Applications/XAMPP/xamppfiles/etc/my.cnf
Step 2:
Open the file and find the [mysqld] section add one line as following innodb_force_recovery = 1 ,and save.
Step 3: Run command in your Terminal
sudo /Applications/XAMPP/bin/mysql.server start
Wait until everything is OK.
Step 4: Edit the my.cnf again and remove the line you just added innodb_force_recovery = 1 ,and save.
Step 5: Stop for restart sudo /Applications/XAMPP/bin/mysql.server stop
 Wait until everything is OK.
Remind that if you didn't passed this step your all tables will be read only.
Step 6: Open XAMPP Manager and click "Start" button to start MySQL Database again The progressing status will show "Running".
NOTE: This problem will be faced again after you restart your Mac OS X. So, you have to repeat these steps again. Remember that this is the workaround solution.
source


text:
Q: Rescaling 2D numpy array as Dense representation I have a numpy array . I want rescale the elements in the array, so that the smallest number in array is represented by 1, and largest number in array is represented by the number of unique elements in array.
For example
A=[ [2,8,8],[3,4,5] ]

would become
[ [1,5,5],[2,3,4] ]

A: Use np.unique with its return_inverse param -
np.unique(A, return_inverse=1)[1].reshape(A.shape)+1

Sample run -
In [10]: A
Out[10]:
array([[2, 8, 8],
       [3, 4, 5]])

In [11]: np.unique(A, return_inverse=1)[1].reshape(A.shape)+1
Out[11]:
array([[1, 5, 5],
       [2, 3, 4]])

A: If you're not opposed to using scipy, you could use rankdata, with method='dense' (judging by the tags on your question):
from scipy.stats import rankdata

rankdata(A, 'dense').reshape(A.shape)

array([[1, 5, 5],
       [2, 3, 4]])

Note that in your case, method='min' would achieve the same results, see linked documentation for more details


text:
Q: Laravel9: route parameter always missing in validation I am using Laravel v9.2.1 + Laravel Sanctum v2.14.1
I got a route
DELETE /api/v1/auth/tokens/{token}

for example (the token is an uuid)
DELETE http://example.com/api/v1/auth/tokens/5fcfa274-81d8-4e9f-8feb-207db77531af

And I am sure it works as expected via php artisan route:list

Before handling by the Controller, it should be validated by a FormRequest
app/Http/Controllers/V1/Auth/TokensController.php
namespace App\Http\Controllers\V1\Auth;

use App\Http\Requests\V1\Auth\Tokens\{
    DestroyRequest,
};

class TokensController extends Controller
{
    public function destroy(DestroyRequest $request) {
        $request->user()->tokens()->where('id', $request->token)->first()->delete();
        return response()->noContent();
    }
}

app/Http/Requests/V1/Auth/Tokens/DestroyRequest.php
class DestroyRequest extends FormRequest
{
    public function rules()
    {
        return [
            'token' => [
                'required',
                'string',
                'regex:/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
                Rule::exists('personal_access_tokens')->where(function ($query) {
                    return $query->where('tokenable_id', $this->user()->id);
                }),
            ]
        ];
    }
}

But what I only got is The token field is required
I had already pass the token, why the 'required' rule still working?

What I tried
Only if I pass the token parameter like below, it will work
DELETE /api/auth/tokens/something?token=test_regex_is_working

I try to dd($this->token) in app/Http/Requests/V1/Auth/Tokens/DestroyRequest.php, it works as expected.

A: You might need to add the following in the FormRequest class:
protected function prepareForValidation()
    {
        $this->merge(['token' => $this->route('token')]);
    }

I believe URL parameters are not included in the request directly.

A: i might try going about it differently as the token isn't really user input
In the routes file:
Route::delete('/api/v1/auth/tokens/{token}', [TokensController::class, 'destroy'])->whereUuid('token');

In the FormRequest something maybe like this:
public function authorize()
{
    return DB::table('personal_access_tokens')
        ->where('tokenable_id', Auth::id())
        ->where('token', $this->route('token'))
        ->exists()
}

A: With the help of both @RawSlugs and @Aaron T, thank them a lot!
app/Http/Requests/V1/Auth/Tokens/DestroyRequest.php
protected function prepareForValidation() {
    $this->merge(['token' => $this->route('token')]);
}

public function authorize() {
    return $this->user()->tokens()->where('id', $this->token)->exists();
}

// But since the authorize() will validate the request before rules(), this will be useless
public function rules() {
    return [
        'token' => [
            'required',
            'string',
            'regex:/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
        ]
    ];
}

I'm using Laravel Sanctum.


text:
Q: How to remove background color on hover of bar in highcharts I am using highcharts. Version: 9.1.1
I am displaying bar chart. When I hover on bars it display background color but I don't want that background color.
As we can see in below image I don't want that grey color by hover on green bar.

I applied this solution but it disable tooltip also. but I need tooltip on hover.
plotOptions: {
       series: {
          enableMouseTracking: false
       }
}

Thanks

A: I would check to see the classes used for these charts.
Once you found the class of your charts you can modify them in the .css file.

Let's say you have something like this but the span in your case would be the chart.
In this case in the.css file you have to do something like this:
.class1 .class2 .class3:hover {
    background: none;
}

Using the browser tools you can also simulate(force) a hover and do there some changes.

A: By taking reference of @Robart. I inspect chart and modified class .highcharts-crosshair-category style
I applied below style
.highcharts-crosshair-category {
   display: none !important;
   visibility: hidden !important;
 }

A: Make this change in chartOption: crosshair: false


text:
Q: Gaussian blur with svg and css over image slider Apparently there is no native way to have a gaussian blur which affects non-absolute positioned images, svg is a good choice in this case. But for some reason it doesn't work here.
I want to have a gaussian blur over the slider like you can see here: https://i.imgur.com/8dXlHbP.jpg
The div with class blur is the one I want the svg filter to be applied, here is my code:

/*SLIDER AMA START*/
.slider_ama_maincontainer{width:100%; height:92vh; position:relative; overflow:hidden; display:flex;}
.slider_ama_nav_container{width:100%; height:75px;  z-index:99999; background-color:rgba(0,0,0,0.5); position:absolute; bottom:0px; left:0px; display:flex; align-items:center;}
.slider_ama_nav_links_container{width:auto; height:auto; display:flex; align-items:center; margin-left:auto;}
.slider_ama_nav_link{font-size:18px; font-weight:400; display:flex; align-items:center;  text-shadow:2px 2px 5px rgba(0,0,0,0.6);  height:100%; transition:all 300ms ease; padding:0px 25px; background-color:none; color:rgba(255,255,255,1.0); margin:0px 0px;}
.slider_ama_nav_link:hover{background-color:var(--web_primary_color);}
.slider_ama_prev{position:absolute; width:auto; height:auto;  top:50%; border-radius:0px; transform:translateY(-50%); left:5px; z-index:9999; display:flex; background-color:none;}
.slider_ama_next{position:absolute; width:auto; height:auto; top:50%; border-radius:0px; transform:translateY(-50%); right:5px; z-index:9999; display:flex; background-color:none;}
.slider_ama_prev .fa{font-size:20px; color:rgba(255,255,255,0.8); margin:auto;}
.slider_ama_next .fa{font-size:20px; color:rgba(255,255,255,0.8); margin:auto;}
.slider_ama_navigation_container{width:auto; height:auto; display:flex; align-items:center; border-radius:5px; justify-content:center; position:absolute; background-color:rgba(0,0,0,0.6); padding:10px 25px; bottom:90px; right:25px; z-index:9999;}
.slider_ama_items_container{width:100%; height:100%; position:relative; overflow:hidden; background-color:black;}
.slider_ama_item{width:100%; height:100%; position:absolute; top:0px; left:0px;}
.slider_ama_gradient_overlay{width:100%; height:100%; z-index:999; position:absolute; top:0px; left:0px;}
.slider_ama_image{width:100%; height:100%;  background-size:cover; position:relative; background-position:center; z-index:998;}
.slider_ama_text_container{min-width:40%; height:auto; padding:30px; display:flex;  flex-direction:column; border-radius:5px; z-index:9999; position:absolute; background-color:none;}
.slider_ama_text_title{font-size:35px; color:rgba(255,255,255,0.8); margin-bottom:15px; font-weight:400; border-radius:5px; padding:15px; background-color:rgba(0,0,0,0.6); text-shadow:2px 4px 8px rgba(0,0,0,0.6);}
.slider_ama_text_description{font-size:25px; color:rgba(255,255,255,0.8); margin-bottom:15px; font-weight:400; border-radius:5px; padding:15px; background-color:rgba(0,0,0,0.6); text-shadow:2px 4px 8px rgba(0,0,0,0.6);}
.slider_ama_text_link{font-size:20px; color:rgba(255,255,255,0.8); margin-bottom:15px; align-self:center; font-weight:400; border-radius:5px; padding:15px; background-color:var(--web_primary_color); text-shadow:2px 4px 8px rgba(0,0,0,0.6);}
.prev{transition:all 1000ms ease; opacity:1;}
.next{transition:all 1000ms ease; opacity:1;}
.container:hover .prev{opacity:1;}
.container:hover .next{opacity:1;}
.slider_active{display:flex; opacity:1;}
.slider_active_dot{background-color:white;}
.dot{width:15px; height:15px;  border-radius:50%; background-color:rgba(255,255,255,0.8); transition: all 2000ms ease; margin:0px 10px; cursor:pointer;}
/*SLIDER AMA END*/
.slider_ama_top_banner{width:100%; height:150px; top:0px; outline:1px solid red; left:0px; display:flex; position:absolute; left:0px; bottom:0px; z-index:99999;}

.blur {
        filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius='3');
        -webkit-filter: url(#blur-filter);
        filter: url(#blur-filter);
        -webkit-filter: blur(3px);
        filter: blur(3px);
    }

       {{ Config::get('globals.slider_title_1') }}
       {{ Config::get('globals.slider_description_1') }}
    Interesting link

          Principal
    Menu
    Horario
    Localización
    Contactar
    Reseñas

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
        <filter id="blur-filter">
            <feGaussianBlur stdDeviation="3"></feGaussianBlur>
        </filter>
    </defs>
</svg>


text:
Q: Why does string not exist? /*
    Hello World example made by Aurelio Mannara for libctru
    This code was modified for the last time on: 12/12/2014 21:00 UTC+1
*/

#include <3ds.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
    gfxInitDefault();

    char player[1024] = "\x1b[";
    int tesx = 1;
    char tesxx = tesx + '0';
    char ot[] = ";";
    char oty[] = "H0";
    int test = 3;
    char testt = test + '0';
    //Initialize console on top screen. Using NULL as the second argument tells the console library to use the internal console structure as current one
    consoleInit(GFX_TOP, NULL);
    strcat(player, tesxx);
    strcat(player, ot);
    strcat(player, testt);
    strcat(player, oty);
    //Move the cursor to row 15 and column 19 and then prints "Hello World!"
    //To move the cursor you have to print "\x1b[r;cH", where r and c are respectively
    //the row and column where you want your cursor to move
    //The top screen has 30 rows and 50 columns
    //The bottom screen has 30 rows and 40 columns
    printf(player);

    // Main loop
    while (aptMainLoop())
    {
        //Scan all the inputs. This should be done once for each frame
        hidScanInput();

        //hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
        u32 kDown = hidKeysDown();

        if (kDown & KEY_START) break; // break in order to return to hbmenu

        // Flush and swap framebuffers
        gfxFlushBuffers();
        gfxSwapBuffers();

        //Wait for VBlank
        gspWaitForVBlank();
    }

    gfxExit();
    return 0;
}

why am I getting this error. I am working in C and I'm making a game for the 3ds and I want to be able to control the placement of my player char by using my int variables tesx and test. I don't understand why my offset is 0 and why its going off bounds.
C:/Users/Jeremy/Desktop/gaame/source/main.c:24:9: warning: 'strcat' offset 0 is out of the bounds [0, 0] [-Warray-bounds]
   24 |         strcat(player, testt);
      |         ^~~~~~~~~~~~~~~~~~~~~
C:/Users/Jeremy/Desktop/gaame/source/main.c:22:9: warning: '__builtin_stpcpy' offset 0 is out of the bounds [0, 0] [-Warray-bounds]
   22 |         strcat(player, tesxx);
      |         ^~~~~~~~~~~~~~~~~~~~~```

A: The header <string> and the class std::string defined in that header are part of the C++ standard library. The .c suffix of the file main.c implies that it is written in the C language. It appears that you are attempting to use C++ features in the C language. This doesn't work because they are separate languages. You cannot use C++ features in C.


text:
Q: Issue on custom loss function with Keras with TensorFlow backend I'm trying to define a loss function of a three-class classification problem as the following:
def func_loss(y_true, y_pred):
    return -K.mean(K.prod(K.cast(K.argmax(y_pred, axis=1), K.floatx()) - 1.0, K.cast(K.argmax(y_true, axis=1), K.floatx()) - 1.0))

My y looks like this:
[[1,0,0], [0,1,0], [1,0,0], [0,0,1], ...]
Intuitively my three-class label is a one-hot encoding of classes "-1", "0" and "+1". I want to maximize the correct labeling of "+/-1", minimize the wrong labeling of "+/-1" and ignore all "0" labels whether they are correct or not.
When I compile the model with this loss function, this is what I get:
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 547, in compile
**kwargs)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 622, in compile
sample_weight, mask)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 324, in weighted
score_array = fn(y_true, y_pred)
File "", line 2, in func_loss
File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 464, in prod
axis = _normalize_axis(axis, ndim(x))
File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 435, in _normalize_axis
if axis is not None and axis < 0:
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 547, in nonzero
raise TypeError("Using a tf.Tensor as a Python bool is not allowed. "
TypeError: Using a tf.Tensor as a Python bool is not allowed. Use if t is not None: instead of if t: to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

I've been trying around little tweaks with this loss function but all of them results in some error when I compile the model. I think I may have some basic misunderstanding of how this thing works. Can someone help?

Edit:
the new loss function:
def func_loss(y_true, y_pred):
    return -K.mean((K.cast(K.argmax(y_pred, axis=1), K.floatx()) - 1.0 )* (K.cast(K.argmax(y_true, axis=1), K.floatx()) - 1.0))

A: I was responding to you on the Tensorflow Github, as well.
You have edited the loss function, but you are actually getting a slightly different error now.
Before, the error was occurring the K.mean
File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 490, in mean
axis = _normalize_axis(axis, ndim(x))

Now, as you can see, it is occurring in K.prod
File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 464, in prod
axis = _normalize_axis(axis, ndim(x))

However, the cause is still the same: K.mean and K.prod each take one Tensor, so the second Tensor you are passing is being treated as the axis argument.


text:
Q: Include module path phpunit I have a problem including my module for my unit test, I have tried some things but nothings works
I have a directory src with my module and a directory test with bootstrap.php,phpunit.xml and my tests
Using set_include_path:
set_include_path(implode(PATH_SEPARATOR, array(
    '.',
    __DIR__ . '/path/to/mymodule',
    get_include_path()
)));

adding with loader:
$loader->add('mymodule', '/path/to/mymodule');

And when I use get_include_path() I can see the path to my module but in my test he can't find classes from my module


text:
Q: Should a component adapter wrap just the component or should it also wrap  Best concept for wrapping react-final-form components
Background
I'm using react-native and will probably start using react-final-form as soon as I have wrapped my head around it. I will build a component library based on react-native-paper.
All examples I've seen on wrapping 3:rd party components for use as react-final-form fields (i.e. <Field>), does not wrap the actual field component. Instead the wrapped component is injected via the component property of the Field component.
If I'm doing all the work wrapping the components, why not go all the way? Since I haven't found any examples of the "complete wrapping", I'm kind of worried that it's not a good idea.
Both solutions seems to work fine, btw. The code below is psuedo:ish.
Only wrapping the component
export default function App() {
  const CheckboxAdapter = ({input: {onChange, value}, meta}) => (
    <Checkbox
      status={value}
      onPress={() => {
        onChange(value === 'checked' ? 'unchecked' : 'checked');
      }}
      errorText={meta.touched ? meta.error : ''}
    />
  );

  return (
    <Form
      ..
      render={({handleSubmit}) => {
        return (
          ..
           <Field
             name="myFieldname"
             component={CheckboxAdapter}
           />
        )
      }
    />
  )
}

Wrapping the component inside of the <Field> component
export default function App() {
  const MyCheckbox = ({name}) => (
    <Field
      name={name}
      component={({input: {onChange, value}, meta, children, ...rest}) => (
        <Checkbox
          status={value}
          onPress={() => {
            onChange(value === 'checked' ? 'unchecked' : 'checked');
          }}
          errorText={meta.touched ? meta.error : ''}
        />
      )};
    />
  );

  return (
    <Form
      ..
      render={({handleSubmit}) => {
        return (
          ..
           <MyCheckbox
             name="myFieldname"
           />
        )
      }
    />
  )
}

A: Not much interest in this question. I ended up wrapping the <Field>as well. This gives much more readable form code.
import React from 'react';
import TextInput from '../components/TextInput';
import {Field} from 'react-final-form';

const TextInputAdapter = ({input, meta, ...rest}) => {
  const onChangeText = value => {
    input.onChange(value);
  };

  return (
    <TextInput
      {...input}
      {...rest}
      onChangeText={onChangeText}
      errorText={meta.touched ? meta.error : ''}
    />
  );
};

const TextInputField = ({...rest}) => {
  return <Field component={TextInputAdapter} {...rest} />;
};

export default TextInputField;


text:
Q: Insert Blank if Section ends on ODD page Word Macro What I have to achieve:
There are two types of data in my word document, "Summary" and "Royalty", can have multiple of these two section in one document. but always in same sequence "Summary -> Royalty -> Summary -> Royalty"

*

*I have to add a blank page after Every Summary page. that will always be of one page max.

*For Royalty, If the Royalty Section Starts page number 2 and ends on 4 means total count of the pages is 3, in this case i have to add a blank page after this.

Code Written till now is below:
Sub Add_Page_After_Summary()
'
' Add_Page_After_Summary Macro

' Add_Page_After_Summary
'
' Sample Code
ActiveDocument.Range.Select
Do

With Selection.Find
        .Text = "S U M M A R Y             "
        .Execute
End With

    If Selection.Find.Found Then

        Selection.GoTo What:=wdGoToBookmark, Name:="\Page"
        Selection.MoveRight Unit:=wdCharacter, Count:=1
        Selection.MoveLeft Unit:=wdCharacter, Count:=1
        Selection.InsertBreak Type:=wdPageBreak

    Else: GoTo nxt

    End If
Loop

nxt:

ActiveDocument.Range.Select

Do

With Selection.Find
        .Text = "R O Y A L T Y             "
        .Execute
End With

    If Selection.Find.Found Then
        Dim startpage As Integer
        Dim endpage As Integer
        startpage = Selection.Information(wdActiveEndPageNumber)
        Selection.GoTo What:=wdGoToBookmark, Name:="\Section"
        endpage = Selection.Information(wdActiveEndPageNumber)

        Dim difference As Integer
        difference = endpage - startpage

        If difference Mod 2 > 0 Then
            Selection.GoTo What:=wdGoToBookmark, Name:="\Section"
            Selection.MoveRight Unit:=wdCharacter, Count:=1
            Selection.MoveLeft Unit:=wdCharacter, Count:=1
            Selection.InsertBreak Type:=wdPageBreak
        End If

    Else: Exit Sub

    End If
Loop

End Sub

My current code is doing as below: it checks the starting of Royalty Section and it fetchs the ending of the royalty section that occurs in last of document, that is issue, i want to get the current Royalty Section. Please help.

A: If I have understood you correctly it sounds as though you want each section to begin on an odd page. If that is correct then adding an Odd Page Section Break before each Summary or Royalty heading should do the trick. This forces a blank page to be added as required when the document is printed or saved as a pdf.
Sub Test()
  InsertSectionBreaks "S U M M A R Y             "
  InsertSectionBreaks "R O Y A L T Y             "
End Sub

Sub InsertSectionBreaks(FindText As String)
  Dim FindRange As Word.Range, SectionRange As Word.Range
  Dim Found As Boolean

  Set FindRange = ActiveDocument.Content

  ' Find next section based on text, insert odd page section break just before
  FindRange.Find.ClearFormatting
  With FindRange.Find
    .Text = FindText
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    Found = .Execute
  End With

  Do While Found
    'avoid adding a section break at beginning of document
    If FindRange.Information(wdActiveEndAdjustedPageNumber) > 1 Then
      Set SectionRange = FindRange.Duplicate
      With SectionRange
        .Expand wdParagraph
        .Collapse wdCollapseStart
        .InsertBreak Type:=wdSectionBreakOddPage
      End With
    End If
    FindRange.Collapse wdCollapseEnd
    Found = FindRange.Find.Execute
  Loop
End Sub


text:
Q: The expandable list view is not expanding the list when clicked. I tried to set the clickable but still clicking on list doesn't expand anything I used an expandable list view in the main layout and then used other two layout. The list_parent includes textfield, so clicking on that textfield it should expand to show the third layout which is the list_child and it also contain a text view.
But the problem is that whenever I click on those texts on the expandable list view in activity_main it doesn't expand. I also tried to set the clickable as true in activity_main and added android:descendantFocusability="blocksDescendants" in the ExpandableListView but it's still not expanding on click.
MainActivity.java
    package com.calcounterapplication.demoexlist;

    import androidx.appcompat.app.AppCompatActivity;

    import android.os.Bundle;
    import android.view.View;
    import android.widget.ExpandableListAdapter;
    import android.widget.ExpandableListView;
    import android.widget.ListView;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    public class MainActivity extends AppCompatActivity {

    ExpandableListView expandableListView;
    List<String> langs;
    Map<String, List<String>> topics;
    ExpandableListAdapter listAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         expandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
         fillData();

         listAdapter = new MyExListAdapter(this,langs,topics);
         expandableListView.setAdapter(listAdapter);
    }

    public void fillData()
    {
        langs = new ArrayList<>();
        topics = new HashMap<>();

        langs.add("Java");
        langs.add("C");

        List<String> java = new ArrayList<>();
        List<String> c = new ArrayList<>();

        java.add("Super");
        java.add("Encapsulation");
        java.add("Methods");

        c.add("Procedure");
        c.add("Pointers");
        c.add("Array");

        topics.put(langs.get(0),java);
        topics.put(langs.get(1),c);

    }
}

MyExListAdapter.java
package com.calcounterapplication.demoexlist;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import java.util.List;
import java.util.Map;

public class MyExListAdapter extends BaseExpandableListAdapter
{
Context context;
List<String> langs;
Map<String, List<String>> topics;

public MyExListAdapter(Context context, List<String> langs, Map<String, List<String>> topics) {
this.context = context;
this.langs = langs;
this.topics = topics;
}

@Override
public int getGroupCount() {
return langs.size();
}

@Override
public int getChildrenCount(int groupPosition) {
return topics.get(langs.get(groupPosition)).size();
}

@Override
public Object getGroup(int groupPosition) {
return langs.get(groupPosition);
}

@Override
public Object getChild(int groupPosition, int childPosition) {
return topics.get(langs.get(groupPosition)).get(childPosition);
}

@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}

@Override
public boolean hasStableIds() {
return false;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)                     {

String lang = (String) getGroup(groupPosition);

if(convertView == null)
{
    LayoutInflater inflater = (LayoutInflater)     context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.list_parent,null);
}

TextView txtParent = (TextView) convertView.findViewById(R.id.txtParent);
txtParent.setText(lang);

return convertView;
}

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View     convertView, ViewGroup parent) {

String topic = (String) getChild(groupPosition,childPosition);

if(convertView == null)
{
    LayoutInflater inflater = (LayoutInflater)     context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.list_child,null);
}

TextView txtChild = (TextView) convertView.findViewById(R.id.txtChild);
txtChild.setText(topic);

return convertView;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="false"
tools:context=".MainActivity">

<ExpandableListView
android:id="@+id/expandableListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" />

</RelativeLayout>

list_parent.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/txtParent"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:text="Large Text" />
    </LinearLayout>

list_child.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Name"
        android:id="@+id/txtChild"
        android:layout_gravity="center" />
    </LinearLayout>


text:
Q: Ansible - How to skip registering a variable if the when condition is not met -  shell: "echo 'hi'"
   register: output
-  shell: "ps -ef"
   register: output
   when: output.stdout =="hello"
 - debug: var=output

The final output variable is defined as below:
TASK [Display output] **********************************************************

    ok: [localhost] =>
{
    "output":
   {
        "changed": false,
        "skip_reason": "Conditional check failed",
        "skipped": true
    }
}

Even though the task 2 is skipped, the variable gets registered. How can I skip the register if the condition is not met?

A: Register both outcomes as output1 and output2. Use 'set_fact' to set a new variable 'output' according to your condition.
- shell: "echo 'hi'"
  register: output1
- shell: "ps -ef"
  register: output2
- set_fact:
    output: "{{ output2 if output2.stdout =='hello' | default(output1)}}"
- debug: var=output

A: Q: "How can I skip the register if the condition is not met?"
A: You can't. Quoting from Registering variables:

"Note: If a task fails or is skipped, the variable still is registered with a failure or skipped status, the only way to avoid registering a variable is using tags."


text:
Q: How do i deserialize a Jsonp response into splited string var responseData = await response.Content.ReadAsStringAsync();
var msg = JsonConvert.DeserializeObject<string>(responseData);
string[] result = msg.Split(',');
string statuscode = result[0];
string RRR = result[1];
string status = result[2];

The code above shows my response after sending a request to an API with a responseData as jsonp ({"statuscode":"025","RRR":"260007663696","status":"Payment Reference generated"})
When i ran the code, i got an error message complaining about var msg = JsonConvert.DeserializeObject<string>(responseData);
How do i go about converting my jsonp response into splitted string values?

A: Your JSON payload represents an object with 3 properties.  I recommend making a class that represents this object so you can serialize/deserialize:
public class SomeObject  //Rename to something more fitting
{
    public string StatusCode {get;set;}
    public string RRR {get;set;}
    public string Status {get;set;}
}

Then when you deseralize, use this new class as the generic parameter (not string like you are currently doing):
var someObj = JsonConvert.DeserializeObject<SomeObject>(json);

Now you can access the properties like you would any other instance:
Console.WriteLine(someObj.Status);
// etc, etc

Fiddle here

A: If you aren't creating a class to deserialize your JSON, you can convert your JSON to a dynamic object and access the properties freely:
dynamic result = JObject.Parse(responseData);
string statuscode = result.statuscode;
string RRR = result.RRR;
string status = result.status;

A: You can use Regex to convert your JSONP to JSON, by stripping the outer function away and extracting only the JSON inside the brackets:
var jsonp = "jsonp({ \"statuscode\":\"025\",\"RRR\":\"260007663696\",\"status\":\"Payment Reference generated\"})";
var jsonMatch = Regex.Match(jsonp, @"\((?<json>.*)\)");
var json = jsonMatch.Groups["json"].Value;

After that, you can deserialize using your preferred method with the JSON.Net library. Here's one way using the Newtonsoft.Json.Linq namespace:
var token = JToken.Parse(json);
var status = token["status"].Value<string>();
var statusCode = token["statuscode"].Value<string>();
var rr = token["RRR"].Value<string>();


text:
Q: What determines the frequency of a soundwave? The frequency of a wave comes from the rate at which the disturbance at the source takes place. My question is, what parameters (on the guitar for example) determine that one string delivers a low pitch sound and that another delivers a high pitch (thus, frequency) one?
And if for example, i am hitting a table with the same intensity, but with different frequencies, say one time with 1hit/second and the other time with 5hits/second, should i notice a different of pitch?

A: The velocity of propagation of a wave in a string ( v ) is proportional to the square root of the force of tension of the string ( T ) and inversely proportional to the square root of the linear density ( $\mu$ ) of the string:
$$ v=(T/\mu)^{1/2} $$
Once the velocity of propagation is known the fundamental harmonic frequency is given by:
$$ f=(v/(2L))=(1/(2L))(T/\mu)^{1/2} $$
where T is the tension,  $\mu$ is the linear density (that is, the mass per unit length), and  L is the length of the string.
You can see that the frequency is not a function of the plucking force amplitude.  It is a function of the tension, the length, and the linear mass density.
See:  https://en.wikipedia.org/wiki/String_vibration

A: This is a complex question. The pure vibration of a string at a single frequency takes on a sine wave pattern. The plucking of a string deforms the string in a non-sine shape, so the disturbance is a linear combination of sine and cosine (a $\pi/2$ phase shift of sine) of multiple frequencies which are determined by properties of the string. The string acts as a filter for the plucking so the string only vibrates with certain frequencies. The sound wave produced in the air will correspond to the frequencies of the wave on the string.
On the other hand, consider a loudspeaker to which an electrical sine wave voltage is applied. The speaker will push and pull at the frequency of the voltage, causing pressure compressions and rarefactions in the air, independent of the size and material of the speaker.
When striking a table (or drum), each strike will be similar to the pluck of the string: the table or drum will filter the frequency content of the strike (actually a continuum of frequencies, initially) to the basic resonant frequencies. BUT as the rate of striking increases, two things could happen: 1) the rate of striking could reach the audible range, and 2) on a drum, the strike rate may be fast enough to change the average tension in the drum head causing a general rise in the resonant frequencies. This often happens in tympani and tabla.