text:
Q: java.lang.ClassCastException android.widget.FrameLayout$LayoutParams I am developing a new app and app crashes and getting following error from Logcat

Fatal Exception: java.lang.ClassCastException
  android.widget.FrameLayout$LayoutParams cannot be cast to
  android.support.v7.widget.RecyclerView$LayoutParams
  android.support.v7.widget.RecyclerView.getChildViewHolderInt
  (RecyclerView.java:4609)
  android.support.v7.widget.RecyclerView.getChildAdapterPosition
  (RecyclerView.java:4628)
  com.empowered.healo.ui.screens.favourite.FavouriteExercisesFragment$initList$1.getItemOffsets
  (FavouriteExercisesFragment.kt:69)
  android.support.v7.widget.RecyclerView$ItemDecoration.getItemOffsets
  (RecyclerView.java:10521) com.android.internal.os.ZygoteInit.main
  (ZygoteInit.java:1374)

below my FavoriteExercisesFragment.java file
class FavouriteExercisesFragment : BaseMvpFragment(), FavoriteExerciseView {

    val adapter: FavoriteExerciseAdapter by lazy {
        FavoriteExerciseAdapter(context!!)
    }
    val presenter: FavoriteExercisePresenter = FavoriteExercisePresenter(this)

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        rootView = inflater.inflate(R.layout.fragment_favorite_ex, container, false)
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            super.onViewCreated(view, savedInstanceState)
        }
        initToolbar()
        initList()
        presenter.getFavoriteExercise()
    }

    private fun initList() {
        rvExercise.layoutManager = LinearLayoutManager(context)
        rvExercise.adapter = adapter
        val helper = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.RIGHT) {
            override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
                adapter.onItemMove(viewHolder.adapterPosition, target.adapterPosition)
                return true
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val position = viewHolder.adapterPosition
                val item = adapter.data[position]
                adapter.onItemDismiss(viewHolder.adapterPosition)
                presenter.deleteFromFavorite(item, position)
                showEmptyData(adapter.data.isEmpty())

            }
        })

        rvExercise.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
                super.getItemOffsets(outRect,itemPosition, parent)
                val position = parent.getChildPosition(view!!)
                if (position == 0) {
                    outRect.top = 58.dp
                } else {
                    outRect.top = 0
                }

            }
        })
        helper.attachToRecyclerView(rvExercise)
        adapter.helper = helper
        adapter.actions = object : FavoriteExerciseAdapter.AdapterAction {
            override fun playExercise(exercise: Exercise) {
                val file = exercise.files.firstOrNull { it.mainFile }
                val uri = file?.getFile() ?: ""

                context?.startActivityFromCenter(VideoActivity.newInstance(context, uri), rootView, VideoActivity.REQUEST_CODE)
            }
        }
    }
    private fun initToolbar() {
        toolbar.setOnNavigateIconClickListener { router.exit() }
        toolbar.setOnToolIconClickListener { openNavDrawer() }
    }

    override fun setFavoriteExercises(exercises: ArrayList<Exercise>) {
        showEmptyData(exercises.isEmpty())
        adapter.addData(exercises)
    }

    override fun showDeleteMessage(item: Exercise, position: Int) {
        val snack = Snackbar.make(rootView, R.string.message_remove_from_favorite, Snackbar.LENGTH_LONG)
        snack.setAction(R.string.action_undo) {
            presenter.addToFavorite(item)
            adapter.addItemOnPosition(item, position)
            showEmptyData(adapter.data.isEmpty())
        }
        snack.show()
    }

    private fun showEmptyData(show: Boolean) {
        tvEmpty.visibility = if (show) View.VISIBLE else View.GONE
        emptyIcon.visibility = if (show) View.VISIBLE else View.GONE
    }
}

below FavoriteExerciseAdapter.kt
class FavoriteExerciseAdapter(val context: Context) : RecyclerView.Adapter() {
var data: ArrayList<Exercise> = ArrayList()
var actions: AdapterAction? = null
var helper: ItemTouchHelper? = null

override fun onCreateViewHolder(p0: ViewGroup, viewType: Int): FavoriteViewHolder =
        FavoriteViewHolder(LayoutInflater.from(context).inflate(R.layout.item_favorite_exercises, p0, true))

override fun onBindViewHolder(holder: FavoriteViewHolder, position: Int) {
    val item = data[position]
    val preview = item.files.firstOrNull { !it.mainFile }
    if (preview != null)
        Glide.with(holder.itemView)
                .load(preview.getFile())
                .into(holder.mainImage)
    else holder.mainImage.setImageResource(0)
    holder.tvName.text = item.title?.getText
    holder.play.setOnClickListener {
        actions?.playExercise(item)
    }
    holder.drag.setOnTouchListener { _, event ->
        if (event.action == MotionEvent.ACTION_DOWN) {
            helper?.startDrag(holder)
        }
        false
    }
}

override fun getItemCount(): Int = data.size

class FavoriteViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val mainImage: ImageView = itemView.findViewById(R.id.mainImage)
    val tvName: TextView = itemView.findViewById(R.id.tvName)
    val play: ImageView = itemView.findViewById(R.id.icon_play)
    val drag: View = itemView.findViewById(R.id.drag)
}

fun addData(data: ArrayList<Exercise>) {
    this.data = data
    notifyDataSetChanged()
}

fun addItemOnPosition(item: Exercise, position: Int) {
    data.add(position, item)
    notifyItemInserted(position)
}

fun onItemDismiss(position: Int) {
    data.removeAt(position)
    notifyItemRemoved(position)
}

fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {
    if (fromPosition < toPosition) {
        for (i in fromPosition until toPosition) {
            Collections.swap(data, i, i + 1)
        }
    } else {
        for (i in fromPosition downTo toPosition + 1) {
            Collections.swap(data, i, i - 1)
        }
    }
    notifyItemMoved(fromPosition, toPosition)
    return true
}

interface AdapterAction {
    fun playExercise(exercise: Exercise)
}

}
I have tried following Android RecyclerView finding out first and last view on ItemDecoration did not fix problem


text:
Q: jQuery Mobile overflow of li-desc How can I force the heading to be visible, and the text below overflow into ellipsis? I can't get it to work with the BlackBerry list item when the page is wider than 768px.
http://jsfiddle.net/TeNXG/14/

News

    Back

iOS 6.1

Apple released iOS 6.1

iOS

BlackBerry 10

BlackBerry launched the Z10 and Q10 with the new BB10 OS and more and stuff and lots of stuff and overflowing and stuff and wow so much text man holy mess even more let's see just how jacked we can make this div

BlackBerry

Responsive Grid Listview

A: Add white-space: nowrap; to the description block:
ui-listview .ui-li-desc {
    white-space: nowrap;
    overflow: visible;
    position: absolute;
    left: 0;
    right: 0;
}

See the updated jsFiddle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como implementar ng-show en un auto-completar de angularjs Hola a todos tengo este autocompletar de material y quiero conseguir que al seleccionar un item se muestre mi etiqueta
:

    <md-autocomplete
            md-selected-item="selectedItem"
            md-selected-text="selectedItem"
            md-search-text="searchText"
            md-items="item in querySearch(searchText)"
            md-item-text="item.rut"
            placeholder="Ingrese rut del paciente">
        <md-not-found>Rut no encontrado.</md-not-found>
        <md-icon md-svg-icon="images/buscame.svg"></md-icon>

        {{item.rut + ' Numero: '+item.numero}}
    </md-autocomplete>

        {{'El rut seleciado es: ' +selectedItem.rut+' y su numero de atención: ' + selectedItem.numero}}

Como puedo implementar correctarmente en esta situacion un ng-hide, ng-show hasta pense en un ng-change pero me la gano... saludos....

A: Esta expresión
ng-show="{{!selectedItem.rut === undefined}}"

Debería ser
ng-show="!!selectedItem.rut"

o
ng-show="selectedItem.rut"

Esta directiva está diseñada para usar una expresión, no una interpolación {{}} como la tienes actualmente.
Además no es necesario comparar contra undefined, puedes usar truthy y simplificar la expresión usando !! para coercionar a booleano o usar el valor directamente ya que si tiene algo la expresión evaluará a true. Recuerda que lo que quieres es mostrar el valor si hay algo ahí.


text:
Q: Hibernate updatable = false UUID field is updated I am using Spring Data JPA with Hibernate and am having trouble with the updatable=false property on the @Column annotation.
I have a base class for all of my @Entity objects with a UUID defined like this:
@MappedSuperclass
@Getter @Setter @EqualsAndHashCode(of= {"uuid"})
public abstract class AbstractEntity implements Persistable<Long> {

    @Id
    @GeneratedValue(strategy = AUTO)
    @Column(unique = true, updatable = false)
    private Long id;

    @Column(unique = true, updatable = false)
    private UUID uuid = UUID.randomUUID();

}

Note the updatable = false annotation.
To verify the UUID field is in fact NOT updatable, I have written this test:
@Test
public void testChangeUUID() {

    User user = userRepo.findOne(1L);

    assertNotNull(user);
    assertEquals(USER_UUID, user.getUuid().toString());

    final UUID newUuid = UUID.randomUUID();

    user.setUuid(newUuid);

    user = userRepo.save(user);

    assertEquals(newUuid, user.getUuid());

    User user2 = userRepo.findOne(1L);
    assertNotNull(user2);
    assertEquals("UUID should not have changed", USER_UUID, user2.getUuid().toString());
}

I was actually expecting an exception to be thrown on the call to userRepo.save(user), but that doesn't happen. Instead, the final assertEquals() fails, which means the UUID was in fact updating.
Is this expected behavior? Is there any way to prevent UUIDs from being changed?

A: While the original question has been answered already, I would like to highlight an important point for people who are new with Hibernate as it might help to avoid some confusion.
The javadoc of Hibernate 5.4  of the @Column annotation, says for its optional element Updatable:

(Optional) Whether the column is included in SQL UPDATE statements generated by the persistence provider.

If you issue an update statement with HQL or using CriteriaUpdate, against a field that you have annotated  with @Column(updatable = false) , your update statement will be executed .
The @Column(updatable = false) works, when you are using either Hibernate's update or JPA's merge method.
No exception will be thrown (unlike for ex.: @Column(nullable= false) as it creates a constraint...), but the generated update statement will not include the marked field.
For further information, it is really a must to familiarise yourself with the JPA's entity lifecycle states and the methods that manages them, as can be seen on the picture below.
As well as I highly recommend to read this article which explains this in details, and is the source of the attached picture.

A: As per the documentation, the updatable property decided whether the column would be part of the update statement. It means that Hibernate ignores it when sending updates to the database. Thus, the in-memory state and the database state will differ.
To verify this, try clearing the session (evict) before calling User user2 = userRepo.findOne(1L)


text:
Q: Synchronize Local and Remote MySQL Databases I'm trying to get a workflow on database synchronization. Right now:

*

*We create a database.

*The database goes to production.

*Later... we realise that we need to change the database structure. We change that locally.

*Once that is done, we upload to the production.
If this is common among developers, what methods do you use to deal with this, without losing data already introduced on the production side?

A: You should be placing your database schema under version control.  There are lots of tools available to help you with this.
Check out this other previous question on the topic for a few PHP-specific options.  Database migrations are usually part of code rollouts.  Look into build tools to help make this process more automated.  Phing is a popular option.


text:
Q: How does SRCNN network retain the original size of image? Why does the image not become smaller with every convolution? SRCNN is one of the most well-known recent techniques in Image super-resolution. The authors propose a CNN layered structure, where they use 4 convolutional layers one after the other with filter sizes of 9, 1, 5, 3.
According to my understanding, this would mean that the image size would progressively decrease (except in the second layer). Even if padding is used to keep the image size same, the first operation would mean the addition of 4 zeros along every edge. So, the filter of size 5 would basically see only zeros at one end, which should lead to terrible resolution along edges.
The paper does not explain how they got around the problem of decreasing image size. Any help would be highly appreciated.
Thanks in advance.

A: This github repository shows the approach(or insight) to work with the edge problem. You may need to modify it a bit to fit into your code.
https://github.com/jormeli/srcnn-keras

A: Sorry for the late reply,
I have been working in this domain and i finally understood why the image size isn't decreasing even when applying convolution operations. Let us take the Architecture mentioned by the author i.e. ( 9 - 3 - 5 ).
In the code implementation, the image is divided into 32x32 sub images and for each sub image its hr and lr version is prepared by downscaling and upscaling. So we prepare a hr patch of size [20:20] and lr patch [32:32]. (Before giving these patches as input to first conv layer, we remove the 6 bordering pixels so the hr patch shape would be 32 - (6+6) = 20 x 20 thats why i have mentioned hr patch above as [20:20])
the whole trick is in padding, we provide the LR patch as input to the CNN
First conv layer : filter size  = 9, padding = Valid, so the shape of
output = n-f+1 ( 32 - 9 + 1 ) = 24, So output of first layer is 24x24 image
Second conv layer : filter size  = 3, padding = Same, so the shape of
output = Shape of input, So output of second layer is 24x24 image
Third conv layer : filter size  = 5, padding = Valid, so the shape of
output = n-f+1 ( 24 - 5 + 1 ) = 20, So output of third layer is 20x20 image.
So finally we have a LR patch of 20x20 and HR patch of 20x20, we compare this, perform mse and backpropagate errors.
So here we donot actually increase the size of image, we keep the size of image same and we make adjustments so that the image appears better.
Cheers :)


text:
Q: Какая регулярка подойдет под эти символы Есть такой массив:
[''','"','.','!','@','#','№','$',';','%',':','^','&','?','*','(',')','-','_','+','=','{','}','[',']','\','|','/','`','~','<','>',' ']

Можно ли его переработать в регулярку чтоб под нее попадали все символы в любом месте строки кроме букв и цифр?

A: Нужно всё, кроме букаф и цифр?
Проще не искать все НЕ буквы/цифры, а исключить онные.
Как-то так:
$str =~ /[^a-z0-9]*/i;

A: Регулярка:
/(\W|_)/g

Пример кода:
var a = 'asdsda ;_-: dd';
console.log(a.match(/(\W|_)/g, ''));


text:
Q: transform excel format Environment: Microsoft Excel 2003, 07, or 10
Is there an easy way to transform
lines 1-11

into
lines 15-20

A: This can be easily done with few additional basic test formulas.
Add the columns in your table as per the screenshot below and filter your table with is_id column TRUE data.
Enjoy, you're welcome.


text:
Q: How to get current location of the User in Flutter I have followed the steps and examples mentioned in the flutter dev community, but I want to fetch location and get latitude and longitude separately. Also, can anyone help me how to use the values returned from async functions in dart?

Here is my code which I feel is inappropriate.

Future<UserLocation> getLocation() async {
  bool _serviceEnabled;
  PermissionStatus _permissionGranted;
  LocationData _locationData;

  _serviceEnabled = await location.serviceEnabled();

  _permissionGranted = await location.hasPermission();
  if (_permissionGranted == PermissionStatus.denied) {
    _permissionGranted = await location.requestPermission();
  } else {
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
    } else {
      _locationData = await location.getLocation();
      return UserLocation(_locationData.latitude, _locationData.longitude);
    }
  }
  return UserLocation(15.25, 15.50);
}

Then while using it -
  @override
  void initState() {
    () async {
      location = await getLocation();
    };
    super.initState();
  }

The result I want is:
double latitude = location.latitude;
double longitude= location.longitude;

A: Firstly, you can define that in this way, let me know if it works
LocationData? currentLocation;

void getCurrentLocation() {

  Location location = Location()

    location.getLocation().then((location) {
    currentLocation = location
  })
}

@override
  void initState() {
    super.initState();
    getCurrentLocation()
  }

Then on the widget side, add this check: You can get latitude and longitude values from currentLocation variable.
currentLocation == null ? const Center(child: CircularProgressIndicator()) : .....

Plus: If you want to get more information about how to build map application in Flutter, you can watch this tutorial.


text:
Q: Projective Line as quotient ringed space Let $\mathbb{k}$ be an infinite field, $X=\mathbb{A}^2 \setminus \{(0,0)\}$ and $G$ the group of automorphisms $(x,y) \mapsto (\alpha x, \alpha y)$ for all $\alpha \in \mathbb{k}^{*}$. Seeing $Y=X/G$ as topological space, it's obvious that it is $\mathbb{P}^1$. In order to show that $Y$ is a ringed space, I have to proof that the sheaf $\mathcal{O}_Y$ such that $\mathcal{O}_Y(U)=\mathcal{O}_X(p^{-1}(U))^G$ is isomorphic to the structure sheaf of $\mathbb{P}^1$.
1) How can proof this result?
2) Moreover, if $G$ is the group of automorphism $(x,y) \mapsto (\alpha x, \alpha^{-1} y)$, is $Y/X/G$ a scheme?
3) Is it true even if $X=\mathbb{A}^2$?

A: Question 1:
You have a $G=k^*$ invariant map of varieties  $\mathbb{A}^2 -(0,0) \rightarrow \mathbb{P}^1$ sending $(x,y)$ to $(x:y)$. Topologically, this is your quotient map. It restricts to a $G$ invariant map $\mathbb{A}^2 - y$ axis $\rightarrow \mathbb{P}^1-\infty$. Both schemes are affine in this case, so the restricted map corresponds to a map of $k$-algebras $k[Y/X] \rightarrow k[X,X^{-1},Y]$ which does the obvious thing. The induced $G$ action on the right hand side is such that $\alpha$ sends $p(X,X^{-1},Y)$ to $p(\alpha X,\alpha^{-1}X^{-1}, \alpha Y)$. It is clear that the image of $k[Y/X]$ is invariant under $G$.
I guess the hard part is to see that you get every invariant polynomial in the image. But it doesn't seem too bad; $p$ is invariant if and only if every monomial in $p$ of the form $X^mY^n$ (where $m$ is allowed to be negative) is invariant. But clearly such a monomial is invariant if and only if $m=-n$, i.e. is $Y/X$ raised to a power. So this proves that $O_{\mathbb{A}^2-(0,0)}|_{x\neq0}$ is isomorphic under the given map to $O_{\mathbb{P}^1}|_{\mathbb{P}^1-\infty}$. Play the same argument with $\mathbb{A}^2 - x$ axis to get the other isomorphism you need.
Question 3: The standard way for affine varieties, in this case $Speck[X,Y]$, to get a quotient with decent functorial properties is to just take $Spec$ of the $G$ invariants. That will give you a point $Spec(k)$ in this case, which isn't the topological quotient. This is because the topological quotient is a bad space. The only neighborhood of the origin is the whole space, so it's not even Hausdorff.

A: *

*Do the computation. What does an open set in $\mathbb{P}^1$ look like? Can you describe it's inverse image under $p$? Can you compute the sections of the sheaves? This computation is relatively straightforwards- just start writing and eventually you'll finish.

*This is an example of weighted projective space. You can construct it as a gluing of two copies of $\mathbb{A}^1$ (where either $x$ or $y$ is nonzero) along the copy of $\mathbb{A}^1\setminus 0$ where they're both nonzero. Weighted projective spaces are toric varieties, and therefore schemes.

*You can take the quotient, but the quotient object is fairly badly behaved- every point is any any neighborhood of the origin, for example. GIT (geometric invariant theory) can tell you more about these types of strangely behaved quotients.


text:
Q: First order ODE and hyper geometric function Is it possible that the solution to a first order differential equation involves a hyper geometric function? I thought that only second order ODE solution contains hypergeometric function. I am relying on Wolfram to find the solution.

A: A first-order Riccati equation "reduces" to a second-order linear equation, which might be hypergeometric.  For example, the Riccati equation
$$ {\frac {\rm d}{{\rm d}x}}v \left( x \right) = \left( v \left( x
 \right)  \right) ^{2}-{\frac { \left(  \left( a+b+1 \right) x-c
 \right) v \left( x \right) }{{x}^{2}-x}}+{\frac {ab}{{x}^{2}-x}}=0
$$
has solutions $v = -u'/u$ where $u$ satisfies the hypergeometric equation
$$ (x^2-x) u'' + ((a+b+1) x - c) u' + ab u = 0$$
and so one of its solutions is
$$ - \;{}_2F_1(a,b; c; x)^{-1} \dfrac{d}{dx} {}_2F_1(a,b; c; x) = -{\frac {ab\;{\mbox{$_2$F$_1$}(b+1,a+1;\,c+1;\,x)}}{
{c\; \mbox{$_2$F$_1$}(a,b;\,c;\,x)}}}
$$


text:
Q: Prove that $e^{x} \geq x^{e}$ for all $x \geq 0$. I have been trying to prove that $e^{x} \geq x^{e}$ for all $x \geq 0$.
This is what I have gotten so far:
$$
f(x) = e^{x} \\
g(x) = x^{e} \\
f'(x) = \frac{d(e^{x})}{dx} = e^{x} \\
g'(x) = \frac{d(x^{e})}{dx} = e x^{e-1}\\
$$
Now for all $x \geq 0$, $f'(x) \geq 0$, so $f(x)$ is always increasing or is constant, and $g'(x) \geq 0$ so $g(x)$ is always increasing or is constant.
Thus across the interval $[0,e]$, the lowest $f(x)$ can be is $f(0) = 1$ and the lowest $g(x)$ can be is $g(0) = 0$. The highest possible value of $f(x)$ is $f(e) = e^{e}$ and highest value of $g(x)$ is $g(e) = e^{e}$.
Thus across the interval $[0,e]$, $f(x) \geq g(x)$.
I've got 2 questions. One, is what I did correct. If not, where did I go wrong and what is the right method. Two, if yes, how does one prove it for the interval $(e,\infty)$.

A: Your proof is incorrect. Just because both functions are increasing doesn't mean that the one that is ahead always maintains the lead. This is because $g(x)$ could pass $f(x)$ because it starts off increasing sufficiently fast, and then at a later point $f(x)$ could start increasing very rapidly to regain the lead over $g(x)$.
EDIT: a specific counter example has been given in the comments.


text:
Q: Run .exe file from SQL Query i am trying to open a .exe file from within an sql query or Job.
im using xp_cmdshell , it is enabled on the server
the .exe runs properly when i double click on it from my windows Explorer
but when i try to open it using xp_cmdshell it returns to me 1 row affected
and the row is null.
the .exe file is supposed to delete all the content from a certain table.
when i run the file from the windows explorer, the .exe deletes all the content of the above mentioned table, whereas when i try using xp_cmdshell the content of the table remain intact, which means the .exe file is not opened.
any ideas?? this is the code i'm using
exec master..xp_cmdshell  'C:\inetpub\wwwroot\Digital_Library_Shamaa\ShamaaConsoleIndexer\Publish\setup.exe'
i have added the permission Everyone to the folder containing the above .exe file and all its sub folders!

A: 1) Run EXEC master..xp_cmdshell 'whoami' to see which user you're trying to run the exe file
2) Did you enable :
USE master
GO
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE WITH OVERRIDE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE WITH OVERRIDE
GO

3) Did you unblock the file ?


text:
Q: Magento 2.3 : How to add Custom button on a custom grid in customer view Adminhtml You have already answer this question , I have to do this in magento2. How can i do?Where i have to add this code

A: Add code inside <argument name="data" xsi:type="array"> tag
<item name="buttons" xsi:type="array">
        <item name="add" xsi:type="array">
            <item name="name" xsi:type="string">add</item>
            <item name="label" xsi:type="string">Button name</item>
            <item name="class" xsi:type="string">primary</item>
            <item name="url" xsi:type="string">*/redirect-url</item>
        </item>
    </item>

in the xml responsible for rendering the grid.
If you grid is rendering from block file add below code in Grid.php
public function getMainButtonsHtml()
{
    $html = parent::getMainButtonsHtml();//get the parent class buttons
    $addButton = $this->getLayout()->createBlock('Magento\Backend\Block\Widget\Button')
        ->setData(array(
        'label'     => 'Button Name',
        'onclick'   => "setLocation('redirect-url')",
        'class'   => 'task'
    ))->toHtml();
    return $addButton.$html;
}


text:
Q: Frequent cluster upgrades Google container engine Last night my production container engine cluster was being upgraded repeatedly without any user action from our team.
I want to understand is this frequent for other users too.
If yes then does Google Cloud team notify of these upgrades.
We were not prepared for this hence we experienced significant downtime.
Anyone else also facing similar issues.
Anyone from Container engine team could let us know what is happening here?


text:
Q: How to the display the number of instances of a string in vim statusline A while ago I got to find a function to use in .vimrc to show if there ocurrances of " TODO " in the current buffer and show TD in the statusline. This is the function:
...
hi If_TODO_COLOR ctermbg=0 ctermfg=175 cterm=bold
set statusline+=%#If_TODO_COLOR#%{If_TODO()}
...

function! If_TODO()
    let todos = join(getline(1, '$'), "\n")
    if todos =~? " TODO "
        return " TD "
    else
        return ""
    endif
endfunction

My question is how can I modify the function to also return how many times the string has appeared in the buffer - somthing like TD (6).

A: You could :help filter() the lines to get a list of lines containing TODO:
let lines = getline(1, '$')
let todos = filter(lines, 'v:val =~? " TODO "')
return len(todos) > 0 ? 'TD' : ''

The same thing, expressed in a slightly more "modern" way:
return getline(1, '$')
    \ ->filter('v:val =~? " TODO "')
    \ ->len() > 0 ? 'TD' : ''

See :help method.


text:
Q: Is this an equivalent definition of the notation $f(x) \equiv g(x) \hspace{4mm} ( \text{mod} \hspace{2mm} h(x), \hspace{1mm} n )$? I understand that the notation
$$
f(x) \equiv g(x) \hspace{4mm} ( \text{mod} \hspace{2mm} h(x), \hspace{1mm} n )
$$
means that $f(x)$ is congruent to $g(x)$ in the polynomial quotient ring $\mathbb{Z}_n / h(x)$ (although I am not really sure what exactly this means).
Is this the same as saying
$$
\left( f(x) \hspace{4mm} \text{mod} \hspace{2mm} h(x) \right) \hspace{4mm} \text{mod} \hspace{2mm} n \hspace{4mm} = \hspace{4mm} g(x)
$$

A: The left hand side of your equation is an equivalence class in $\mathbb{Z}_n[x]/(h(x))$ whereas the right hand side is a polynomial in $\mathbb{Z}[x]$. Hence it is not correct.
The congruence you define means $\overline{f}-\overline{g}\in (\overline{h})$ where $\overline{f}$ denotes the image of $f$ under the canonical map $\mathbb{Z}[x]\rightarrow\mathbb{Z}_n[x]$.


text:
Q: Does a MySQL database run faster on Windows server or Windows 10? I was wondering if a MySQL database run faster on Windows server 2019 or on Windows 10.
Are the performance based on the operating system or just on the installed hardware?

A: The only significant differences are

*

*HDD (slower) or SSD (faster)

*Network latency (now close are the client and server)

Other things:

*

*CPU -- Today's CPUs don't have much range in speed.  And most queries are fast enough that a CPU speed difference is usually not noticeable

*CPU cores -- See CPU.

*RAID with hardware write cache -- Beneficial for heavy write situations.

*OS -- Only if you have very little I/O and network latency might you even be able to measure an OS speed difference.


text:
Q: How to move my app from "Rejected" status to "waiting for upload" status? my app was rejected from my iTunesConnect account and now i did't find ready for upload button on iTunesConnect new design. so how can my app move from "Rejected" status to waiting for upload status.

A: thanks to all this issue solved.
now in iTunesConnect new design this steps are changed as below.
Step 1 : first you need to upload new build from XCode or Application Loader.
Step 2 : open iTunesConnect account and Then Attach that build on iTunesConnect build section.
Step 3 : then click on save button.
Step 4 :Click on Right Side You have Option to Submit For Review.
so by following these steps your app move from "Rejected" status to "Waiting for review Status".


text:
Q: How can I install R mockery package using conda? I want to install this package: https://cran.r-project.org/web/packages/mockery/README.html
I'm trying to install it in my conda environment but conda install -c r r-mockery yields an error saying that the package could not be found.
Is there a reason why some packages on CRAN could be uninstallable via conda?

A: It could be version Issue. Please post some details regarding what version of R you are using and see if the package is available for that version of R.


text:
Q: Find the node that has no children. If it has any  children, just ignore it I'm using HTMLAgilityPack. I have something like this:

Postadress

Box  27

    16493 KISTA

The problem is there are other
s.
So I have to find the one that has a
 child with the text "Postaddress".
What I need to extract is the value of
 that is "16493 KISTA".
There are other records returned for
 that have  children and I don't want those to be returned. I'm only looking for
 that has no children and only contains naked text.
My solution so far is:
var postAddressdiv = doc.DocumentNode.SelectNodes("//div[@class='address']");
if (postAddressdiv != null)
{
    foreach (HtmlAgilityPack.HtmlNode node in postAddressdiv)
    {
        HtmlNode postAddress;
        var h3 = node.Descendants("h3");
        if (h3 != null)
        {
            if (h3.First().LastChild.InnerHtml == "Postadress")
            {
                MessageBox.Show("right place you are.");
                postAddress = node.SelectSingleNode("//div[@class='post-address']");
                var postAddressChildren = postAddress.Descendants();
                if (postAddressChildren == null)
                    MessageBox.Show("found one!!!!");
            }
        }
    }
}

But it's not working. What am I doing wrong? Thanks.

A: var nodes  = doc.DocumentNode
            .SelectNodes("//div[@class='address' and h3='Postadress']/div[@class='post-address']");


text:
Q: How to get total network usage in terminal since pc opened I can get total network usage from terminal by ifconfig wlp0s20f3 but i also get many other extra info about wlp0s20f3 device.
The output:
wlp0s20f3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.43.67  netmask 255.255.255.0  broadcast 192.168.43.255
        inet6 fe80::5f55:a45c:b66a:a7d2  prefixlen 64  scopeid 0x20<link>
        ether 48:f1:7f:f3:15:83  txqueuelen 1000  (Ethernet)
        RX packets 82724  bytes 108476705 (103.4 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 28959  bytes 3840172 (3.6 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

I only need 103.4 MiB for rx  and 3.6 MiB for tx to use together with command output plasmoid in kde panel.  How can i get that?
PS: Any bash script to parse ifconfig output or any application gives that values are acceptable

A: *

*The more obvious route is to use Grep to extract only the values.
# RX bytes
ifconfig wlp0s20f3 | grep -o '[0-9.]* MiB' | head -n1
# TX bytes
ifconfig wlp0s20f3 | grep -o '[0-9.]* MiB' | tail -n1

*A more elegant alternative is to fetch the values (in bytes) from the /sys/class/net/wlp0s20f3/statistics/ directory.
cat /sys/class/net/wlp0s20f3/statistics/rx_bytes
cat /sys/class/net/wlp0s20f3/statistics/tx_bytes

A: You can get stats (including TX/RX byte and packet counts) in human readable units from the ip link command:
ip -s -h link show

To restrict output to a specific device use the dev field:
$ ip -h -s link show dev wls1
3: wls1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DORMANT group default qlen 1000
    link/ether 00:21:6a:96:40:12 brd ff:ff:ff:ff:ff:ff
    RX: bytes  packets  errors  dropped overrun mcast
    4.52G      5.03M    0       1       0       0
    TX: bytes  packets  errors  dropped carrier collsns
    357M       2.16M    0       0       0       0

It's not the easiest output to parse robustly but you could probably use something like
$ ip -s -h link show dev wls1 |
    awk '/RX: bytes/{getline; printf "RX: %s, ", $1} /TX: bytes/{getline; printf "TX: %s\n",$1}'
RX: 4.52G, TX: 357M

Replace wls1 with your own interface name wlp0s20f3 .

A: An addition to @Quasimodo 's answer:
echo "Down: $(($(cat /sys/class/net/wlp0s20f3/statistics/rx_bytes)/1024/1024)) MiB, Up: $(($(cat /sys/class/net/wlp0s20f3/statistics/tx_bytes)/1024/1024)) MiB"

gives excatly what i want. (wlp0s20f3) is my device.
Result:
Down: 103 MiB, Up: 4 MiB


text:
Q: Traverse string and replace symbols with their RTF escape representation in Java I am attempting to process several large text files and to replace their symbols such as #,@,$,= etc. with their corresponding RTF escape representation.
List of rtf char representations :
https://www.oreilly.com/library/view/rtf-pocket-guide/9781449302047/ch04.html
The temporary solution that I have implemented is to store some of those characters into an array and in case of match to replace them. The problem is that the files that I process are subject of change and it is typical for them to evolve. In some cases they have new symbols that are not present into my rtf array and updating the array is not an option. I can assume that adding all of the symbols from the list into the array is probably a very inefficient solution.
Could you please suggest me better and efficient solution to the problem or some concrete library ?


text:
Q: Time profiling C program in Xcode 7.3 Is it possible to use instruments's Time Profiler on a C program written within Xcode? I've tried opening up Instruments and selecting Time Profiler from within Xcode. The program I want to run it on (my Xcode project) is already selected under "recent executables". However when I press the record button there is no output, it just instantly stops with the pause button greyed out.
Help would be appreciated, thanks.


text:
Q: Can I close port 3306 if I dont use? I have a LAMP server. The port 3306 is opened.
I have a php program on the server, to make query and display it on the port 80.
Can I close it if I do not use SQL DB manager client software?

A: If you don't want to connect remotely to your DB from another host, you can just bind your mysql process to listen from only localhost 127.0.0.1, or yes you can close that port from firewall.


text:
Q: cuda - can't access blockDim.x? I'm working on a cuda program to process a 2D image.
The problem is when I try to access blockDim.x and blockId.x, the kernel always failed to launch and output unknown error.
Besides, if I use a 3x5 image, I can access the threadId.x, while I use a 2048x2048 image I can't.
My kernel code runs OK when I use PyCuda, but now I have to switch to cuda C.
I think the problem may be related to

*

*the way I pass the array pointer and there's something wrong with cudaMalloc

*the configuration with my block size and grid size( but the same configuration works well in PyCuda so I don't know how to correct it).

And I use cuda-memcheck, I got unknown error 30 and I googled for solutions but no helpful information.
__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    debug[idx] = threadIdx.x; // debug variable is used for debugging
}

int main(int arg, char* args[])
{
    // ...
    int size = w*h; // w is image width and h is image height
    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    // Copy image data from host memory to GPU buffers.
    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char),cudaMemcpyHostToDevice);

    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    extractor<<<g_dim, b_dim>>>(in, out, debug);

    // clean up code and processing result
}

Now I can't get expected index so I can't do processing in the kernel, what can be the problem?

EDIT
I want to use 1D index, which means I assume the image array is a "flattened" 1D array and do indexing.

EDIT
After I added the thread check, there's still something wrong.
__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    int y; int x;
    int temp_x; int temp_y; int temp_idx;
    int check = width*height;
    if (idx < check) {
        debug[0] = 1;    // get kernel launch failed "unknown error"
    }
}

I've tried to put the debug[0]=1; expression both in the thread check block and out the block, both of them get the same error.
So I doubt the memalloc is not been done correctly?
BTW, I used nvprof and it said
=22344== Warning: Found 2 invalid records in the result.
==22344== Warning: This can happen if device ran out of memory or if a device kernel was stopped due to an assertion.

EDIT
complete code:
#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <cmath>
#include <iostream>

#include "PNG.h"

#define L 3
#define INC1 1
#define INC2 1
#define R_IN 2
#define N_P 4
#define BLOCK_SIZE 1024
#define PI 3.14159265358979323846

using namespace std;

__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug, int* disX, int* disY, int width, int height, int pad, int num_sample)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    int y; int x;
    int temp_x; int temp_y; int temp_idx;
    int check = width*height;

       if (idx < check) {
        debug[idx] = threadIdx.x;
        y = idx/width;
        x = idx%width;
            if ((x < pad) || (x >= (width-pad)) || (y < pad) || (y >= (height-pad))) {
                // need padding
                for (int i = 0; i < num_sample; ++i){
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];

                    if (!((temp_x < 0)||(temp_x > (width-1)) || (temp_y < 0) ||(temp_y>(height-1)))) {
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
                }
            } else {
                for (int i = 0; i < num_sample; ++i)
                {
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
            }
       }
  }

vector<int> getCirclePos() {
    int r = 0;
    vector <int> circlePos;
    while (!(r>(L/2))) {
        circlePos.push_back(r);
        if (r < R_IN) r += INC1;
        else r += INC2;
    }
    cout << "circlePos:" << endl;
    for (auto i = circlePos.begin(); i != circlePos.end(); ++i)
    {cout << *i << ' ';}
    cout << endl;
    return circlePos;
}

int main(int arg, char* args[])
{
    cudaError_t cudaStatus;
    vector<int> circlePos = getCirclePos();

    // get disX, disY
    int num_sample_per_point = circlePos.size() * N_P;
    int* disX = new int[num_sample_per_point];
    int* disY = new int[num_sample_per_point];
    int r; int cnt = 0;
    for (int i = 0; i < circlePos.size(); ++i)
    {
        r = circlePos[i];
        float angle;
        for (int j = 0; j < N_P; ++j)
        {
            angle = j*360.0/N_P;
            disX[cnt] = r*cos(angle*M_PI/180.0);
            disY[cnt] = r*sin(angle*M_PI/180.0);
            // cout nvpro   << disX[cnt] << "|" << disY[cnt]<< endl;

            cnt++;
        }
    }

    PNG inPng("test.png");
    // PNG outPng;
    // outPng.Create(inPng.w, inPng.h);

    //store width and height so we can use them for our output image later
    const unsigned int w = inPng.w;
    const unsigned int h = inPng.h;
    cout << "w: " << w << " h: " << h << endl;
    //4 because there are 4 color channels R, G, B, and A
    int size = w * h;

    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    vector<unsigned char> img_data;
    for (int i = 0; i < size; ++i)
    {
        img_data.push_back(inPng.data[i*4]);
    }

    // debug
    cout << "========= img_data ==========" << endl;
    for (int i = 0; i < size; ++i)
    {
        cout << int(img_data[i]) << "," ;
    }
    cout << endl;

    // Copy image data from host memory to GPU buffers.
    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char), cudaMemcpyHostToDevice);

    //free the input image because we do not need it anymore
    inPng.Free();

    // Launch a kernel on the GPU with one thread for each element.
    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    int pad = L/2;

    // __global__ void extractor(const unsigned char* in, unsigned char* out, vector<int> disX, vector<int> disY, int width, int height, int pad, int num_sample)
    extractor<<<g_dim, b_dim>>>(in, out, debug, disX, disY, w, h, pad, num_sample_per_point);

    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess)
    {
        std::cout << "Kernel launch failed: " << cudaGetErrorString(cudaStatus) << std::endl;
        cudaFree(in);
        cudaFree(out);
        cudaFree(debug);
        exit(1);
    }

    auto tmp = new unsigned char[size*num_sample_per_point];
    auto tmp_debug = new int [size];

    cudaMemcpy(tmp_debug, debug, size * sizeof(int), cudaMemcpyDeviceToHost);
    cudaMemcpy(tmp, out, num_sample_per_point * size * sizeof(unsigned char), cudaMemcpyDeviceToHost);

    cout << "========= out =========" << endl;
    for (int i = 0; i < size*num_sample_per_point; ++i)
    {
        cout << int(tmp[i]) << ", ";
    }
    cout << endl;

    cout << "========debug=======" << endl;
    for (int i = 0; i < size; ++i)
    {
        cout << tmp_debug[i] << ", ";
    }
    cout << endl;

    cudaFree(in);
    cudaFree(out);
    cudaFree(debug);

    delete[] tmp; delete[] tmp_debug;

    return 0;
}

A: This (according to your comment) is defining 1024 threads per block:
dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)

According to your question text, w and h are each 2048 in the failing case, so this:
dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)

is creating 4097 blocks, just as you indicate in your comment.
4097 blocks of 1024 threads each is 4195328 threads total, but your allocation sizes are only providing 2048*2048 elements, or 4194304 elements total. So you are launching 4195328 threads with only 4194304 elements, leaving 1024 threads left over.
So what do those 1024 extra threads do?  They still run the kernel code and attempt to access your debug array beyond the end of the allocated space.
This results in undefined behavior in C and in C++.
The customary method to fix this is to pass the problem size to your kernel and  add a "thread check" in your kernel code, like this:
__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug, int n)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    if (idx < n)
      debug[idx] = threadIdx.x; // debug variable is used for debugging
}

which prevents the "extra" threads from doing anything.
If you search here on the cuda tag for "thread check" you will find many other examples of questions like this.
As an example, based on the code pieces you have shown, the following runs without error for me:
$ cat t147.cu
const int width = 2048;
const int height = 2048;
const int BLOCK_SIZE = 1024;
__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
//    int y; int x;
//    int temp_x; int temp_y; int temp_idx;
    int check = width*height;
    if (idx < check) {
        debug[idx] = 1;    // get kernel launch failed "unknown error"
    }
}
int main(int arg, char* args[])
{

    const int w = width;
    const int h = height;
    const int num_sample_per_point = 1;
    int size = w*h; // w is image width and h is image height
    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    // Copy image data from host memory to GPU buffers.
//    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char),cudaMemcpyHostToDevice);

    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    extractor<<<g_dim, b_dim>>>(in, out, debug);
    cudaDeviceSynchronize();
}
$ nvcc -arch=sm_61 -o t147 t147.cu
$ cuda-memcheck ./t147
========= CUDA-MEMCHECK
========= ERROR SUMMARY: 0 errors
$

In your complete code, you simply have an illegal access problem in your kernel.  I've modified it to remove the dependency on PNG, and if we omit the kernel code other than the debug setting, it runs fine.  However if we include your kernel code, and run with cuda-memcheck we get all sorts of out-of-bounds accesses.  In the future, you could use the method described here to debug these:
$ cat t146.cu
#include <cmath>
#include <iostream>
#include <vector>

#define L 3
#define INC1 1
#define INC2 1
#define R_IN 2
#define N_P 4
#define BLOCK_SIZE 1024
#define PI 3.14159265358979323846

using namespace std;

__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug, int* disX, int* disY, int width, int height, int pad, int num_sample)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    int y; int x;
    int temp_x; int temp_y; int temp_idx;
    int check = width*height;

       if (idx < check) {
        debug[idx] = threadIdx.x;
        y = idx/width;
        x = idx%width;
#ifdef  FAIL
            if ((x < pad) || (x >= (width-pad)) || (y < pad) || (y >= (height-pad))) {
                // need padding
                for (int i = 0; i < num_sample; ++i){
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];

                    if (!((temp_x < 0)||(temp_x > (width-1)) || (temp_y < 0) ||(temp_y>(height-1)))) {
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
                }
            } else {
                for (int i = 0; i < num_sample; ++i)
                {
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
            }
#endif
       }
  }

vector<int> getCirclePos() {
    int r = 0;
    vector <int> circlePos;
    while (!(r>(L/2))) {
        circlePos.push_back(r);
        if (r < R_IN) r += INC1;
        else r += INC2;
    }
    cout << "circlePos:" << endl;
    for (auto i = circlePos.begin(); i != circlePos.end(); ++i)
    {//cout << *i << ' ';
      }
    cout << endl;
    return circlePos;
}

int main(int arg, char* args[])
{
    cudaError_t cudaStatus;
    vector<int> circlePos = getCirclePos();

    // get disX, disY
    int num_sample_per_point = circlePos.size() * N_P;
    int* disX = new int[num_sample_per_point];
    int* disY = new int[num_sample_per_point];
    int r; int cnt = 0;
    for (int i = 0; i < circlePos.size(); ++i)
    {
        r = circlePos[i];
        float angle;
        for (int j = 0; j < N_P; ++j)
        {
            angle = j*360.0/N_P;
            disX[cnt] = r*cos(angle*M_PI/180.0);
            disY[cnt] = r*sin(angle*M_PI/180.0);
            // cout nvpro   << disX[cnt] << "|" << disY[cnt]<< endl;

            cnt++;
        }
    }

    const unsigned int w = 2048;
    const unsigned int h = 2048;
    cout << "w: " << w << " h: " << h << endl;
    //4 because there are 4 color channels R, G, B, and A
    int size = w * h;

    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    vector<unsigned char> img_data;
    for (int i = 0; i < size; ++i)
    {
        img_data.push_back(0);
    }

    // debug
    cout << "========= img_data ==========" << endl;
    for (int i = 0; i < size; ++i)
    {
 //       cout << int(img_data[i]) << "," ;
    }
    cout << endl;

    // Copy image data from host memory to GPU buffers.
    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char), cudaMemcpyHostToDevice);

    // Launch a kernel on the GPU with one thread for each element.
    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    int pad = L/2;

    // __global__ void extractor(const unsigned char* in, unsigned char* out, vector<int> disX, vector<int> disY, int width, int height, int pad, int num_sample)
    extractor<<<g_dim, b_dim>>>(in, out, debug, disX, disY, w, h, pad, num_sample_per_point);

    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess)
    {
        std::cout << "Kernel launch failed: " << cudaGetErrorString(cudaStatus) << std::endl;
        cudaFree(in);
        cudaFree(out);
        cudaFree(debug);
        exit(1);
    }

    auto tmp = new unsigned char[size*num_sample_per_point];
    auto tmp_debug = new int [size];

    cudaMemcpy(tmp_debug, debug, size * sizeof(int), cudaMemcpyDeviceToHost);
    cudaMemcpy(tmp, out, num_sample_per_point * size * sizeof(unsigned char), cudaMemcpyDeviceToHost);

    cout << "========= out =========" << endl;
    for (int i = 0; i < size*num_sample_per_point; ++i)
    {
   //     cout << int(tmp[i]) << ", ";
    }
    cout << endl;

    cout << "========debug=======" << endl;
    for (int i = 0; i < size; ++i)
    {
     //   cout << tmp_debug[i] << ", ";
    }
    cout << endl;

    cudaFree(in);
    cudaFree(out);
    cudaFree(debug);

    delete[] tmp; delete[] tmp_debug;

    return 0;
}
$ nvcc -std=c++11 -o t146 t146.cu -arch=sm_61 -lineinfo
t146.cu(18): warning: variable "y" was set but never used

t146.cu(18): warning: variable "x" was set but never used

t146.cu(19): warning: variable "temp_x" was declared but never referenced

t146.cu(19): warning: variable "temp_y" was declared but never referenced

t146.cu(19): warning: variable "temp_idx" was declared but never referenced

t146.cu(18): warning: variable "y" was set but never used

t146.cu(18): warning: variable "x" was set but never used

t146.cu(19): warning: variable "temp_x" was declared but never referenced

t146.cu(19): warning: variable "temp_y" was declared but never referenced

t146.cu(19): warning: variable "temp_idx" was declared but never referenced

$ cuda-memcheck ./t146
========= CUDA-MEMCHECK
circlePos:

w: 2048 h: 2048
========= img_data ==========

========= out =========

========debug=======

========= ERROR SUMMARY: 0 errors
$ nvcc -std=c++11 -o t146 t146.cu -arch=sm_61 -lineinfo -DFAIL
$ cuda-memcheck ./t146
...
========= Invalid __global__ read of size 4
=========     at 0x00000418 in /home/ubuntu/bobc/misc/t146.cu:41:extractor(unsigned char const *, unsigned char*, int*, int*, int*, int, int, int, int)
=========     by thread (197,0,0) in block (17,0,0)
=========     Address 0x00c8b290 is out of bounds
=========     Saved host backtrace up to driver entry point at kernel launch time
=========     Host Frame:/usr/lib/x86_64-linux-gnu/libcuda.so.1 (cuLaunchKernel + 0x2c5)
...
(and much more output like this)

The above output points to line 41 in the code, which is reading from disX.
As it turns out, your disX is a host-allocated variable:
int* disX = new int[num_sample_per_point];

but you are attempting to pass it to device code:
extractor<<<g_dim, b_dim>>>(in, out, debug, disX, disY, w, h, pad, num_sample_per_point);
                                            ^^^^

That is just completely broken.  You can't do that in CUDA.  You need to make a device copy of that variable, and also disY  When I fix that problem, the modified code runs without error for me:
$ cat t146.cu
#include <cmath>
#include <iostream>
#include <vector>

#define L 3
#define INC1 1
#define INC2 1
#define R_IN 2
#define N_P 4
#define BLOCK_SIZE 1024
#define PI 3.14159265358979323846

using namespace std;

__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug, int* disX, int* disY, int width, int height, int pad, int num_sample)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    int y; int x;
    int temp_x; int temp_y; int temp_idx;
    int check = width*height;

       if (idx < check) {
        debug[idx] = threadIdx.x;
        y = idx/width;
        x = idx%width;
#ifdef  FAIL
            if ((x < pad) || (x >= (width-pad)) || (y < pad) || (y >= (height-pad))) {
                // need padding
                for (int i = 0; i < num_sample; ++i){
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];

                    if (!((temp_x < 0)||(temp_x > (width-1)) || (temp_y < 0) ||(temp_y>(height-1)))) {
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
                }
            } else {
                for (int i = 0; i < num_sample; ++i)
                {
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
            }
#endif
       }
  }

vector<int> getCirclePos() {
    int r = 0;
    vector <int> circlePos;
    while (!(r>(L/2))) {
        circlePos.push_back(r);
        if (r < R_IN) r += INC1;
        else r += INC2;
    }
    cout << "circlePos:" << endl;
    for (auto i = circlePos.begin(); i != circlePos.end(); ++i)
    {//cout << *i << ' ';
      }
    cout << endl;
    return circlePos;
}

int main(int arg, char* args[])
{
    cudaError_t cudaStatus;
    vector<int> circlePos = getCirclePos();

    // get disX, disY
    int num_sample_per_point = circlePos.size() * N_P;
    int* disX = new int[num_sample_per_point];
    int* disY = new int[num_sample_per_point];
    int r; int cnt = 0;
    for (int i = 0; i < circlePos.size(); ++i)
    {
        r = circlePos[i];
        float angle;
        for (int j = 0; j < N_P; ++j)
        {
            angle = j*360.0/N_P;
            disX[cnt] = r*cos(angle*M_PI/180.0);
            disY[cnt] = r*sin(angle*M_PI/180.0);
            // cout nvpro   << disX[cnt] << "|" << disY[cnt]<< endl;

            cnt++;
        }
    }

    int *d_disX, *d_disY;
    cudaMalloc(&d_disX, num_sample_per_point*sizeof(int));
    cudaMalloc(&d_disY, num_sample_per_point*sizeof(int));
    cudaMemcpy(d_disX, disX, num_sample_per_point*sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_disY, disY, num_sample_per_point*sizeof(int), cudaMemcpyHostToDevice);
    const unsigned int w = 2048;
    const unsigned int h = 2048;
    cout << "w: " << w << " h: " << h << endl;
    //4 because there are 4 color channels R, G, B, and A
    int size = w * h;

    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    vector<unsigned char> img_data;
    for (int i = 0; i < size; ++i)
    {
        img_data.push_back(0);
    }

    // debug
    cout << "========= img_data ==========" << endl;
    for (int i = 0; i < size; ++i)
    {
 //       cout << int(img_data[i]) << "," ;
    }
    cout << endl;

    // Copy image data from host memory to GPU buffers.
    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char), cudaMemcpyHostToDevice);

    // Launch a kernel on the GPU with one thread for each element.
    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    int pad = L/2;

    // __global__ void extractor(const unsigned char* in, unsigned char* out, vector<int> disX, vector<int> disY, int width, int height, int pad, int num_sample)
    extractor<<<g_dim, b_dim>>>(in, out, debug, d_disX, d_disY, w, h, pad, num_sample_per_point);

    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess)
    {
        std::cout << "Kernel launch failed: " << cudaGetErrorString(cudaStatus) << std::endl;
        cudaFree(in);
        cudaFree(out);
        cudaFree(debug);
        exit(1);
    }

    auto tmp = new unsigned char[size*num_sample_per_point];
    auto tmp_debug = new int [size];

    cudaMemcpy(tmp_debug, debug, size * sizeof(int), cudaMemcpyDeviceToHost);
    cudaMemcpy(tmp, out, num_sample_per_point * size * sizeof(unsigned char), cudaMemcpyDeviceToHost);

    cout << "========= out =========" << endl;
    for (int i = 0; i < size*num_sample_per_point; ++i)
    {
   //     cout << int(tmp[i]) << ", ";
    }
    cout << endl;

    cout << "========debug=======" << endl;
    for (int i = 0; i < size; ++i)
    {
     //   cout << tmp_debug[i] << ", ";
    }
    cout << endl;

    cudaFree(in);
    cudaFree(out);
    cudaFree(debug);

    delete[] tmp; delete[] tmp_debug;

    return 0;
}
$ nvcc -std=c++11 -o t146 t146.cu -arch=sm_61 -lineinfo -DFAIL
$ cuda-memcheck ./t146
========= CUDA-MEMCHECK
circlePos:

w: 2048 h: 2048
========= img_data ==========

========= out =========

========debug=======

========= ERROR SUMMARY: 0 errors
$


text:
Q: GLM Gamma family Term                 Estimate Std. Error     T-value   Pr(>|t|)
(Intercept)           5.04024   0.05426        92.9     <2e-16
Classe Juvenil       -1.45409   0.06265       -23.21    <2e-16
Complexidade Simples 1.022298   0.06265        16.33    <2e-16

How can I interpret this results?
In intercept I think I have two parameters (Class Adulto and Complexidade Complexo)

A: The intercept is the estimated mean for someone who is a complex adult, whatever that means. You then add the coefficient for youth (juvenil) to get the estimated mean for complex youth, add the coefficient for simple (simples) to get the estimated mean for simple adult, add both to get simple youth.
If you are modelling on the log scale (which you do not state) then those means are on the log scale and you may need to exponentiate them if you want to move back on to the raw scale.


text:
Q: WCF service could not be activated I am having problem with my WCF (which has client and server certificates)
Exception:

System.ServiceModel.ServiceActivationException:
  The requested service,
  'http://localhost/CustomerServiceSite/Customer.svc'
  could not be activated. See the
  server's diagnostic trace logs for
  more information..

Error Stack trace:

DoNegotiation(TimeSpan timeout)
  System.ServiceModel.Security.SspiNegotiationTokenProvider.OnOpen(TimeSpan
  timeout)
  System.ServiceModel.Security.TlsnegoTokenProvider.OnOpen(TimeSpan
  timeout)
  System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
  timeout)
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)
  System.ServiceModel.Security.CommunicationObjectSecurityTokenProvider.Open(TimeSpan
  timeout)
  System.ServiceModel.Security.SecurityUtils.OpenTokenProviderIfRequired(SecurityTokenProvider
  tokenProvider, TimeSpan timeout)
  System.ServiceModel.Security.SymmetricSecurityProtocol.OnOpen(TimeSpan
  timeout)
  System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
  timeout)
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout) OnOpen(TimeSpan timeout)
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)
  System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation
  operation, EndpointAddress target, Uri
  via, SecurityToken currentToken,
  TimeSpan timeout)
  System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetTokenCore(TimeSpan
  timeout)
  System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan
  timeout)
  ClientSecuritySessionChannel.OnOpen(TimeSpan
  timeout)
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)
  System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan
  timeout)
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)
  System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)
  System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)
  System.ServiceModel.ICommunicationObject.Open(TimeSpan
  timeout)
  System.ServiceModel.ICommunicationObject.Open(TimeSpan
  timeout) Open()

Dignostics settings (inside system.serviceModel)
<diagnostics>
  <messageLogging logEntireMessage="true" logMalformedMessages="true"
  logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" />
</diagnostics>

Where can I see diagnostics errors? Someone know what could be the problem?

A: That configuration won't be sufficient for logging those error messages.
What you need is two-fold - first the part inside <system.serviceModel> that you already have, to instruct WCF to do logging.
But you also need a second part - inside <system.diagnostics> - to define where to log that information to! Something like this:
<system.diagnostics>
    <sources>
        <source name="System.ServiceModel.MessageLogging" switchValue="Information, ActivityTracing">
           <listeners>
             <add name="messages"
             type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="c:\logs\messages.svclog" />
          </listeners>
        </source>
    </sources>
    <trace autoflush="true" />
</system.diagnostics>

There are a few different log listeners defined in the System.Diagnostics namespace - this one here will be logging the information to a XML-based *.svclog file, which you can then view and analyze using the Service Trace Viewer Tool.
Read more about Configure Message Logging on MSDN.

A: Just look in the Applications event log with the Event Viewer application.


text:
Q: Display the frequency of occurrence of words, and the words themselves Here are entered word and called container, which is a collection of storage words.
public class Part1 {

    public static void main(String[] args) {
        WordContainer wc = new WordContainer();
        Scanner in = new Scanner(System.in);
        String line;
        while (in.hasNextLine() && !"stop".equals(line = in.nextLine())) {
            wc.put(new Word(line));
        }

        in.close();
        print();

    }

    public static void print() {
        for (Word w : WordContainer.al) {
            System.out.println(w + ": " + w.getfrequency());
        }
    }
}

A container that stores word. If the word is in the sheet, we increase the frequency, if not - add a new word
public class WordContainer {

public static ArrayList<Word> al = new ArrayList<Word>();

public Word put(Word s) {
    for (Word w : al) {
        if (w.s.compareTo(s.getWord()) == 0) {
            s.setfrequency();
        } else {
            al.add(new Word());
        }
    }
    return s;
}

}
This class of words where the word is stored and the frequency of their occurrence
public class Word implements Comparable<Word> {
String s = "";
private int frequency = 0;

Word(String s) {
    this.s = s;
    frequency = 1;
}

Word() {
    setfrequency();
}

public void setfrequency() {
    ++frequency;
}

public int getfrequency() {
    return frequency;
}

public String getWord() {
    return s;
}

    @Override
    public int compareTo(Word o) {
        return s.compareTo(o.getWord());
    }
}

I can not understand why it does not work.
Please help me!

A: In case don't find a word, you add a new Word with a empty string instead of just the Word passed as parameter (or a copy with the same content). Furthermore you add a new Word for every Word where the content doesn't match...
Also the enhanced for loop tries to continue iterating through the list after it's modified, which leads to a ConcurrentModificationException.
Furthermore you'll probably want to return the Word from the list, not the one passed as parameter
Change the code as follows:
public Word put(Word s) {
    for (Word w : al) {
        if (w.s.compareTo(s.getWord()) == 0) {
            w.setfrequency();

            // found it, now stop searching
            return w;
        }
    }
    // didn't find it; insert
    al.add(s);
    return s;
}

Notes on the design
There are several things in your code that I'd consider bad design:

*

*You're using a static list in WordContainer, however the put method is a instance method. This means the data will be shared accross all instances of WordContainer, but you need to create a instance to call put. The list should be a non-static field too.

*The "internal data" of the WordContainer class is public. Furthermore Word is modifiable (you can call setfrequency on it), which lets you easily break encapsulation. The simplest way of fixing this would be making the Word class a inner class of WordContainer, changing the setfrequency method to private and passing a String to the put method.

public class WordContainer {

    public static class Word implements Comparable<Word> {
        private final String s;
        private int frequency;

        private Word(String s) {
            this.s = s;
            frequency = 1;
        }

        /*Word() {
            this("");
        }*/

        private void setfrequency() {
            ++frequency;
        }

        public int getfrequency() {
            return frequency;
        }

        public String getWord() {
            return s;
        }

        @Override
        public int compareTo(Word o) {
            return s.compareTo(o.getWord());
        }
    }

    private final List<Word> al = new ArrayList<Word>();
    private final List<Word> unmodifiableWords = Collections.unmodifiableList(al);

    public Word put(String s) {
        for (Word w : al) {
            if (w.s.equals(s)) {
                w.setfrequency();
                return w;
            }
        }
        Word word = new Word(s);
        al.add(word);
        return word;
    }

    public List<Word> getWords() {
         // do not allow for external modification of the list
         return unmodifiableWords;
    }

}

A: I think the problem lies in your put method in your class WordContainer. You are adding a new Word object to your list rather than using the one passed in your method.
if (w.s.compareTo(s.getWord()) == 0) {
   s.setfrequency();
} else {
   al.add(new Word());  // This is the likely reason, remove this line
                        // you should not be adding a new object

   al.add(s);           // Try this, you should be adding the object s
}

UPDATE :
There are 2 changes need to your existing implementation, I didn't realized that before.
First of all, you need to look if you list in WordContainer has already got that word or not. If not then you need to add it.
And second, for that to work, you need to override equals method in your Word method as the contains method would try to compare objects using equals
public Word put(Word s) {
        if (al.contains(s)) {
            for (Word w : al) {
                if (w.s.compareTo(s.getWord()) == 0) {
                    s.setfrequency();
                }// else {           //Remove this else, as you add element outside
                 // al.add(s);
                 //}
            }
        } else
            al.add(s);
        return s;
    }

And override equals method in your Word class. Typical override method generated by Eclipse would look like :
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Word other = (Word) obj;
        if (frequency != other.frequency)
            return false;
        if (s == null) {
            if (other.s != null)
                return false;
        } else if (!s.equals(other.s))
            return false;
        return true;
    }

UPDATE 2 :
Answer by Fabian is a nice and elegant way to do it.

A: Here's my shoot at a problem. I think issue is in WordContainer put method.
public class WordContainer {

public static ArrayList<Word> al = new ArrayList<Word>();
public Word put(Word s) {
    for (Word w : al) {
        if (w.s.compareTo(s.getWord()) == 0) {
            //s.setfrequency();
            w.setfrequency(); // <-- set frequency of existing word in al
            return w; // <-- return word object that is in al
        }
        // no need to add new word to list after every failed comparison
        // unless that's what you want to do.
    }
    al.add(s);
    return s;
}


text:
Q: JavaScript: Cross-Origin Read Blocking (CORB) blocked cross-origin response when request through gitlab api I have successfully received the user's id through gitlab api, but when I tried to receive the project list of the user, chrome returns CORB.
I have successfully received the id and all other user info with GitLab api v4. But when I was trying to receive the repo list of the user, I received the CORB block and get nothing on the response text. I can see the data in json form if the website address is entered directly. If I use jQuery.getJSON directly, it will ask me to add X-Requested-With or Origin to the header, which I don't know how to achieve.
                        var target = 'https://gitlab.com/api/v4/users/'+doc.data().gitlab_id+'/projects?callback=?';
                        console.log(target);
                        var xhr = new XMLHttpRequest();
                        xhr.onreadystatechange = process;
                        xhr.open("GET", target, true);
                        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                        xhr.setRequestHeader('responseType', 'text/plain');
                        xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
                        xhr.send();
                        function process() {
                            console.log(xhr);

I expect to get the json data, but now the response text is empty and it returns a message below:
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://gitlab.com/api/v4/users/USER_ID/projects?callback=jQuery11130057655514217979986_1563975117007&_=1563975117008 with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.

A: For anyone who faces the same problem:
Try adding 'https://cors-anywhere.herokuapp.com/' right before your request url.
For example, you can use
'https://cors-anywhere.herokuapp.com/https://api.linkedin.com/v2/me?oauth2_access_token=' + access_token;
to get info from linkedin without being troubled by cors policy.


text:
Q: Por que no funciona esta comprobación de multiselect vacío Estoy tratando de hacer una comprobación si dos campos multiselect están vacíos , Si están ambos llenos ejecute una parte de código, pero siempre me dice que están llenos.
JS
function ComprobarTallyColor() {
  if($("#colores").val().length >= 0 && $("#tallas").val().length >= 0){
    $().toastmessage('showToast', { text : 'Error
 Talla o Color vacios', sticky : false, type : 'notice' });
   } else {
     $().toastmessage('showToast', { text : 'Error
 Talla o Color llenos', sticky : false, type : 'notice' });
   }
}

HTML
<select onchange="ComprobarTallyColor()" name="tallas[]" id="tallas" style="width: 410px;" class="multibuskiselect multibuskiselect_Inarticulos" multiple="multiple">
<?php foreach($CTallas as $DTallas) { ?><option value="<?=$DTallas["id"];?>"><?=$DTallas["1"];?></option><?php } ?></select>

Colores:
<select onchange="ComprobarTallyColor()" id="colores" name="colores[]" style="width: 410px;" class="multibuskiselect multibuskiselect_Inarticulos" multiple="multiple">
<?php foreach($CColores as $DColores) { ?><option value="<?=$DColores["id"];?>"><?=$DColores["1"];?></option><?php } ?></select>

A: Es un poco difícil de ver por como tienes el código de JS pero en primera instancia me parece que el problema es que tienes al revés el mensaje del if y el else. Donde debería decir llenos dice vacíos y viceversa.
Si no es eso posiblemente sea cosa de cómo estás tratando de obtener el número de opciones en tu select. Posiblemente usando algo como lo siguiente sea lo más apropiado
$('#colores option').size()

Y entonces tu if quedaría de la siguiente manera.
if($('#colores option').size() >= 0 && $('#tallas option').size() >= 0){
    $().toastmessage('showToast', { text : 'Error
 Talla y Color llenos', sticky : false, type : 'notice' });
} else {
    $().toastmessage('showToast', { text : 'Error
 Talla o     Colores vacios', sticky : false, type : 'notice' });
}

De nuevo, puede ser que tu código funcione y sólo sea cosa de lo que estás imprimiendo en el if.
EDICIÓN
Ya vi que pusiste mejor tu código de JS. Sí tienes al revés los mensajes. En el if compruebas que los dos estén llenos o tengan algo y sin embargo estás imprimiendo 'Error
 Talla o Color vacios'

A: Al final quitando el = funciona
así que ha quedado así:
if($("#colores").val().length > 0 && $("#tallas").val().length > 0){

:) Muchas gracias a todos por la ayuda


text:
Q: Tensors constructed using KroneckerDelta's - and/or displaying KroneckerDelta as a matrix I am doing some work in elasticity and as a result am working with tensors. In particular, I would like to calculate the contraction of a fourth order tensor (the stiffness tensor) with a second order tensor (the velocity gradient) to get another tensor (the time derivative of the stress, for anyone interested).
For my material, the stiffness tensor is easily written down in terms of products of Kronecker Delta Functions such as $\delta_{ij}\delta_{kl}$. I can then easily compute the contraction by manually entering the second order tensor of interest, and using Sum in combination with Part to extract the result.
The problem is that, naturally, Mathematica displays the output in terms of KroneckerDelta[3, i], for example, and there's a lot of them - it's essentially writing the matrix out elementwise using delta functions. Is there a way I can easily view this as a matrix, or map them to a matrix, or alternatively, approach this problem from a different perspective which would avoid this issue altogether? I am trying to apply something along the lines of the following to my expression:
Replace[KroneckerDelta[i, j], KroneckerDelta[i, j] ->
TensorProduct[Part[IdentityMatrix[3], i], Part[IdentityMatrix[3], j]]]
If this were valid Mathematica code, it would work in theory, but I get the error The expression i cannot be used as a part specification. along with the same for j.

A: As far as I understood from your answers to comments you like KronekerDelta in the stiffness tensor, but not in the stress tensor. You can do as follows:
stiff[i_, j_, k_, l_] :=
 L KroneckerDelta[i, j] KroneckerDelta[k,
    l] + \[Mu] (KroneckerDelta[i, k] KroneckerDelta[j, l] +
     KroneckerDelta[i, l] KroneckerDelta[j, k])
vg = Array[v, {3, 3}];
vg // MatrixForm
stress[i_, j_] := Sum[stiff[i, j, k, l] vg[[k, l]], {k, 3}, {l, 3}]
stressT = Table[stress[i, j], {i, 3}, {j, 3}] // Simplify;
stressT // MatrixForm

leading to
$\begin{pmatrix}
 v(1,1) & v(1,2) & v(1,3) \\
 v(2,1) & v(2,2) & v(2,3) \\
 v(3,1) & v(3,2) & v(3,3) \\
\end{pmatrix}$
and
$\left(\begin{smallmatrix}
 2 \mu  v(1,1)+L (v(1,1)+v(2,2)+v(3,3)) & \mu  (v(1,2)+v(2,1)) & \mu  (v(1,3)+v(3,1)) \\
 \mu  (v(1,2)+v(2,1)) & 2 \mu  v(2,2)+L (v(1,1)+v(2,2)+v(3,3)) & \mu  (v(2,3)+v(3,2)) \\
 \mu  (v(1,3)+v(3,1)) & \mu  (v(2,3)+v(3,2)) & 2 \mu  v(3,3)+L (v(1,1)+v(2,2)+v(3,3)) \\
\end{smallmatrix}\right)$


text:
Q: How to smoothly interpolate colors in a Voronoi diagram to remove cell borders? I am trying to create a Voronoi diagram where the color of each cell smoothly interpolates between the colors of its nearest control points. Currently, there are visible borders between the cells in the diagram. How can I get rid of these borders and smoothly interpolate the colors of the cells?

here is a working example: https://codepen.io/miguel007/pen/BaPzxxy?editors=0011
this is the drawVoronoiNoise
function drawVoronoiNoise(canvas,cells=50,noiseScale=0.06,distortionStrength=5) {
  // Get the canvas context
  const ctx = canvas.getContext('2d');

  // Generate a random set of control points
  const controlPoints = [];
  for (let i = 0; i < cells; i++) {
    var x = seededRandom(i) * canvas.width
    var y = seededRandom(i+1) * canvas.height
    const j = noise(x/188.05, y/188.05)*255;

    controlPoints.push({
      x:x,
      y:y,
      color: {r:j ,g: j ,b: j }
    });
  }

//`rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
  const points = [];
  for (let x = 0; x < canvas.width; x++) {
    for (let y = 0; y < canvas.height; y++) {
      points.push({x, y});
    }
  }
  // For each point, find the nearest control point
  for (const point of points) {
    let nearestDistance = Infinity;
    let nearestControlPoint;
    for (const controlPoint of controlPoints) {
      // Distort the distance between the point and the control point using noise
      const noiseX = noise(point.x * noiseScale, point.y * noiseScale) * distortionStrength;
      const noiseY = noise(point.x * noiseScale + 100, point.y * noiseScale + 100) * distortionStrength;
      const distance = Math.hypot(point.x - controlPoint.x + noiseX, point.y - controlPoint.y + noiseY);
      if (distance < nearestDistance) {
        nearestDistance = distance;
        nearestControlPoint = controlPoint;
      }
    }

    // Interpolate the color of the current point based on the distance to the nearest control point
    const color = nearestControlPoint.color;
    const t = 6*nearestDistance / Math.sqrt(canvas.width ** 2 + canvas.height ** 2);
    const r = Math.round(color.r + t * (255 - color.r));
    const g = Math.round(color.g + t * (255 - color.g));
    const b = Math.round(color.b + t * (255 - color.b));
    ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
    ctx.fillRect(point.x, point.y, 1, 1);
  }
}


text:
Q: How to store an input string and use it to save a file...? How can I use the variable name from an input with the sprintf function and write it as part of the filename.
   allData = input('Introduce a variable name:','s');

   matfilename = sprintf('xcross_%d_.mat',names(k));

i.e:  During the input process I enter the variable name Hands_X
So I want to added into the filename as this:

xcross_0914_Hands_X.mat

Thank you so much advance!!!!

A: You can do this my simply adding an additional string input to sprintf
allData = input('Introduce a variable name:','s');
matfilename = sprintf('xcross_%d_%s.mat', names(k), allData);

A: Since you mentioned in the comment that you don't know how to add the variable containing the string as another argument, I'm going to explain the principle of using sprintf.
Let's have a look at the documentation accessible by doc sprintf in the command window or in the online documentation here:

str = sprintf(formatSpec,A1,...,An)

We see that sprintf takes a variable amount of arguments. In fact the number of arguments reflect - simply speaking - the number of %-constructs in the string formatSpec. So when you only have one variable that should be formatted and inserted into the output str, the command looks very simple (similar to your question):
>> A1 = 42;
>> sprintf('demo_%d',A1)
ans =
demo_42

Now we can add another variable by adding a new %-construct in the format-string and by writing the new variable containing the actual value as another argument A2.
>> A1 = 42;
>> A2 = 'test';
>> sprintf('demo_%d_%s',A1,A2)
ans =
demo_42_test

Note that I used the term %-construct as simplification for the term formatting operator. In the documentation you'll find a lot of information on how to use them.
Of course we can add some more variables and format them a bit:
>> A1 = 42;
>> A2 = 'test';
>> A3 = 0.012345;
>> A4 = 12;
>> sprintf('demo_%d_%s %.2e %X',A1,A2,A3,A4)
ans =
demo_42_test 1.23e-02 C


text:
Q: How to not break Cypress tests if element you'r looking for is not exist I have the div with classname 'okrSelectorSelect__value-container' in DOM.

This div is optional. I want to click on it and do some additional tests with block that appears after that IF IT EXIST.
I'm trying this.
cy.get('.okrSelectorSelect__value-container').then(($higherObjectivePick) => {
 if ($higherObjectivePick.length > 0) {
  $higherObjectivePick.click();
 }
});

But got this when block is not on the page

Here is my solution, but looks like there is much more beautiful ways to do that.
 cy.get('body').then($body => {
    if ($body.find('.okrSelectorSelect__value-container').length > 0) {
      cy.get('.okrSelectorSelect__value-container').click();
      cy.get('.okrSelectorSelect__option').eq(higherOrderObjectiveNumber).click();
    }
  });

A: You could use jquery operators to check the existence of an element and wrap that function as below, adding to your support.js file:
Cypress.Commands.add("checkIfClassExists", (classToFind) => {
    return Cypress.$(classToFind).length>0
})

Then in your tests:
if (cy.checkIfClassExists('.okrSelectorSelect__value-container')) {
    //do something
} else {
    //do nothing
}

A: I usually do the same like you but it would be more pretty to create a custom command for it like this:
Cypress.Commands.add("clickIfExists",(containerId , ItemId)=>{
  cy.get('body').then($body => {
    if ($body.find(containerId).length > 0) {
      cy.get(ItemId).click();
    }
  });
})

and by this way you can always call it like that if you would like to click on .okrSelectorSelect__option :
cy.clickIfExists(".okrSelectorSelect__value-container",".okrSelectorSelect__option")


text:
Q: Unicode error when inserting PDF figure into LaTeX document I receive the following error when attempting to compile a LaTeX document:
Package inputenc Error: Unicode character \GenericError {(inputenc)}{Package inputenc Error: Unicode character (U+2069)
The cause of this error is a pdf image that I created in R. The title of the figure contains greek letters and subscripts. I have changed the pdf compiler from pdfLaTex to xeLaTeX and have included \usepackage[utf8]{inputenc}, but neither works.
Has anyone had this issue and if so, how did you fix it?
Thanks,
Nate
Example Code: (test.Rnw)
\documentclass{article}
\usepackage{hyperref}
\usepackage{amsmath, bm, multirow,booktabs,mathtools}
\usepackage{setspace, relsize, booktabs, needspace, epic}
\usepackage{longtable, color, colortbl, lscape, dcolumn}
\usepackage[table]{xcolor}

\begin{document}
<<fig_test,eval=TRUE>>=
pdf("test_fig.pdf")
par(las=1, cex.axis=1.5,cex.lab=1.5,cex.main=1.5)
plot(x=c(1,5.1), y=c(0.75,3), typ='n',
main=expression(paste('X(',alpha[1],')',sep='')),ylab='',xlab='')
graphics.off()
@

\begin{figure}
\caption{Caption}
\centering
\includegraphics[scale=0.5]{"test_fig"}
\end{figure}

\end{document}

A: The error is unrelated to the pdf insertion or Greek, you have a BIDI control character  U+2069 POP DIRECTIONAL ISOLATE after test_fig"} in your source, if you retype that line just with ASCII it should be fine.
  U+0074 LATIN SMALL LETTER T     t
  U+0065 LATIN SMALL LETTER E     e
  U+0073 LATIN SMALL LETTER S     s
  U+0074 LATIN SMALL LETTER T     t
  U+005f LOW LINE     _ _ \_
  U+0066 LATIN SMALL LETTER F     f
  U+0069 LATIN SMALL LETTER I     i
  U+0067 LATIN SMALL LETTER G     g
  U+0022 QUOTATION MARK     " " "
  U+007d RIGHT CURLY BRACKET     } } \rbrace
  U+2069 POP DIRECTIONAL ISOLATE


text:
Q: jQuery text rotation function not working with parameters I searched around for a text rotation engine in jQuery, because I didn't know how to do it. I found an answer here on StackOverflow:
changing text periodically in a span from an array with jquery
The code that I found that worked:
var terms = ["term 1", "term 2", "term 3","term 4","term 5","term 6","term 3"];

function rotateTerm2() {

  console.log($("#rotate").data("term"));  //debug 1

  var ct = $("#rotate").data("term") || 0;
  console.log(ct);
  $("#rotate").data("term", ct == terms.length -1 ? 0 : ct + 1).text(terms[ct]).fadeIn()
      .delay(2000).fadeOut(400, rotateTerm2);
}
$(rotateTerm2);

This worked well and I could just add new strings to my array and edit the animation timing. However, I wanted to edit this to a function using parameters, that I can put in A script and import it when needed. I planned 4 parameters:

*

*Which element to change

*The array that contains the strings to what the text will be changed to

*The delay / the time the display will stay (simple jquery .delay)

*the fadeOut speed.

Now my code looked like this:
var terms = ["term 1", "term 2", "term 3","term 4","term 5","term 6","term 3"];

function rotateTerm(changeE,Rterms,delay,fadeSpeed) {
  var element = "#" + changeE;

  console.log(element);          //debug 1
  var ct = $(element).data("term") || 0;

  console.log($(element).data("term"));  //debug 2
  console.log(ct);            //debug 3
  $(element).data("term", ct == Rterms.length -1 ? 0 : ct + 1).text(Rterms[ct]).fadeIn()
              .delay(delay).fadeOut(fadeSpeed, rotateTerm);
}
rotateTerm("rotate",terms,2000,400);

However, this didn't work, I got an Error:

TypeError: Rterms is undefined

which real confused me, because I was sure that this would be a piece of cake just passing the values and using the value variables instead of the values themselves. So I tried debugging as seen in my code, I console.log'ged the variable I got the error and the other variables and compared them to the console.logs of the working function, and I found out that the error appears after the function ran the second time, with the outputs of the console logs being the following:

rotate  textRotate.html:44:5
  undefined  textRotate.html:52:5
  0

and then right after, the second time was this:

undefined  textRotate.html:44:5
  undefined  textRotate.html:52:5
  0

and the third time raised the error.
I noticed that the element changed to "#undefined" for some strange reason I dont understand. I thought that since the array (second parameter) raised a type error, I looked up whether I made a mistake and javascript needs some special conditions to be able to use an array as an parameter, but I think it doesnt since I didnt find any reference. I tried the ... operator thing in the parameter section for my array but it didnt work either.
Now my Question, is there any way to turn:
function rotateTerm2() {

  console.log($("#rotate").data("term"));  //debug 1

  var ct = $("#rotate").data("term") || 0;
  console.log(ct);
  $("#rotate").data("term", ct == terms.length -1 ? 0 : ct + 1).text(terms[ct]).fadeIn()
             .delay(2000).fadeOut(400, rotateTerm2);
}
$(rotateTerm2);

to a engine-like function with parameters for the element, array with values that the element is changed to, the delay and the animation speed?
I would really appreciate some help, I'm really new to jQuery and I dont get the reason why my array and my element are suddenly undefined.

A: Your fadeout wasn't being called with rotateTerm with same arguments, hence rTerms was undefined
  .fadeOut(fadeout, function(){
    rotateTerm( $element, terms, delay, fadeout )
  });

Demo

var terms = ["term 1", "term 2", "term 3"];

function rotateTerm( $element, terms, delay, fadeout )
{
  var ct = $element.data("term") || 0;
  $element.data("term", ct == terms.length - 1 ? 0 : ct + 1).text(terms[ct]).fadeIn().delay(delay)

  .fadeOut(fadeout, function(){
    rotateTerm( $element, terms, delay, fadeout )
  });
}

rotateTerm( $("#rotate"), terms, 2000, 200);

Here is a sentence this is what changes


text:
Q: How to set up different environments of Wso2 AM on a single localhost? somehow it is possible to run different environments in Wso2 API Manager like development, test and production environments on a single machine as this video shows it:
https://www.youtube.com/watch?v=wd3ubjxEM_I
I have tried it with two docker images of Wso2 called wso2/wso2am and did a offset to their ports so first runs on port 9444 and the second on 9445. I have also a local installation of Wso2 AM on my local machine on port 9443.
But they do not run independantly. When I log in myself as admin on one port, it automatically logs me out of other ports.
So how do I set up independant different environments on my local machine as in that YouTube Video? I am using the Wso2 API Manager 3.1.0 Version and Ubuntu 18.04 OS.
Thank you.

A: You cannot use the same browser as all deployments use the same cookies for the UI. Use 3 different browsers or 3 browser profiles.


text:
Q: using proxy with online flash games when I try to play this flash online game "tankionline.com" using our university proxy I get this error "Cannot establish connection (host: 62.152.57.11, ports: 4444,5190,5223,5222,5050)".
In windows I use "Microsoft Firewall Client for ISA Server" to solve this problem.
how can I solve it in ubuntu?
the problem is not from the browser because I have tried different ones and nothing worked.
thanks

A: Most proxies restrict available ports.. talk to your network admin


text:
Q: How make a list with all download URLs terminating with tar.gz within a web directory So, I want download all files terminating with tar.gz in this URL per example:
http://ns334561.ip-5-196-65.eu/~fgscenery/WS2.0/
but i need it with format of a list like:
http://ns334561.ip-5-196-65.eu/~fgscenery/WS2.0/e000n00.tar.gz
http://ns334561.ip-5-196-65.eu/~fgscenery/WS2.0/e000n10.tar.gz
http://ns334561.ip-5-196-65.eu/~fgscenery/WS2.0/e000n20.tar.gz

...

to put in my download manager.
So, how i make that list from the URL above?

A: Just solved my problem...
To do that simply install JDownloader, click "Add new address" add in URL/Address Collector the parent URL, in my case: http://ns334561.ip-5-196-65.eu/~fgscenery/WS2.0/, the deselect "auto decompress", in package name, choose a name for the save package/folder, in my case "scenery" and click "next", then in the right hand bar deselect "images" to make sure you only download the tar.gz archives in this case which is the only archive type,
Finally click "Start Download"


text:
Q: Response throwing error: Server Did not recognize the value of HTTP Header SOAPAction I am trying to test a soap url. But I am getting the error response as mentioned in the question everytime I send the soap request. My code is as shown:
public static void main(String[] args) {
    try {
        SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = sfc.createConnection();

        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage sm = mf.createMessage();
        SOAPPart soapPart = sm.getSOAPPart();

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        envelope.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");

        SOAPHeader sh = sm.getSOAPHeader();
        SOAPBody sb = sm.getSOAPBody();
        sh.detachNode();
        QName postageLabelXML = new QName("www.envmgr.com/LabelService", "GetPostageLabelXML");

        SOAPBodyElement bodyElement = sb.addBodyElement(postageLabelXML);
        QName qn = new QName("LabelRequestXML");
        SOAPElement quotation = bodyElement.addChildElement(qn);
        QName qnLabelRequest = new QName("LabelRequest");
        SOAPElement qnLabelRequestQuotation = quotation.addChildElement(qnLabelRequest);

        MimeHeaders mimeHeaders = sm.getMimeHeaders();
        mimeHeaders.addHeader("Host", "https://elstestserver.endicia.com");
        mimeHeaders.addHeader("Content-Length", "65536");
        mimeHeaders.addHeader("Content-Type", "text/xml; charset=utf-8");
        mimeHeaders.addHeader("SOAPAction", "http://www.envmgr.com/LabelService/GetPostageLabelXML");

        System.out.println("\n Soap Request:\n");
        sm.writeTo(System.out);
        System.out.println();

        URL endpoint = new URL("https://elstestserver.endicia.com/LabelService/EwsLabelService.asmx");
        SOAPMessage response = connection.call(sm, endpoint);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.writeTo(out);
        String strMsg = new String(out.toByteArray());
        System.out.println(response.getContentDescription());
        System.out.println("xml -= " + strMsg);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

The above code produces the following xml as request :
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <SOAP-ENV:Body>
      <GetPostageLabelXML xmlns="www.envmgr.com/LabelService">
         <LabelRequestXML>
            <LabelRequest />
         </LabelRequestXML>
      </GetPostageLabelXML>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The required xml is :
POST /LabelService/EwsLabelService.asmx HTTP/1.1
Host: elstestserver.endicia.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "www.envmgr.com/LabelService/GetPostageLabelXML"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetPostageLabelXML xmlns="www.envmgr.com/LabelService">
      <LabelRequestXML>
         <LabelRequest>...some xml </LabelRequest>
      </LabelRequestXML>
    </GetPostageLabelXML>
  </soap:Body>
</soap:Envelope>

After spending around 2 hours now in this issue I am not able to guess the real issue behind this error response :
    <?xml version="1.0" encoding="UTF-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"     xmlns:xsd="http://www.w3.org/2001/XMLSchema"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <soap:Body>
          <soap:Fault>
              <faultcode>soap:Client</faultcode>
              <faultstring>Server did not recognize the value of HTTP Header SOAPAction: .</faultstring>
             <detail />
          </soap:Fault>
        </soap:Body>
    </soap:Envelope>

Please let me know if any error is noticed in this code.

A: I was adding an additional 'http://' in my
mimeHeaders.addHeader("SOAPAction", "http://www.envmgr.com/LabelService/GetPostageLabelXML");

It worked fine when I removed the http:// suffix. So the changed line was
mimeHeaders.addHeader("SOAPAction", "www.envmgr.com/LabelService/GetPostageLabelXML");


text:
Q: SegmentTimeline in MP4Box Based on DASH standard, there are 4 DASH segment referencing schemes. SegmentBase, SegmentList, SegmentTemplate and SegmentTimline.
How to create a MPD file with SegmentTimeline scheme in MP4Box?
In SegmentTimeline, there is r attribute which is repetition of segment, how to generate it in MP4Box?
Thanks

A: This blog post by Romaine from gpac has some useful info:  http://www.gpac-licensing.com/2014/08/21/ibc-2014-dash-avc264-support-in-gpac/
Cheers
Will

A: You can simply use the -segment-timeline option on top of your DASH options.


text:
Q: INSERT e UPDATE em relacionamento n:m no MySQL Preciso criar um relacionamento n:m no mysql, segue meu exemplo:
Tenho uma tabela chamada empresas e outra representantes. Uma empresa pode ter mais do que um representante, e um representante pode pertencer a mais de uma empresa. Neste caso, o melhor relacionamento que se encaixa para este problema, é o relacionamento n:m.
No relacionamento n:m, existe uma terceira tabela unindo o representante e uma empresa. Como posso fazer um INSERT e um UPDATE nesta terceira tabela de forma recursiva, sem duplicar os registros, sabendo que ao cadastrar uma empresa, eu tenho vários representantes, e vice-versa?

A: Eu não sei se entendi bem a necessidade, mas acho que seria:
insert into empresas_has_representantes (empresas_id, representantes_id) values (<id da empresa>, <id do representante>)

A forma de persistência destes dados depende muito do que voce está usando pra gerenciar sua camada de data access.
No hibernate, por exemplo, existe um tipo de relacionamento @ManyToMany que trata isso pra voce automaticamente. Alguma coisa a respeito voce le aqui
Se voce usa JDBC puro, ou acesso ao banco puro, voce precisa iterar seus dados e tratar isso de forma manual, usando a query que eu postei acima pra colocar as relações.
Obviamente antes de persistir a relação, voce precisa persistir as empresas e/ou os representantes.
Quanto a duplicidade, voce pode garantir via banco, inserindo uma constraint de unique das duas colunas. Mais informações aqui