text:
Q: Postgres, update and lock ordering I'm working on Postgres 9.2.
There are 2 UPDATEs, each in their own transactions.  One looks like:
UPDATE foo SET a=1 WHERE b IN (1,2,3,4);

The other is similar:
UPDATE foo SET a=2 WHERE b IN (1,2,3,4);

These could possibly run at the same time and in reality have 500+ in the 'IN' expression.
I'm sometimes seeing deadlocks.  Is is true that that order of items in the 'IN' expression may not actually influence the true lock ordering?

A: Yes. I think the main issue here is that IN checks for membership in the set specified, but does not confer any sort of ordering on the UPDATE, which in turn, means that no concrete ordering is conferred upon the lock ordering.
The WHERE clause in an UPDATE statement essentially behaves the same way it does in a SELECT. For example, I will often simulate an UPDATE using a SELECT to check what will be updated to see that it's what I expected.
With that in mind, the following example using SELECT demonstrates that IN does not in itself confer ordering:
Given this schema/data:
create table foo
(
  id serial,
  val text
);

insert into foo (val)
values ('one'), ('two'), ('three'), ('four');

The following queries:
select *
from foo
where id in (1,2,3,4);

select *
from foo
where id in (4,3,2,1);

yield the exact same results -- the rows in order from id 1-4.
Even that isn't guaranteed, since I did not use an ORDER BY in the select. Rather, without it, Postgres uses whatever order the server decides is fastest (see point 8 about ORDER BY in the Postgres SELECT doc). Given a fairly static table, it's often the same order in which it was inserted (as was the case here). However, there's nothing guaranteeing that, and if there's a lot of churn on the table (lots of dead tuples, rows removed, etc.), it's less likely to be the case.
I suspect that's what's happening here with your UPDATE. Sometimes -- if not even most of the time -- it may end up in numerical order if that's the same way the rows were inserted, but there's nothing to guarantee that, and the cases where you see the deadlocks are likely scenarios where the data has changed such that one update is ordered different than the other.
sqlfiddle with the above code.
Possible fixes/workarounds:
In terms of what you could do about it, there are various options, depending on your requirements. You could explicitly take out a table lock on the table, although that would of course have the effect of serializing the updates there, which may prove to be too large a bottleneck.
Another option, which would still allow for concurrency -- is to explicitly iterate over the items using dynamic SQL in, say, Python. That way, you'd have a set of one-row updates that occurred always in the same order, and since you could ensure that consistent order, the normal Postgres locking should be able to handle the concurrency without deadlocking.
That won't perform as well as batch-updating in pure SQL, but it should solve the lock issue. One suggestion to bump up performance is to only COMMIT every so often, and not after every single row -- that saves a lot of overhead.
Another option would be to do the loop in a Postgres function written in PL/pgSQL. That function could then be called externally, in, say, Python, but the looping would be done (also explicitly) server-side, which may save on some overhead, since the looping and UPDATEs are done entirely server-side without having to go over the wire each loop iteration.

A: There is no ORDER BY in the UPDATE command.
But there is for SELECT. Use row-level locking with the FOR UPDATE clause in a subquery:
UPDATE foo f
SET    a = 1
FROM (
   SELECT b FROM foo
   WHERE  b IN (1,2,3,4)
   ORDER BY b
   FOR   UPDATE
   ) upd
WHERE f.b = upd.b;
Of course, b has to be UNIQUE or you need to add more expressions to the ORDER BY clause to make it unambiguous.
And you need to enforce the same order for all UPDATE, DELETE and SELECT .. FOR UPDATE statements on the table.
Related, with more details:

*

*Postgres UPDATE … LIMIT 1

*Avoiding PostgreSQL deadlocks when performing bulk update and delete operations

*Optimizing concurrent updates in Postgres


text:
Q: Identifying the original email from user's reply I am developing an application which enables the user to do a reply via email. However, when a user replies to an email, the original email is also appended to the user's response.
This original email text is being appended in different ways for different clients. For gmail it starts as

On Tue, Jan 4, 2011 at 6:24 PM, User
   wrote:

Like wise it's different for each client.
Is there any way to identify the original email text from user's reply?

A: There are three popular ways of tracing the parent of an email message, all done via the message headers rather than the message body.
The In-Reply-To header, when present, should contain the value of the Message-ID header of the parent message.
The References header, when present, should contain a space-separated list containing some of the message-ids of the message's ancestors, ordered from oldest to most recent.  The last one in the header should be the value of the Message-ID header of the parent message.
The non-standard Thread-Index header is Microsoft Outlook-specific.  When present, it contains a base64-encoded value.  If you decode this value, remove the last 5 bytes from the resulting byte array, and re-base64-encode the result, you'll have the value of the Thread-Index header of the parent message -- if the parent had a Thread-Index header.

redpajama_set_name: RedPajamaStackExchange


text:
Q: DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported IMPORTANT: Works fine in localhost, but not on a live server. (Godadddy)
Issue:

Wordpress plugin is giving an error when "preview" button clicked which is not giving the same error on localhost.

Error:

Uncaught DOMException: Failed to execute 'toDataURL' on
  'HTMLCanvasElement': Tainted canvases may not be exported.

Line of Error:
var data = canvasObj.toDataURL()

Initialisation of canvasObj:
canvasObj= new fabric.Canvas('wtd_background_image');

Setting image to canvasObj:
  function wtd_load_bg_image( img_url )
  {
    if( img_url )
    {
      var bg_img = new Image();
      bg_img.setAttribute('crossOrigin', '');
      bg_img.onload = function()
      {
        canvasObj.setBackgroundImage(bg_img.src, canvasObj.renderAll.bind(canvasObj), {
          originX: 'left',
          originY: 'top',
          left: 0,
          top: 0
        });
      };
      bg_img.src = img_url;
    }
  }

Solutions I found online, which are did not work:
Modifing htaccess file (Did Not Work!)
<IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
        <FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
            SetEnvIf Origin ":" IS_CORS
            Header set Access-Control-Allow-Origin "*" env=IS_CORS
        </FilesMatch>
    </IfModule>
</IfModule>

Adding a PHP Header (Did Not Work!)
adding 'Access-Control-Allow-Origin: *' to top of the plugin's page as below:
<?php
require_once('../../../../wp-load.php');
//header('HTTP/1.1 200 OK');
header('Access-Control-Allow-Origin: *');
get_header();

Adding a crossorigin attribute to image (Did Not Work)
I added below code to image as you can see above
bg_img.setAttribute('crossOrigin', '');

Changin the version of Fabric.js (Works Partially)
Changing the Fabric.js version from 1.2.0 to different version, this error goes away, but new ones occur. So I don't prefer.

A: Upgrade to 1.7.9, and solve other issues.


text:
Q: Modification of Magento 2 database core table I am getting this error in UpgradeSchema. I have added one column in these core tables, functionalities are working good. According to coding standard it shows warning message.
 ----------------------------------------------------------------------
     60 | WARNING | Modification of magento database core table
        |         | 'sales_order'
     78 | WARNING | Modification of magento database core table
        |         | 'sales_order_grid'
 ----------------------------------------------------------------------

I have attached my code below
<?php
namespace frontname\modulename\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class UpgradeSchema implements UpgradeSchemaInterface
{
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $customerGroupTable = $setup->getConnection()->describeTable($setup->getTable('customer_group'));
        $customerGroupIdType = $customerGroupTable['customer_group_id']['DATA_TYPE'] == 'int'
            ? \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER : $customerGroupTable['customer_group_id']['DATA_TYPE'];
        $installer->startSetup();
        if (version_compare($context->getVersion(), '2.0.1') < 0) {
            $eavTable = $installer->getTable('sales_order');
            $columns = [
                'is_wallet_quote' => [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                    'nullable' => false,
                    'comment' => 'Is this quote for wallet?',
                ],
                'holded_quote_id' => [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                    'nullable' => false,
                    'comment' => 'Holded Quote Id',
                ],

            ];
            $connection = $installer->getConnection();
            foreach ($columns as $name => $definition) {
                $connection->addColumn($eavTable, $name, $definition);
            }
            $eavTable = $installer->getTable('sales_order_grid');
            $columns = [
                'is_wallet_quote' => [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                    'nullable' => false,
                    'comment' => 'Is this quote for wallet?',
                ],
            ];
            $connection = $installer->getConnection();
            foreach ($columns as $name => $definition) {
                $connection->addColumn($eavTable, $name, $definition);
            }
        }
        $installer->endSetup();
    }
}

Anyone have any idea about this?
Thanks in Advance

A: It is not considered a good practice to add or update anything in the structure of Magento.
A better way to do this is to add a new table of your own and add the elements needed as foreign keys if you need anything.
A good explanation is here (However, the explanation was in regards to Magento1, but I think the standard shall remain the same.)
An example to do this can be:-
addForeignKey(
                $installer->getFkName(
                    'yourTable',
                    'yourTable_id',
                    'catalog_product_entity',
                    'entity_id'
                ),
                'entity_id',
                $installer->getTable('catalog_product_entity'),
                'entity_id',
                \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
            )


text:
Q: TreeView tab navigation I have an UserControl with a Grid that contain a simple TreeView. I'm able to navigate in forward direction (Tab) while in backwards direction (Alt+Tab) not working. (It's focus the last button in my item template).
Do you have any suggestions?
    <TreeView ItemsSource="{Binding myList}"
          KeyboardNavigation.TabNavigation="Continue" TabIndex="4" IsTabStop="False">

  <TreeView.ItemContainerStyle>
    <Style TargetType="{x:Type TreeViewItem}">
      <Setter Property="IsExpanded" Value="True" />
      <Setter Property="KeyboardNavigation.TabNavigation" Value="Continue"/>
    </Style>
  </TreeView.ItemContainerStyle>

  <TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding MySubList}">
      <TextBlock Text="{Binding Name}" FontWeight="Bold"/>

      <HierarchicalDataTemplate.ItemTemplate>
        <HierarchicalDataTemplate>
          <Grid KeyboardNavigation.TabNavigation="Local">

            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="Auto" SharedSizeGroup="Col1"/>
              <ColumnDefinition Width="5"    SharedSizeGroup="Col2"/>
              <ColumnDefinition Width="*"/>
              <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>
              <RowDefinition Height="Auto"/>
              <RowDefinition Height="Auto"/>
              <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <GridSplitter Grid.Column="1" Grid.RowSpan="2147483647" Width="5" HorizontalAlignment="Left" VerticalContentAlignment="Stretch" IsTabStop="False"/>

            <TextBlock Grid.Column="0" Grid.Row="0" Text="Text1"/>
            <TextBox   Grid.Column="2" Grid.Row="0" Text="{Binding Text1, UpdateSourceTrigger=LostFocus}" TabIndex="0"/>
            <Button    Grid.Column="3" Grid.Row="0" Content="..." TabIndex="1"/>
          </Grid>
        </HierarchicalDataTemplate>
      </HierarchicalDataTemplate.ItemTemplate>
    </HierarchicalDataTemplate>
  </TreeView.ItemTemplate>
</TreeView>


text:
Q: Помогите пожалуйста найти ошибку в docker-compose конфиге
Всем привет, делаю тут задание одно, docker-compose ругается на отсутствие доветочий в строке "maria_db:". Ошибка: yaml: line 17: could not find expected ':', можете подсказать, в чём может быть ошибка?

A: Засунул config в yaml линтер, были скрытые символы.


text:
Q: How to create inverse png image? i am creating png image which painted on my base, from the base i can save a png image, for your reference
Graphics g = e.Graphics;
 ....
g.DrawLine(pen, new Point(x, y), new Point(x1, y1));
 .....
base.OnPaint(e);

using (var bmp = new Bitmap(500, 50))
{
    base.DrawToBitmap(bmp, new Rectangle(0, 0, 500, 50));
    bmp.Save(outPath);
}

this is single color transparency image, now how do i can inverse this image like png filled with any color and the real image portion should be transparent, is there any possibilities?
bit detail : so transparent will go nontransparent and where there is fill will go to transparent

A: There's a faster way if you're willing to use unsafe code:
private unsafe void Invert(Bitmap bmp)
{
    int w = bmp.Width, h = bmp.Height;
    BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

    int* bytes = (int*)data.Scan0;
    for ( int i = w*h-1; i >= 0; i-- )
        bytes[i] = ~bytes[i];
    bmp.UnlockBits(data);
}

Note that this doesn't care about the colors and will invert those as well. If you wish to use a specific color, then the code will have to be modified a bit.

A: EDIT (thanks for Thomas notation)
public void ApplyInvert()
{
    byte A, R, G, B;
    Color pixelColor;

    for (int y = 0; y < bitmapImage.Height; y++)
    {
        for (int x = 0; x < bitmapImage.Width; x++)
        {
            pixelColor = bitmapImage.GetPixel(x, y);
            A = (byte)(255 - pixelColor.A);
            R = pixelColor.R;
            G = pixelColor.G;
            B = pixelColor.B;
            bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));
        }
    }
}

from here : Image Processing in C#: Inverting an image

A: For anyone who wants a fast method for inverting Bitmap colors without using unsafe:
public static void BitmapInvertColors(Bitmap bitmapImage)
{
    var bitmapRead   = bitmapImage.LockBits(new Rectangle(0, 0, bitmapImage.Width, bitmapImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);
    var bitmapLength = bitmapRead.Stride * bitmapRead.Height;
    var bitmapBGRA   = new byte[bitmapLength];
    Marshal.Copy(bitmapRead.Scan0, bitmapBGRA, 0, bitmapLength);
    bitmapImage.UnlockBits(bitmapRead);

    for (int i = 0; i < bitmapLength; i += 4)
    {
        bitmapBGRA[i]     = (byte)(255 - bitmapBGRA[i]);
        bitmapBGRA[i + 1] = (byte)(255 - bitmapBGRA[i + 1]);
        bitmapBGRA[i + 2] = (byte)(255 - bitmapBGRA[i + 2]);
        //        [i + 3] = ALPHA.
    }

    var bitmapWrite = bitmapImage.LockBits(new Rectangle(0, 0, bitmapImage.Width, bitmapImage.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb);
    Marshal.Copy(bitmapBGRA, 0, bitmapWrite.Scan0, bitmapLength);
    bitmapImage.UnlockBits(bitmapWrite);
}

Bitmap GetPixel and SetPixel are extremly slow, this method works by copying the Bitmap pixels into a byte array, which you can then loop through and change, before finally copying the pixels back.

A: When you say invert the transparent sections into color, are you storing the real colors in the PNG image just set to full transparency? A lot of programs will optimize a png by removing the color data from transparency so you can't reverse it.
Colors can be converted to transparency
But transparency (without underlying colors) cannot be converted to color.
If your lucky your PNG will be non optimized and still have the original color data intact, but if your doing this from user input then it won't work for a high percentage of cases.


text:
Q: Grant Select Privileges for a user not working? I am using mysql 5.0.86 in windows machine . I am creating a user with select privileges only .
Query
Grant select on *.* to 'readonly'@'%' identified by 'readonly';
Flush privileges;

MYSQL Table Output
 ************************** 1. row ***************************
                Host: %
                User: readonly
            Password: *922A4B420903CAD4E7FC56A23122AB927E051FE3
         Select_priv: Y
         Insert_priv: Y
         Update_priv: Y
         Delete_priv: Y
         Create_priv: Y
           Drop_priv: Y
         Reload_priv: Y
       Shutdown_priv: Y
        Process_priv: Y
           File_priv: Y
          Grant_priv: Y
     References_priv: Y
          Index_priv: Y
          Alter_priv: Y
        Show_db_priv: Y
          Super_priv: Y
reate_tmp_table_priv: Y
    Lock_tables_priv: Y
        Execute_priv: Y
     Repl_slave_priv: Y
    Repl_client_priv: Y
    Create_view_priv: Y
      Show_view_priv: Y
 Create_routine_priv: Y
  Alter_routine_priv: Y
    Create_user_priv: Y
            ssl_type:
          ssl_cipher:
         x509_issuer:
        x509_subject:
       max_questions: 0
         max_updates: 0
     max_connections: 0
max_user_connections: 0

After this , I am trying to login with the created username .
>mysql -ureadonly -preadonly
ERROR 1045 (28000): Access denied for user 'readonly'@'localhost' (using password: YES)

Why it's not working ?

A: Please login without password

mysql -ureadonly

A: You created user 'readonly'@'%', but connected as 'readonly'@'localhost', because  'localhost' is default host.
You need to specify --host (-h) option  in command line.
mysql -u readonly -preadonly -h <host_name>


text:
Q: Keyboard shortcut to focus the file list in Dolphin? When using Dolphin, I often end up with focus on the "Places" left-panel. Moving keyboard focus to the main file list is a horrible process, involving pressing Tab once per entry in the location breadcrumbs bar.
Is there any keyboard shortcut to move focus directly to the file panel?
How to switch pane in Dolphin using keyboard? explains how to move keyboard focus between the left/right pane, using Tab. However Tab does not move focus from Places to the file pane.

A: Although, 2 shortcuts, I believe the fastest way would be CTRL+L to select the address bar and then press TAB once to jump to the file list.

A: At first, I had a hard time recreating this problem because I only display the Places panel and the Files panel. This way the focus is always on the Files panel. I had to open another panel to get it to go somewhere else.
You can use a tool such as AutoKey to achieve the desired result using desktop automation.
I just played around with Dolphin for a minute and found two sequences (of many that are probably possible):
Ctrl+F (opens the Find panel)
Esc    (closes the Find panel and leaves me in the Places panel - a fixed starting point)
Tab 5 times takes me to the Files panel

or

Just press the hotkey for Places. By default, it's assigned to F9
and then the five Tabs

A sequence such as this is easy to define in an AutoKey script triggered by the hotkey of your choice.
You might be able to send all the keys as one sequence, but, more likely, you may have to send them one at a time with small delays between them because AutoKey emits the keystrokes at machine speed and sometimes applications can't keep up.
The only issue with an approach like this is that it is "hard-coded" and if the Dolphin page layout changes over time/releases, it may need to be adjusted.
To address this, AutoKey offers a second approach which is a bit more involved. It has a visual grep feature from the Xautomation project.
If you can identify a distinguishing feature of the Files panel (this works better for other targets), you can take and save a small rectangular screenshot of the feature and tell AutoKey to find it on the display and put the mouse cursor there. You can then have it click the left mouse button to bring the focus there.
Doing this with the Files panel is a bit tricky because it doesn't have a lot of fixed distinguishing features to search for, but, depending on what else is on your screen, you might get away with a picture of just the upper left hand corner of the Files panel border.
If you explore AutoKey, you will find that it can also do many other similar and much more complicated tasks as the need arises.

A: I found that pressing F3 twice (to show and hide the "second file pane") focuses the file list.

A: Pressing Shift+Tab two times skips between the panel and list of files. For some reason the first movement in the panel has to be done with left/right arrow keys.


text:
Q: Appengine model filtering problem I've got an entity class:
class User(db.Model):
    local = db.TextProperty(required=True)
    jid = db.TextProperty(required=True)

Later in code I'm checking if a user exists:
def parseMessageFromJid(self, message, mesFrom) :
        #user = User.all().filter(' jid', mesFrom.lower().strip()).get()
        user = db.GqlQuery("SELECT * FROM User " +
                "WHERE jid = :1",
                mesFrom.lower().strip()).get()
    if user is None :
      if message.body.strip().lower().find("register") != 0 :
        message.reply(HELP_MSG)
      elif message.body.strip().lower().find("register") == 0 :
        uname = message.body.strip().replace("register ", "", 1).replace(" ", "") + "@mybot.com"
        user = User(jid=mesFrom,local=uname)
        user.put()
        message.reply("Ok. You are now registered.")
    else :
      # User registered, proceed
      self.send_to_bots(message, user.local)

I tried both approaches: gql and the commented code. Both approaches return None, althought the user is there: I can see it in my console and it is there when I do User.all(). What am I missing here?

A: TextProperty is not indexed.
Use StringProperty


text:
Q: EdgeCollider2D wall not preventing objects from going off screen I am trying to create an EdgeCollider2D script for my game. From the code below it is suppose to cover part of the left and right ends of the main camera. The left side wall is working and objects are prevented from moving left but the right side wall doesn't prevent objects from going off the screen. I am not too sure what's causing it.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GameEdgeScript : MonoBehaviour {

// lets make verticies for the edge collider 2d
List<Vector2> newVerticies = new List<Vector2>();
EdgeCollider2D col;

// Use this for initialization
void Awake () {

    col = gameObject.AddComponent<EdgeCollider2D>();

    Camera camera = GameObject.FindGameObjectWithTag ("MainCamera").GetComponent<Camera> ();
    Vector3 screenSize = camera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, camera.nearClipPlane));

    float height1 = GameObject.FindGameObjectWithTag ("spriteHigh").GetComponent<SpriteRenderer> ().sprite.rect.height/2;
    float height2 = Screen.height*((float)0.8) + GameObject.FindGameObjectWithTag ("spriteLow").GetComponent<SpriteRenderer> ().sprite.rect.height/2;

    newVerticies.Add( (Vector2)camera.ScreenToWorldPoint(new Vector3(0, height1, camera.nearClipPlane)));
    newVerticies.Add( (Vector2)camera.ScreenToWorldPoint(new Vector3(0, height2, camera.nearClipPlane)));
    newVerticies.Add( (Vector2)camera.ScreenToWorldPoint(new Vector3(Screen.width, height2, camera.nearClipPlane))); // NOT BLOCKING OBJECTS AT THE RIGHT X VALUE (Screen.width)
    newVerticies.Add( (Vector2)camera.ScreenToWorldPoint(new Vector3(Screen.width, height1, camera.nearClipPlane)));// NOT BLOCKING OBJECTS AT THE RIGHT X VALUE (Screen.width)

    Debug.Log (Screen.width);

    getPointsToDebug ();

    setPoints ();

    for (int i = 0; i<col.points.Length; i++) {
        Debug.Log (col.points[i]);
    }

void getPointsToDebug() {
    foreach (Vector2 piste in col.points) {
        Debug.Log(piste);
    }
}

void setPoints() {
    col.points = newVerticies.ToArray();
    }

}


text:
Q: What will be the best way to update my NSString with appropriate NSArray value I am trying to update my NSString value with the following code.
  NSString *string =[NSString stringWithFormat:@"array[0]%@",[array componentsJoinedByString:@"[0]"]];

This is the result I got.
array[0]1array[0]2array[0]3

However, I need this result, basically the number inside the brackets will be updated based on the number of objects in the NSMutablearray.
array[0]1array[1]2array[2]3

I tried using a for loop with [NSString stringWithFormat:@"[%i]", i], but it seem to not have worked.

A: Untested:
NSMutableString *finalString = [[NSMutableString alloc] init];

[array enumerateObjectsUsingBlock:^(NSString *str, NSUInteger idx, BOOL *stop) {
    [finalString appendFormat:@"[%lu]%@", (unsigned long)idx, str];
}];

// do stuff with finalString


text:
Q: Why does the iteration not work here in cuda? I tried to implement Jacobi method for 1D Poisson's equation using CUDALink.
The kernel is (I use only 1 block):
__global__ void jacobi(float *out, float *in, mint n)
{
    __shared__ float smem[BLOCK_DIM];
    int idx = threadIdx.x + blockIdx.x * blockDim.x;

    if(idx < n)
        smem[threadIdx.x] = in[idx];
    else
        smem[threadIdx.x] = in[n - 1];

    __syncthreads();

    if(threadIdx.x < BLOCK_DIM - 1 && threadIdx.x > 0)
    {
        //the iteration is here*************
        for(int i = 0; i < 100000; i++)
        {
            smem[threadIdx.x] = (smem[threadIdx.x - 1] + smem[threadIdx.x + 1])/2 + 0.001;
        }
    }

    __syncthreads();
    if(idx < n)
        out[idx] = smem[threadIdx.x];

    return;
}

Ideal:
Since smem[] is shared between threads and which run in parallel, later iterations will use smem[] values generated by earlier iterations. Thus, although iterations between threads are not ordered perfectly, smem[] will converge to the solution more or less.
Real:
It seems that the threads have their own caches, so once they fetch their smem[threadIdx.x - 1]s and smem[threadIdx.x + 1]s, they will not do it again any longer(, but the essence is that smem[] values are changing!).

Later, I found a costly solution to the problem. Threads were synchronized after each iteration:
for(int i = 0; i < 100000; i++)
{
    smem[threadIdx.x] = (smem[threadIdx.x - 1] + smem[threadIdx.x + 1])/2 + 0.001;
    __syncthreads();
}

But the synchronizations made the iterations runs at only ~2MHz on my 1GHz GPU.

Are there any other solutions?


text:
Q: How do you find the minimum and maximum to see if they match? How do you find the minimum and maximum to see if they match? But the thing I'm finding the minimum and maximum for integers that are not an array. I need to find the minimum and maximum of the averages and compare them. So far I have this:
        int i;
        int totalall = 0;
        int total1 = 0;
        int total2 = 0;
        int total3 = 0;
        int total4 = 0;
        int min1 = Integer.MAX_VALUE, minIndex = 0;
        int max1 = Integer.MIN_VALUE, maxIndex = 0;
        int average1 = 0;
        int average2 = 0;
        int average3 = 0;
        int average4 = 0;

        System.out.print("Please enter the sample size: ");
        int max = input.nextInt();
        int[]arr0 = new int[max + 1];
        int[]arr1 = new int[max + 1];
        int[]arr2 = new int[max + 1];
        int[]arr3 = new int[max + 1];
        System.out.println("Enter numbers for Trial 0 ");
        for (i = 1;i <= max;i++){
            System.out.print("Enter sample #" + (i-1) + ":");
            arr0[i-1]= input.nextInt();
            total1 = total1 + arr0[i-1];
            }
        System.out.println("Enter numbers for Trial 1 ");
        for (i = 1; i <= max; i++){
            System.out.print("Enter sample #" + (i-1) + ":");
            arr1[i-1] = input.nextInt();
            total2 = total2 + arr1[i-1];
            }
        System.out.println("Enter numbers for Trial 2 ");
        for (i = 1; i <= max; i++){
            System.out.print("Enter sample #" + (i-1) + ":");
            arr2[i-1] = input.nextInt();
            total3 = total3 + arr2[i-1];
            }
        System.out.println("Enter numbers for Trial 3 ");
        for (i = 1; i <= max; i++){
            System.out.print("Enter sample #" + (i-1) + ":");
            arr3[i-1] = input.nextInt();
            total4 = total4 + arr3[i-1];
            }
        totalall += total1 + total2 + total3 + total4;
        average1 = total1 / (i-1);
        average2 = total2 / (i-1);
        average3 = total3 / (i-1);
        average4 = total4 / (i-1);

        System.out.println("\tSample #\tTrial 0\tTrial 1\tTrial 2\tTrial 3");
        System.out.println("\t\t" + arr3[max] + "\t" + arr0[i-2] + "\t" + arr1[i-2] + "\t" + arr2[i-2] + "\t" + arr3[i-2]);
        System.out.print("Average: \t\t");
        System.out.println(average1 + "\t" + average2 + "\t" + average3 + "\t" + average4);

        for (i=1; i < average; i++);

    }
}

A: Perhaps this:
var averages = new List<int>(){average1,average2,average3,average4};
var maxAvg = averages.Max();
var minAvg = averages.Min();

A: do you need this?
import java.util.Scanner;

public class test {

    public static void main(String[] args) {
        int max = 0;
        int min = 0;
        int total = 0;
        int avg = 0;
        float count = 0;
        String input = "";

        Scanner scanner = new Scanner(System.in);
        while (!(input = scanner.nextLine()).equals("end")) {

            if(max < Integer.parseInt(input))
                max = Integer.parseInt(input);
            else if(min > Integer.parseInt(input))
                min = Integer.parseInt(input);
            if(count == 0)
                max = min = Integer.parseInt(input);
            total += Integer.parseInt(input);
            count++;
        }
        System.out.println("max: " + max);
        System.out.println("min: " + min);
        System.out.println("total: " + total);
        System.out.println("avg: " + total / count);
    }

}

A: To find the minimum of a list of variables (which are not an array) you can let java syntax help you:
The NumberUtils class comes from Apache Commons-Lang library
public class ArrayTest {

    public static int min(int ... value)
    {
        return org.apache.commons.lang.math.NumberUtils.min(value);
    }
    public static int max(int ... value)
    {
        return org.apache.commons.lang.math.NumberUtils.max(value);
    }

    public static void main(String[] args) {
        int average1=4, average2=20, average3=40;
        System.out.println("minimum:"+min(average1,average2,average3));
        System.out.println("maximum:"+max(average1,average2,average3));
    }
}


text:
Q: Why does HTML5 video not work in the new Windows version of Safari? I've tested on several installations of Safari 5.1.7 for Windows and I can't seem to get HTML5 videos to play.
I've been testing with this:
Basic HTML5 video test
It seems to work on Safari 5.1.7 for Mac and also earlier 5.0.x installations of Safari on Windows. Am I missing something?

A: Managed to fix this. For anyone else encountering similar problems, note that Safari requires quicktime in order to play HTML5 video/audio. If you've upgrade to a later version of Safari and notice that HTML5 video/audio stops working, you may also need to upgrade to the latest version of quicktime.


text:
Q: Do color-neutral gluons exist? If I'm correct a quark can change color by emitting a gluon. For example a blue up quark $u_b$ can change into a red up quark by emitting a gluon:
$$u_b \longrightarrow u_r + g_{b\overline{r}}$$
(Here, the subscript indicates color and $\overline{r}$ means anti-red). This is needed to keep the color balance (left hand side: $b$, right hand side $r+b+\overline{r}=b$).
My question is then, do color-neutral gluons exist? Eg a gluon that is blue-anti-blue?
If it would, it could be created by any quark then:
$$u_b \longrightarrow u_b + g_{b\overline{b}}$$
I'm learning about the Standard Model in school, but the text isn't always that clear.

A: Color-neutral gluons that have the component blue-antiblue do exist, much like red-antired and green-antigreen. However, the sum of these three possible kinds of gluons is unphysical, so there are only two "diagonal" types of gluons. None of these two types of gluons are "genuinely color-blind" or "completely color-neutral".
This is more manifest if you realize that the color dependence of the gluon field may be written as a traceless $3\times 3$ Hermitian matrix. It is traceless because the gauge group is $SU(3)$ rather than $U(3)$ whose dimension is 8 rather than 9. (There are 3 complex entries strictly above the diagonal, which are copied in the complex conjugate way beneath the diagonal, plus 2 or 3 real entries on the diagonal, depending on whether we require the trace to vanish.)
Completely color-neutral gluons, if they were added, would be proportional to the identity matrix and they would couple to all three colors of the quarks equally. In other words, the interactions mediated by such gluons would only depend on the baryon number of the quarks. Experimentally, this interaction doesn't exist. In beyond-the-Standard-Model physics, one may try to extend $SU(3)$ to $U(3)$ in this way (this is very common in braneworld models) but because no new baryon-charge long-distance interaction is seen, the $U(1)$ in the $U(3)$ has to be spontaneously broken at a pretty high energy scale.


text:
Q: How to append to a String and send through intents in Android? I am trying to add values to a string and then send it to the next activity. Here is the only relevant part of the code. adding() is the id of the button which appends values to the String msg and sendMessage() sends the msg altogether. When I just send a dummy value, the message is being passed, even when I add something like 1,2,3,4,5 at once instead of adding, it goes. But when I try to add, append and then send, it gives me an "Unfortunately stopped" error.

I tried couple of tweaks, but still the same error. How to fix this?
public void adding(View view){
    EditText et1=(EditText) findViewById(R.id.editText1);
    msg=msg+","+et1.getText().toString();
    TextView tv1=(TextView) findViewById(R.id.textView1);
    tv1.setText(msg);

    et1.setText("");

}
public void sendMessage(View view){

    Intent intent=new Intent(this,Next.class);
    msg+=",";
    intent.putExtra("message", msg);
    startActivity(intent);
}

EDIT: Activity Code-
package com.example.newlist;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
    String msg="";
    int count=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    public void adding(View view){
        EditText et1=(EditText) findViewById(R.id.editText1);
        msg=msg+","+et1.getText().toString();
        TextView tv1=(TextView) findViewById(R.id.textView1);
        tv1.setText(msg);

        et1.setText("");

    }
    public void sendMessage(View view){

        Intent intent=new Intent(this,Next.class);
        msg+=",";
        intent.putExtra("message", msg);
        startActivity(intent);
    }
    }

A: Not sure I understand your question correctly

*

*move your findViewById to onCreate
EditText et1;
TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    et1=(EditText) findViewById(R.id.editText1);
    tv1=(TextView) findViewById(R.id.textView1);
}

*in your adding method do it like this
public void adding(View view){
    msg = msg + "," + et1.getText().toString();
    final String showMessage = msg;
    tv1.setText(showMessage);

    et1.setText("");
}

*in your sendMessage
public void sendMessage(View view){
    Intent intent=new Intent(this,Next.class);
    msg+=",";
    final String msgThatWillSend = msg;
    intent.putExtra("message", msgThatWillSend);
    startActivity(intent);
}

didn't test yet, but it should be work

A: try this :
ActivityA.java
public class ActivityA extends Activity{

    StringBuilder msg=new StringBuilder();
    private EditText et1;
    private TextView tv1;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        et1=(EditText)findViewById(R.id.et1);
        tv1=(TextView)findViewById(R.id.tv1);

    }

    public void adding(View view){

        msg.append(" "+et1.getText().toString());

        tv1.setText(msg);

        et1.setText("");

    }
    public void sendMessage(View view){

        Intent intent=new Intent(this,Next.class);

        intent.putExtra("message", msg.toString());
        startActivity(intent);
    }

}

Next.java
public class Next extends Activity{

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.next);

        TextView tv = (TextView)findViewById(R.id.textView1);

        tv.setText(getIntent().getStringExtra("message"));

    }

}

test.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"

>

<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:gravity="center"
  android:text=""
    android:textSize="12sp" />

<EditText
    android:id="@+id/et1"
    android:layout_width="200dip"
    android:layout_height="wrap_content"
    android:text="" />

<Button
    android:id="@+id/btnadd"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:onClick="adding"
    android:text="adding"

    />

<Button
    android:id="@+id/btnsent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:onClick="sendMessage"
    android:text="SendMessage" />

</LinearLayout>

next.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

 >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:gravity="center"
    android:text="msg"
    android:textSize="25sp" />

</LinearLayout>


text:
Q: Modify the last row of each group in pandas MultiIndex DataFrame I have a sample multi index dataframe below (actual much larger).  I want to set the last row of each level = 0 index in the column 'col' to 100.  Dataframe like this
mux = pd.MultiIndex.from_arrays([
list('aaabbbcccddd'),
list('tuvwacdjpkqz')],
names=['level 0', 'level 1'])
df = pd.DataFrame({'col': np.arange(len(mux))}, mux)
df

So the 2,5,8 and 11 wold all be replaced with 100.  I have tried these solution but I dont know how to set the value properly.  I can get the boolean series and the dataframe of the last rows but cant seem to figure out how to set them to the new value.  What I have tried below
df.groupby(level=0).tail(1).col = 100
df.groupby(level=0).tail(1).col
df.iloc[-1, df.columns.get_loc('col')] = 100

The last line of code was from a previous post but it only sets the last row of df, not at the index level

A: You were close, use loc with the index of your result and assign:
df.loc[df.groupby(level=0).tail(1).index, 'col'] = 100
df

                 col
level 0 level 1
a       t          0
        u          1
        v        100
b       w          3
        a          4
        c        100
c       d          6
        j          7
        p        100
d       k          9
        q         10
        z        100

This is your groupby result:
df.groupby(level=0).tail(1)

                 col
level 0 level 1
a       v          2
b       c          5
c       p          8
d       z         11

Get the indices of the rows you want to change with .index:
df.groupby(level=0).tail(1).index

MultiIndex([('a', 'v'),
            ('b', 'c'),
            ('c', 'p'),
            ('d', 'z')],
           names=['level 0', 'level 1'])

You have index labels, so you will need loc (not iloc) for the final assignment step.


text:
Q: Hatcher Exercise 3.2.11 I'm having trouble doing exercise 3.2.11 at page 231 of Hatcher. It states:

Using cup products, show that every map $S^{k+l}\to S^k\times S^l$ induces the trivial homomorphism $H_{k+l}(S^{k+l})\to H_{k+l}(S^k\times S^l)$.

I don't know how to use the cup product in order to do this kind of computations. Any help would be appreciated

A: Recall that $H^*(S^n)$ is an exterior algebra $\Lambda(x,n)$ with $x$ in degree $n$. If you pick a continuous map $f : S^n \to S^p \times S^q$ with $p+q=n$, there is induced a map in cohomology
$$f^* : \Lambda(x',p)\otimes \Lambda(x'',q) \longrightarrow \Lambda(x,n)$$
by the Künneth formula. If $\pi_1$ and $\pi_2$ are the projections to $S^p$ and $S^q$, respectively, this corresponds to the map
$$a\otimes b\longmapsto (\pi_1f)^*(a) \smile (\pi_2f)^*(b).$$
Now what are the degree preserving maps $\Lambda(x',p)\to \Lambda(x,n)$ for $p<n$? Well, simply by degree considerations, there is only the trivial map (since $\Lambda(x,n)$ has nonzero parts only in degree $0$ and $n$) meaning that $\pi_i f$ both induce the trivial map on cohomology, and then so does $f^*$.


text:
Q: Can't access all json properties I have this json structure and for some reason I can't access the other properties. I can only "access" through the main properties like type, properties and so on with that hierarchy level. But I can't access to icon, iconURL, title. The data is there but I can access singularly.
If I use console.log(markerRE[i].properties), it shows all the properties but if I want the title only, the console fires can't read property properties of undefined.
var markerRE = [{}]; //JSON ARRAY

$.ajax({
    url: 'consulta4.php',
    data: {},
    method: 'POST',
    dataType: 'json',
    success: function (data) {
        for (var i = 0; i < Object.keys(data).length; i++) {
            markerRE.push({
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [data[i].longitude, data[i].latitude]
                    },

                    "properties": {
                        "title": "Emergencia: " + data[i].priority,
                        "id": data[i].id_emergency,
                        //"descripcion":"<button class='RE'>oisdjos</button>", Forma alternativa de añadir html
                        "icon": {
                            "iconUrl": data[i].imagen,
                            "iconSize": [50, 50], // size of the icon
                            "iconAnchor": [25, 50], // point of the icon which will correspond to marker's location
                            "popupAnchor": [0, -25], // point from which the popup should open relative to the iconAnchor
                            "className": "dot"
                        }
                    }
                }

            );
            console.log(markerRE[i].properties.title);
        }
    }
});

A: Did you try declaring markerRE as
var markerRE = []; //without {}

i tried in my own way bt not sure and I don know why but Using {} makes counter to be started from 1 not 0.

A: It doesn't make a lot of sense to me what you're doing above, as far as looping by the number of keys in your data. But I think one of your problems is also you are instantiating markerRE with an empty object already inside of it. Instead of just making it an empty array []. so  console.log(markerRE[0].properties.title); is going to be invalid because markerRE[0] is an empty object


text:
Q: Probability for dependent events and "Or" Is there a way to calculate the "or" of dependent events?
That is if P(A) = 0.25 and P(B) = 0.6
and P(A|B) = 0 and P(B|A) = 0
I know I can calculate P(A and B) = P(A|B) * P(B)
Is there some way to calculate P(A or B)?

A: $$P(A \text{ or } B) = P(A) + P(B) - P(A \text{ and } B)$$
And you know how to get $P(A \text{ and } B)$.

A: The probability is
$$P(A)+P(B)-P(A\mbox{ and }B)=P(A)+P(B)$$
since the events are mutually exclusive.

A: P(A or B) is P(A)+P(B)-P(A and B)
or P(A ∪ B) = P(A) + P(B) - P(A)P( B | A )


text:
Q: Add marker directly on streetview I´m working with google maps API V3.
I have a google map with a click listener, and when you click on the map, y put a marker on the lat,lng clicked.
Is it posible to add a listener in streetview, where on click or rigthclick I can add a marker directly on the point clicked?
Thanks in advance


text:
Q: gatsby build error while gatsby develop works fine Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

<--- Last few GCs --->

[16184:00000237DCD7CC20]    88497 ms: Mark-sweep (reduce) 2041.4 (2054.4) -> 2041.0 (2054.2) MB, 6714.0 / 0.1 ms  (average mu = 0.053, current mu = 0.001) allocation failure scavenge might not succeed
[16184:00000237DCD7CC20]    94059 ms: Mark-sweep (reduce) 2042.0 (2051.2) -> 2041.6 (2052.9) MB, 5546.7 / 0.1 ms  (average mu = 0.027, current mu = 0.003) allocation failure scavenge might not succeed

<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 00007FF7B2A6412F napi_wrap+133311
 2: 00007FF7B29FDD06 SSL_get_quiet_shutdown+63062
 3: 00007FF7B29FEB9D node::OnFatalError+301
 4: 00007FF7B32E19CE v8::Isolate::ReportExternalAllocationLimitReached+94
 5: 00007FF7B32C67BD v8::SharedArrayBuffer::Externalize+781
 6: 00007FF7B316FFCC v8::internal::Heap::EphemeronKeyWriteBarrierFromCode+1516
 7: 00007FF7B317B3EA v8::internal::Heap::ProtectUnprotectedMemoryChunks+1258
 8: 00007FF7B3178529 v8::internal::Heap::PageFlagsAreConsistent+2457
 9: 00007FF7B316D0C1 v8::internal::Heap::CollectGarbage+2049
10: 00007FF7B316B2C5 v8::internal::Heap::AllocateExternalBackingStore+1349
11: 00007FF7B318B73B v8::internal::Factory::NewFillerObject+203
12: 00007FF7B2EB9F81 v8::internal::interpreter::JumpTableTargetOffsets::iterator::operator=+1409
13: 00007FF7B336CDFD v8::internal::SetupIsolateDelegate::SetupHeap+474253
14: 00007FF7B33046BD v8::internal::SetupIsolateDelegate::SetupHeap+46413
15: 0000013BF1A43736

gatsby develop is working fine and the local site is running fine. but not able to use gatsby build

A: There was an await call for a library inside a function, so it was acting like a loop. Thus the error.


text:
Q: How To Write Asynchronous Method in an Class Library in C# I am trying to write a class library in C#. I should use .net framework 3.0.
I have a method which converts one file type to another file type. It takes time:
public bool ConvertFiles()
{
    // Conversion takes a long time
    // After conversion, if conversion is successfull then I return true,
    // else I return false
}

Since this method will be given to public, when API user wants to use this funtion, I should not block his application because of this method. e.g:
//User calls my API functions
ApiClass api = new ApiClass;
api.ConvertFiles();
// user should not wait for ConvertFiles to finish
// user's codes should continue even if ConvertFiles is not finished!

Therefore, I understand it, I should give API user to an "Asynchronous Method".
Until now I searched following links:

*

*http://www.codeproject.com/Articles/14931/Asynchronous-Method-Invocation

*https://support.microsoft.com/en-us/kb/315582

*http://www.codeproject.com/Articles/41777/NET-Framework-Delegates-Understanding-Asynchronou
After reading them I understand that I can create a method like this:
public bool ConvertFilesAsync()
{
    MethodDelegate dlgt = ConvertFiles;
    // Create the callback delegate.
    AsyncCallback cb = MyAsyncCallback;

   // Initiate the Asynchronous call passing in the callback delegate
   // and the delegate object used to initiate the call.
   IAsyncResult ar = dlgt.BeginInvoke();
}

private void MyAsyncCallback(IAsyncResult ar)
{
// Because you passed your original delegate in the asyncState parameter
// of the Begin call, you can get it back here to complete the call.
MethodDelegate dlgt = (MethodDelegate) ar.AsyncState;
// Complete the call.
bool conversion = dlgt.EndInvoke (ar) ;
}

When user imports my class library, he will use the function as following:
//User calls my API functions
ApiClass api = new ApiClass;
api.ConvertFilesAsync();
// Now user's codes continue even if ConvertFiles is not finished!

But how does he understand if conversion is finished with successfully? In the somewhere of his code, he should understand that file conversion is finished? How do I manage this?
Ps: I am a newbie at delegates and Asynchronous method calling

A: Asynchronous Programming Patterns

The .NET Framework provides three patterns for performing asynchronous
  operations:
Asynchronous Programming Model (APM) pattern (also called the IAsyncResult pattern), where asynchronous operations require Begin and
  End methods (for example, BeginWrite and EndWrite for asynchronous
  write operations). This pattern is no longer recommended for new
  development. For more information, see Asynchronous Programming Model
  (APM).
Event-based Asynchronous Pattern (EAP), which requires a method that has the Async suffix, and also requires one or more events, event
  handler delegate types, and EventArg-derived types. EAP was introduced
  in the .NET Framework 2.0. It is no longer recommended for new
  development. For more information, see Event-based Asynchronous
  Pattern (EAP).
Task-based Asynchronous Pattern (TAP), which uses a single method to represent the initiation and completion of an asynchronous
  operation. TAP was introduced in the .NET Framework 4 and is the
  recommended approach to asynchronous programming in the .NET
  Framework. The async and await keywords in C# and the Async and Await
  operators in Visual Basic Language add language support for TAP. For
  more information, see Task-based Asynchronous Pattern (TAP).

Since you are using .Net 3 you can use APM and EAP.
You can find an example here: MSDN How to: Implement a Component That Supports the Event-based Asynchronous Pattern (.Net 3.0)

A: Maybe you can use BackgroundWorker class
You can create private field like:
private BackgroundWorker backgroundWorker;

Then in constructor create an instance and start it running:
this.backgroundWorker = new BackgroundWorker();
this.backgroundWorker.WorkerSupportsCancellation = true;
this.backgroundWorkerr.DoWork += new DoWorkEventHandler(YourMethod);
this.backgroundWorker.RunWorkerAsync();

in your method you can perform sending and then add some delegates.


text:
Q: how to change character_set_client and character_set_results by client coding instead of changing my.ini I have a requirement that change character_set_client and character_set_results, but don't wanna change them in my.ini, currently on client code side we have a connection configuration as below: username:password@tcp(dns_ip:PORT)/db_name?timeout=10s&readTimeout=10s,
so anyone knows how to change character_set_client and character_set_results by changing above configuration? thank u

A: used collation=utf8mb4_general_ci can work


text:
Q: XSLT typograph Divide a large amount of text on an arbitrary number of equal parts.
I probably already fed up with their stupid questions, but I have one more question.
I have a large piece of text

    Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium,
    totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt,
    explicabo. Nemo enim ipsam voluptatem, quia voluptas sit,

    aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi
    nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit,
    sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem.
    Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid
    ex ea commodi consequatur?

    Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur,
    vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio
    dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas
    molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt
    mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.
    Nam libero tempore, cum

    soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus,
    omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis
    aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae.
    Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur
    aut perferendis doloribus asperiores repellat.

    Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem
    aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo.
    Nemo enim ipsam voluptatem, quia voluptas sit,

    Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium,
    totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt,
    explicabo. Nemo enim ipsam voluptatem, quia voluptas sit,

    aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi
    nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit,
    sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem.
    Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid
    ex ea commodi consequatur?

    Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur,
    vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio
    dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et
    quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia
    deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita
    distinctio. Nam libero tempore, cum

    soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus,
    omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut
    rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae.
    Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur
    aut perferendis doloribus asperiores repellat.

    Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur,
    vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio
    dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas
    molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt
    mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.
    Nam libero tempore, cum

    Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium,
    totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt,
    explicabo. Nemo enim ipsam voluptatem, quia voluptas sit,

    soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere
    possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut
    officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae
    non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores
    alias consequatur aut perferendis doloribus asperiores repellat.

    Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam
    rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt,
    explicabo. Nemo enim ipsam voluptatem, quia voluptas sit,

At the exit I need to divide the text on the "n" equal parts, so that in these parts was about the same amount of text. Then I these part are arranged in columns and the need for these columns look about the same height. Another condition: Tags you can break (I mean that if the tag "p" contains a lot of text, it can be divided into two parts, to bring in another column). I think this is a monumental task, I shall be grateful for any help.
I understand that XSLT is not typography tool. But is it possible divide the text into parts with the same number of characters in each part?

A: Text justification with XSLT is possible (I did it many years ago). Here is a small example that you can use as a base to carry out your complete task:
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/"
xmlns:ext="http://exslt.org/common"
xmlns:str-split2lines-func="f:str-split2lines-func"
exclude-result-prefixes="xsl ext str-split2lines-func"
>

   <xsl:import href="dvc-str-foldl.xsl"/>

   <str-split2lines-func:str-split2lines-func/>

   <xsl:output indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="/">
      <xsl:call-template name="str-split-to-lines">
        <xsl:with-param name="pStr" select="/*"/>
        <xsl:with-param name="pLineLength" select="64"/>
        <xsl:with-param name="pDelimiters" select="'

'"/>
      </xsl:call-template>
    </xsl:template>

    <xsl:template name="str-split-to-lines">
      <xsl:param name="pStr"/>
      <xsl:param name="pLineLength" select="60"/>
      <xsl:param name="pDelimiters" select="'

'"/>

      <xsl:variable name="vsplit2linesFun"
                    select="document('')/*/str-split2lines-func:*[1]"/>

      <xsl:variable name="vrtfParams">
       <delimiters><xsl:value-of select="$pDelimiters"/></delimiters>
       <lineLength><xsl:copy-of select="$pLineLength"/></lineLength>
      </xsl:variable>

      <xsl:variable name="vResult">
          <xsl:call-template name="dvc-str-foldl">
            <xsl:with-param name="pFunc" select="$vsplit2linesFun"/>
            <xsl:with-param name="pStr" select="$pStr"/>
            <xsl:with-param name="pA0" select="ext:node-set($vrtfParams)"/>
          </xsl:call-template>
      </xsl:variable>

      <xsl:for-each select="ext:node-set($vResult)/line">
        <xsl:for-each select="word">
          <xsl:value-of select="concat(., ' ')"/>
        </xsl:for-each>
        <xsl:value-of select="'
'"/>
      </xsl:for-each>
    </xsl:template>

    <xsl:template match="str-split2lines-func:*" mode="f:FXSL">
      <xsl:param name="arg1" select="/.."/>
      <xsl:param name="arg2"/>

      <xsl:copy-of select="$arg1/*[position() < 3]"/>
      <xsl:copy-of select="$arg1/line[position() != last()]"/>

      <xsl:choose>
        <xsl:when test="contains($arg1/*[1], $arg2)">
          <xsl:if test="string($arg1/word)">
             <xsl:call-template name="fillLine">
               <xsl:with-param name="pLine" select="$arg1/line[last()]"/>
               <xsl:with-param name="pWord" select="$arg1/word"/>
               <xsl:with-param name="pLineLength" select="$arg1/*[2]"/>
             </xsl:call-template>
          </xsl:if>
        </xsl:when>
        <xsl:otherwise>
          <xsl:copy-of select="$arg1/line[last()]"/>
          <word><xsl:value-of select="concat($arg1/word, $arg2)"/></word>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:template>

    <xsl:template name="fillLine">
      <xsl:param name="pLine" select="/.."/>
      <xsl:param name="pWord" select="/.."/>
      <xsl:param name="pLineLength" />

      <xsl:variable name="vnWordsInLine" select="count($pLine/word)"/>
      <xsl:variable name="vLineLength"
       select="string-length($pLine) + $vnWordsInLine"/>
      <xsl:choose>
        <xsl:when test="not($vLineLength + string-length($pWord)
                           >
                            $pLineLength)">
          <line>
            <xsl:copy-of select="$pLine/*"/>
            <xsl:copy-of select="$pWord"/>
          </line>
        </xsl:when>
        <xsl:otherwise>
          <xsl:copy-of select="$pLine"/>
          <line>
            <xsl:copy-of select="$pWord"/>
          </line>
          <word/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:template>

</xsl:stylesheet>

when performed on this XML document (this is the original document that was used back then -- this cnn text can be traced back to 2003 or 2002):
<text>
Dec. 13 — As always for a presidential inaugural, security and surveillance were
extremely tight in Washington, DC, last January. But as George W. Bush prepared to
take the oath of office, security planners installed an extra layer of protection: a
prototype software system to detect a biological attack. The U.S. Department of
Defense, together with regional health and emergency-planning agencies, distributed
a special patient-query sheet to military clinics, civilian hospitals and even aid
stations along the parade route and at the inaugural balls. Software quickly
analyzed complaints of seven key symptoms — from rashes to sore throats — for
patterns that might indicate the early stages of a bio-attack. There was a brief
scare: the system noticed a surge in flulike symptoms at military clinics.
Thankfully, tests confirmed it was just that — the flu.
</text>

correctly performs justification of every line to the desired width of no more than 64 The result is:
Dec. 13 — As always for a presidential inaugural, security and
surveillance were extremely tight in Washington, DC, last
January. But as George W. Bush prepared to take the oath of
office, security planners installed an extra layer of
protection: a prototype software system to detect a biological
attack. The U.S. Department of Defense, together with regional
health and emergency-planning agencies, distributed a special
patient-query sheet to military clinics, civilian hospitals and
even aid stations along the parade route and at the inaugural
balls. Software quickly analyzed complaints of seven key
symptoms — from rashes to sore throats — for patterns that might
indicate the early stages of a bio-attack. There was a brief
scare: the system noticed a surge in flulike symptoms at
military clinics. Thankfully, tests confirmed it was just that —
the flu.

The rest of the task is left as an exercise for the reader :)


text:
Q: Android Studio: keep non-essential elements after revising application for release? I'm new to software dev, so I don't know the proper etiquettes for this process.
I just want to keep certain debugging code (comments and stuff) and maybe some testing resources like images after cleaning an app for release. These are things the app will never need for functioning, just stuff I wanna keep.
Are comments kept after the compile? If not I can just comment out those lines.
I thought about using different flavours, but it doesn't seem appropriate? Just because the build release type makes 4 options.-which I never really understood. Does switching from Debug mode to Release mode change anything code-wise? Like other than the signing methods and other discrete (discrete to me anyways) changes?
Thanks!

A:
Are comments kept after the compile? If not I can just comment out those lines.

Commented-out code isn't compiled, so if you want, yes you can comment out code and it won't show up in the final app. However, there's no way to comment out resources in the same way, so if there are resources you only want to have in your debug version, keep reading.

I thought about using different flavours, but it doesn't seem
  appropriate? Just because the build release type makes 4 options.

You're right, you don't need flavors because there's already build types (Debug and Release) which are set up to do what you want. Your Java code can tell the difference between debug and release types via the BuildConfig class, which is automatically generated as part of the build. It has a DEBUG Boolean constant that's defined to true for debug builds and false for release. So you can have code that does something like this:
if (BuildConfig.DEBUG) {
    // Do something here that you don't want to have in the final release
}

Since BuildConfig.DEBUG is a static final Boolean, then Java is smart enough to see that what's inside that if block will never run in a release build, so the compiler will strip that code out and it won't appear in your app.
If there are resources you'd only like to have in the debug and not release versions of the app, then you can put them in a different folder in your hierarchy:
ProjectDirectory
+--app
   +--src
      +--main
         +--res  <--Your normal resources go here
         +--java
         +--AndroidManifest.xml
      +--debug
         +--res  <-- Put resources for the debug build only here

That debug/res folder won't be created by default, but if you set it up, the build system should pick it up. Having said that, debug-only resources are a little unusual; you would only have something like this if your debug version of the app had something like a diagnostic activity or menus or something like that. It's certainly possible, but it's a little more advanced than it sounds like what you're doing so far.

-which I never really understood. Does switching from Debug mode to Release mode change anything code-wise? Like other than the signing
  methods and other discrete (discrete to me anyways) changes?

Some of the important changes in a release build are:

*

*BuildConfig.DEBUG will be false as already noted.

*Your app will be signed with a release key instead of the debug key. The release key is what you will use to sign it to upload to the Google Play store. You'll need to set up that key if you don't have it already.

*Release apps are built as non-debuggable unless you change the setting.

*You can run ProGuard (which does dead code stripping and obfuscation) on release builds, though it's not configured to run by default.


text:
Q: Deploy Angular Application on AWS S3 or EC2 I need to deploy an Angular application on AWS,
I found two ways to do it:

*

*S3 Bucket

*EC2 instance using nginx

Which is the best and why?
The application is a big application that will call severals Spring Boot Microservices also deployed on AWS EC2.


text:
Q: creating classes based on Object.class I want to define a list of classes and instantiate them later. I have a list like this

List<Class> classList = new ArrayList<>();
classList.add(ClassA.class);
classList.add(ClassB.class);

I want to read from this list and create the classes. I don't know witch classes I have to create since clients of my library will define this list. All i know is all of this classes extend from the same class and have one object as constructor argument.

Any idea how should i achieve this?

A: If constructors of all your classes in question accept a single parameter, and the type of that parameter is the same (let's say it's String), you could instantiate such a class with the following:
Object instance = clazz.getConstructor(String.class).newInstance("string value you pass to the constructor");

Also, if all your classes extend class Super, it's better to write Class<? extends Super> instead of raw Class. Then you could write
Super instance = clazz.getConstructor(String.class).newInstance("string value you pass to the constructor");


text:
Q: How to delete workspace? How do I delete a workspace that I created in the wrong place?
I'm completely new to svn.  Just installed svnslik and got far enough to create a repository and then a workspace.  However, it added one more level of directory than I expected so I want to remove the workspace and recreate it.

A: No problem. Just delete the workspace directory using your current operating system's command. All the information that makes it a Subversion workspace is embedded in the .svn directory in the root of your workspace.
Unlike Perforce or ClearCase, the Subversion repository server does not track workspaces.


text:
Q: AngularJS touchmove event with multiple elements/scope I am trying to handle a touchmove event for an ng-repeat'ed directive, regardless of where the touchstart occurred. In my present code, if one of the elements detects a touchstart, all touchmove events will be handled by that same element, regardless of where on the screen the touchmoves happen. When I execute similar functionality with a mousemove, each element correctly receives mousemove events only when the mouse is over the respective elements.
I have seen questions unrelated to AngularJS about detecting the DOM element for a touchmove event (How to find out the actual event.target of touchmove javascript event?), but if I were to do that, I don't see a way of handling that inside a directive/controller with the correct scope.
Here is a basic example (for convenience: http://jsfiddle.net/zMKKv/1/) to compare the difference in behavior between mousemove and touchmove:

            <counter ng-repeat="item in somedata" />

//-----------

.box {
  width: 150px;
  height: 150px;
  border: solid;
  float: left;
}

//-----------

var app = angular.module('myApp', []);

app.controller("countController", function ($scope) {
    $scope.somedata = [{
        label: "One",
        count: 0
    }, {
        label: "Two",
        count: 0
    }, {
        label: "Three",
        count: 0
    }];

    $scope.increment = function(item) {
      item.count = item.count + 1;
      $scope.$digest();
    };
});

app.directive("counter", function () {
    return {
        restrict: "E",
        template: '
{{item.label}}
{{item.count}}
',
        link: function (scope, element, attrs) {

            element.on('mousemove', function () {
                scope.increment(scope.item);
            });

            element.on('touchmove', function (e) {
                e.preventDefault();
                scope.increment(scope.item);
            });
        }
    };
});


text:
Q: SAS code: Number of tab characters in a string I am importing a tab-delimited file in SAS, but there is a possible number of extra tab characters in some of the data lines. In order to verify whether all lines have the same number of tab delimiters, I want to count the number of tab character in each data line. How do I achieve that in SAS? For ordinary characters (for example ";" or "|", the code below works fine, but I don't know how to refer to the tab character, since '09'x does not work inside the count() function:
   DATA output_file;
      drop inrecord;
      INFILE "input_file"
          LRECL=1000
          dlm=';'
      MISSOVER
      DSD
      ;

   length inrecord $1000;
    input @1 inrecord $1000.;
    dlm_count = count(inrecord,';');
    RUN;

A: Use countc().
(Note: you'll need to manually add tabs to the end of the datalines rows as they're converted to spaces on Stack Overflow)
data dr_seuss;
    length line $100.;
    infile datalines dlm=',';
    input line$;

    total_tabs = countc(line, '09'x);

    datalines;
one fish
two fish
red fish
blue fish
;
run;

A: The Count and the CountC both should work.  '09'x should work inside Count.
CountC with modifiers would be more flexible for character delimited data and code that might have to run on both ASCII and EBCDIC platforms.
Use the input; statement alone to read an entire line into the input buffer which is accessed through the automatic variable _infile_.
filename tabdata '....';
data _null_;
  infile tabdata lrecl=32000;

  input;

  tabcount = count(_infile_, '09'x);
  if tabcount ne lag(tabcount) and _n_ > 1 then put 'tabcount changed! ' _n_= tabcount=;
run;

Example of three tab counterings:
data _null_;
  s = "ABC" || "09"x || "DEF" || "09"x || "GHI" || "0909090909"x;

  tabcount = count(s, "09"x);    * count when tab specified as the substring;
  tabcountc = countc(s, "09"x);  * countc with single character, the ascii tab character;
  tabcountc2 = countc(s,,'h');   * countc with modifier h for counting horizontal tabs;

  put (tabcount:) (=/);
run;
----------------- LOG ------------------
tabcount=7
tabcountc=7
tabcountc2=7

Be careful, the Count target is the substring argument, and the CountC single character target(s) are in the charlist argument.  If there are multiple delimiters, use CountC.

A: Both COUNT() and COUNTC() will work.
ntabs1=count(_infile_,'09'x);
ntabs2=countc(_infile_,'09'x);

To have any hope of actually fixing the file you need one of two things.
First the extra tabs might have been escaped by being prefixed with a backslash. Just look at one of the bad lines and decide if that is what they did.  You could use  TRANWRD() function to change any backslash + tab into some other character, like pipe.
data want;
  infile "input_file" dsd dlm='09'x truncover ;
  input @;
  _infile_=tranwrd(_infile_,'\'||'09'x,'|');
  input .... ;
run;

Second if you are certain that there is only one column that could contain the extra tabs then just peel off the values before and after that column and whatever is left is the value of that column.
If neither of these things are true then you might need to manually edit the lines with extra tabs. You could fix it by changing the embedded tabs to some other character or by adding quotes around the values with embedded tabs.  You could use the result of the COUNTC() function to tell which lines need editing.  For example if there should be 11 fields (so 10 tabs) then a program like this will split the file into two parts.
 data _null_;
   infile "input_file";
   input;
   if countc(_infile_,'09'x)=10 then file "good_file";
   else file "bad_file";
   put _infile_;
run;


text:
Q: Spring Boot application using the Spring Cloud Stream Kafka Binder + Kafka Streams Binder not working - Producer doesn't send messages My Spring Boot 2.3.1 app with SCS Hoshram.SR6 was using the Kafka Streams Binder. I needed to add a Kafka Producer that would be used in another part of the application so I added the kafka binder. The problem is the producer is not working, throwing an exception:
19:49:40.082 [scheduling-1] [900cdeb11106e199] ERROR o.s.c.stream.binding.BindingService - Failed to create producer binding; retrying in 30 seconds
org.springframework.cloud.stream.provisioning.ProvisioningException: Provisioning exception; nested exception is java.util.concurrent.TimeoutException
    at org.springframework.cloud.stream.binder.kafka.provisioning.KafkaTopicProvisioner.createTopic(KafkaTopicProvisioner.java:332)
    at org.springframework.cloud.stream.binder.kafka.provisioning.KafkaTopicProvisioner.provisionProducerDestination(KafkaTopicProvisioner.java:148)
    at org.springframework.cloud.stream.binder.kafka.provisioning.KafkaTopicProvisioner.provisionProducerDestination(KafkaTopicProvisioner.java:79)
    at org.springframework.cloud.stream.binder.AbstractMessageChannelBinder.doBindProducer(AbstractMessageChannelBinder.java:222)
    at org.springframework.cloud.stream.binder.AbstractMessageChannelBinder.doBindProducer(AbstractMessageChannelBinder.java:90)
    at org.springframework.cloud.stream.binder.AbstractBinder.bindProducer(AbstractBinder.java:152)
    at org.springframework.cloud.stream.binding.BindingService.lambda$rescheduleProducerBinding$4(BindingService.java:336)
    at org.springframework.cloud.sleuth.instrument.async.TraceRunnable.run(TraceRunnable.java:68)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.base/java.lang.Thread.run(Unknown Source)
Caused by: java.util.concurrent.TimeoutException: null
    at org.apache.kafka.common.internals.KafkaFutureImpl$SingleWaiter.await(KafkaFutureImpl.java:108)
    at org.apache.kafka.common.internals.KafkaFutureImpl.get(KafkaFutureImpl.java:272)
    at org.springframework.cloud.stream.binder.kafka.provisioning.KafkaTopicProvisioner.createTopicAndPartitions(KafkaTopicProvisioner.java:368)
    at org.springframework.cloud.stream.binder.kafka.provisioning.KafkaTopicProvisioner.createTopicIfNecessary(KafkaTopicProvisioner.java:342)
    at org.springframework.cloud.stream.binder.kafka.provisioning.KafkaTopicProvisioner.createTopic(KafkaTopicProvisioner.java:319)

This is my configuration:
spring:
  cloud:
    function:
      definition: myProducer
    stream:
      bindings:
        myKStream-in-0:
          destination: my-kstream-topic
          producer:
            useNativeEncoding: true
        myProducer-out-0:
          destination: producer-topic
          producer:
            useNativeEncoding: true
      kafka:
        binder:
          brokers: ${kafka.brokers:localhost}
          min-partition-count: 3
          replication-factor: 3
          producerProperties:
            enable:
              idempotence: true
            retries: 0x7fffffff
            acks: all
            key:
              serializer: io.confluent.kafka.serializers.KafkaAvroSerializer
              subject:
                name:
                  strategy: io.confluent.kafka.serializers.subject.RecordNameStrategy
            value:
              serializer: io.confluent.kafka.serializers.KafkaAvroSerializer
              subject:
                name:
                  strategy: io.confluent.kafka.serializers.subject.RecordNameStrategy
            schema:
              registry:
                url: ${schema-registry.url:http://localhost:8081}
            request:
              timeout:
                ms: 5000
        streams:
          binder:
            brokers: ${kafka.brokers:localhost}
            configuration:
              application:
                id: ${spring.application.name}
                server: ${POD_IP:localhost}:${local.server.port:8080}
              schema:
                registry:
                  url: ${schema-registry.url}
              key:
                subject:
                  name:
                    strategy: io.confluent.kafka.serializers.subject.RecordNameStrategy
              value:
                subject:
                  name:
                    strategy: io.confluent.kafka.serializers.subject.RecordNameStrategy
              processing:
                guarantee: exactly_once
              replication:
                factor: 3
              group:
                id: kpi
            deserialization-exception-handler: logandcontinue
            min-partition-count: 3
            replication-factor: 3
            state-store-retry:
              max-attempts: 20
              backoff-period: 1500

What could be the problem here?
UPDATE
I tweaked the config as follows:
spring:
  cloud:
    function:
      definition: myProducer
    stream:
      function:
        definition: myKStream

Now I can't see any exception but the messages don't get to the topic.
In another application that only uses the kafka binder it works perfectly:
@Configuration
class KafkaProducerConfiguration {

    @Bean
    fun myProducerProcessor(): EmitterProcessor<Message<XXX>> {
        return EmitterProcessor.create()
    }

    @Bean
    fun myProducer(): Supplier<Flux<Message<XXX>>> {
        return Supplier { myProducerProcessor() }
    }

}

...

@Component
class XXXProducer(@Qualifier("myProducerProcessor") private val myProducerProcessor: EmitterProcessor<Message<XXX>>) {

    fun send(...): Mono<Void> {
        return Mono.defer {
                myProducerProcessor.onNext(message)
                Mono.empty()
        }
   }

UPDATE 2
I set logging.level.org.springframework.cloud.stream: debug
In the logs the following trace shows up:
o.s.c.s.binder.DefaultBinderFactory - Creating binder: kstream

However there isn't anything about a Creating binder: kafka.

A: I was missing the multiple binder config for kafka and kstreams (https://cloud.spring.io/spring-cloud-static/spring-cloud-stream-binder-kafka/3.0.0.RELEASE/reference/html/spring-cloud-stream-binder-kafka.html#_multi_binders_with_kafka_streams_based_binders_and_regular_kafka_binder)
Thus, I had to set up: spring.cloud.stream.function.definition=myProducer;myKStream


text:
Q: Can I play a demo of Katamari Damacy on Windows? I would like to try playing Katamari Damacy but do not have Nintendo. Is there a demo version, even a short one, that runs on Windows 10?
I checked the official site but did not find any Windows demo.

A: No there ist no demo of Katamari Damacy available for the PC, only for the Nintendo Switch. To test the game on PC, you could buy it on Steam and return it within the refund time period, if you don't like it.


text:
Q: python password checker fails I defined the following function to check the validity of a password, but it doesn't work for valid passwords. For a password to be valid, it should only have numbers and ascii letters, and must be longer than 10 chars. What I am I doing wrong?
def checker(password):
    letters = map(chr, range(97, 123))+ map(chr, range(65, 91))
    numbers = [range(0, 10)]
    if len(password) < 10:
            return 'Too short'
    for i in password:
        if (i not in letters or i not in numbers):
            return 'Password has invalid chars'
        return 'Password is valid'

A: fist your numbers is a nested list range(0, 10) is a list by itself you dont need to wrap in in a list ! and also you need to your numbers be string , so as a more efficient way you just could use string module for create your checking set Also you need to move your last return outside of for loop :
>>> s=string.ascii_letters+string.digits
>>> s
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

So your function could be like following :
def checker(password):
    s=string.ascii_letters+string.digits
    if len(password) < 10:
            return 'Too short'
    for i in password:
        if i not in s:
            return 'Password has invalid chars'
    return 'Password is valid'

Demo :
>>> checker('thisis4thtest')
'Password is valid'
>>> checker('thisis4thtest#')
'Password has invalid chars'
>>> checker('thisis4#')
'Too short'

A: First problem: the condition is wrong: not in chars or not in numbers is always true.
Second problem: your numbers are numbers (integers) and wrapped in another list, instead of just characters. Use numbers = [str(x) for x in range(10)]

A: def checker(password):
    letters = map(chr, range(97, 123))+ map(chr, range(65, 91))
    numbers = [str(x) for x in range(10)]
    if len(password) < 10:
            return 'Too short'
    for i in password:
        if not (i in letters or i in numbers):
            return 'Password has invalid chars'
        return 'Password is valid'

Your if logic was a bit wrong.

A: You can use regex to find if password only contains ascii letters and numbers or not
import re
check = re.compile('^[\w]{10,}$')
if check.match(password):
    return 'Password is valid'
else:
    return 'Password has invalid chars'


text:
Q: How to make code into a class with processing I am taking a coding class, and I am struggling to do the following:
Rewrite the following code into an object-oriented fashion with a Snake class, and use an array to make a second snake appear.
This is what I have so far.
THIS IS NOT HOMEWORK, DO NOT WORRY. THIS IS A CLASS I AM TAKING ONLINE
int[] xpos = new int[50];
int[] ypos = new int[50];

void setup() {
  size(800,600);
  // Initialize
  for (int i = 0; i < xpos.length; i++){
   xpos[i] = 0;
   ypos[i] = 0;
  }
}

void draw() {
  background(255);

  // Shift Array Values
  for (int i = 0; i < xpos.length - 1; i++){
    xpos[i] = xpos[i + 1];
    ypos[i] = ypos[i + 1];
  }

  // New location
   xpos[xpos.length - 1] = mouseX;
   ypos[ypos.length - 1] = mouseY;

  // Draw Everything
  for (int i = 0; i < xpos.length - 1; i++){
    noStroke();
    fill(255 - i*5);
    ellipse(xpos[i], ypos[i], i, i);
  }
}

A: So I don't know how much you already know about objects is Processing, so I hope you will understand this.
A object is just an instance of a class.
A class can include variables and functions.
When you create an object from a class you can set the variables of the object, so that two different objects can have two different values for the same variable.
When you run a function of an object it will perform the function only on the variables from that object (not from the others).
So to create a class you just wrap the code in class [class name here] { [your code here] }.
You can cut out stuf that you don't want to be executed multible times like background(255); and paste it back into draw function.
Now you have to rename the functions: for the setup function you can use a constructer which is just a function without a return type (like void) and with the same name as the class. This will automatically run when you create the object later. The draw function you can just name how you want (I named it update).
So at that point you should have this:
class Snake{
  private int[] xpos = new int[50];
  private int[] ypos = new int[50];

  Snake(){
   for (int i = 0; i < xpos.length; i++){
     xpos[i] = 0;
     ypos[i] = 0;
    }
  }

  void update(){
    // Shift Array Values
    for (int i = 0; i < xpos.length - 1; i++){
      xpos[i] = xpos[i + 1];
      ypos[i] = ypos[i + 1];
    }

    // New location
     xpos[xpos.length - 1] = mouseX;
     ypos[ypos.length - 1] = mouseY;

    // Draw Everything
    for (int i = 0; i < xpos.length - 1; i++){
      noStroke();
      fill(255 - i*5);
      ellipse(xpos[i], ypos[i], i, i);
    }
  }

}

so now you can create an array of snakes and run the update function (or what ever you named it) on all of them (of cause I would do that with a loop, but I think this way it's more obvious)
Snake[] snakes = {new Snake(), new Snake()};

void setup() {
  size(800,600);
  // Initialize
}

void draw() {
  background(255);

  snakes[0].update();
  snakes[1].update();

}

Now you have two snakes, but you can't see both of them because they are on top of each other. That's why I added a variable offset, that will offset the two snakes and r, g, b variables for the color of the snake.
of cause you have to pass the variables to the object when you create it and recieve it in the constructor.
So when you're done you should have something like that:
Snake[] snakes = {new Snake(0,0,255, 0), new Snake(255,0,0, 50)};

void setup() {
  size(800,600);
  // Initialize
}

void draw() {
  background(255);

  snakes[0].update();
  snakes[1].update();

}

class Snake{
  private int[] xpos = new int[50];
  private int[] ypos = new int[50];
  private int r;
  private int g;
  private int b;
  private int offset;

  Snake(int r, int g, int b, int offset){
    this.r = r;
    this.g = g;
    this.b = b;
    this.offset = offset;
   for (int i = 0; i < xpos.length; i++){
     xpos[i] = 0;
     ypos[i] = 0;
    }
  }

  void update(){
    // Shift Array Values
    for (int i = 0; i < xpos.length - 1; i++){
      xpos[i] = xpos[i + 1];
      ypos[i] = ypos[i + 1];
    }

    // New location
     xpos[xpos.length - 1] = mouseX +offset;
     ypos[ypos.length - 1] = mouseY +offset;

    // Draw Everything
    for (int i = 0; i < xpos.length - 1; i++){
      noStroke();
      fill(r - i*5, g - i*5, b - i*5);
      ellipse(xpos[i], ypos[i], i, i);
    }
  }

}

So finally it should look like this:
two snakes in red and blue
I hope I could help you with this!


text:
Q: java.lang.NullPointerException: at com.google.firebase.iid.zzad.zzchp Below error is reported by Play Store. android vitals.
I am using
compile 'com.google.firebase:firebase-messaging:11.6.2'
    java.lang.RuntimeException:
  at android.app.LoadedApk$ReceiverDispatcher$Args.run (LoadedApk.java:1195)
  at android.os.Handler.handleCallback (Handler.java:751)
  at android.os.Handler.dispatchMessage (Handler.java:95)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1518)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1408)

Caused by: java.lang.NullPointerException:
  at com.google.firebase.iid.zzad.zzchp (zzad.java)
  at com.google.firebase.iid.zzae.onReceive (zzae.java)
  at android.app.LoadedApk$ReceiverDispatcher$Args.run (LoadedApk.java:1185)
  at android.os.Handler.handleCallback (Handler.java:751)
  at android.os.Handler.dispatchMessage (Handler.java:95)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1518)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1408)

Any clue please ?

A:
Cloud Messaging
CHANGED: FirebaseInstanceIdInternalReceiver has been removed from the SDK's automatically-merged AndroidManifest. If you weren't using
  Gradle or its manifest automerging feature and were adding this
  receiver manually, you can now remove it.

https://firebase.google.com/support/release-notes/android
It's just a crash caused by a vestige from FirebaseInstanceIdInternalReceiver during apk update. The receiver still functioning, but the class is gone and then... crashes.


text:
Q: Opening a PDF file using FileProvider uri opens a blank screen I'm creating a PDF file on my app and writing it to the external storage, "Download" directory. Now, when I open it through my app with an intent action.VIEW using FileProvider uri, Google PDF Viewer displays a blank screen, Adobe Acrobat cannot even open the file. Here's my code to write the file and then trying to show it. Note that I'm sending a local notification and trying to open the file through the notification.
try {

                    File mypath=new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),mParam1.getEmlak_id()+".pdf");
                    document.writeTo(new FileOutputStream(mypath));

                    document.close();

                    NotificationManager notificationManager = (NotificationManager)getContext().getSystemService(Context.NOTIFICATION_SERVICE);

                    File file = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),mParam1.getEmlak_id()+".pdf");
                    Uri pdfUri = FileProvider.getUriForFile(getContext(), getContext().getApplicationContext().getPackageName() + ".com.onur.emlakdosyasi.provider", file);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(pdfUri, "application/pdf");
                    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                    //use the flag FLAG_UPDATE_CURRENT to override any notification already there
                    PendingIntent contentIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                    Notification notification = new Notification.Builder(getContext())
                            .setContentTitle("title")
                            .setContentText("content")
                            .setSmallIcon(R.drawable.pdficon)
                            .setContentIntent(contentIntent)
                            .setDefaults(Notification.DEFAULT_ALL)
                            .setPriority(Notification.PRIORITY_HIGH)
                            .build();

                    notificationManager.notify(10, notification);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

Here's my provider on AndroidManifest.xml
<provider
        android:name=".GenericFileProvider"
        android:authorities="${applicationId}.com.onur.emlakdosyasi.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

And here's the provider paths:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
<external-path name="Download" path="Download/"/>

Note that I can open the saved file from the Download folder manually. I just cannot open it through the uri provided by FileProvider.
Changing "exported" field to true doesn't change anything.

A:   File pdfFile = new File(Environment.getExternalStorageDirectory() + "/Ap/" + "manual.pdf");  // -> filename = manual.pdf

    Uri excelPath;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

        excelPath = FileProvider.getUriForFile(mContext, "YourPackageName", pdfFile);
    } else {
        excelPath = Uri.fromFile(pdfFile);
    }
    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
            pdfIntent.setDataAndType(excelPath, "application/pdf");
            pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            pdfIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            try{
        startActivity(pdfIntent);
    }catch(ActivityNotFoundException e){
        Toast.makeText(mContext, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
    }

A: Tried everything for hours and posted here for last resort. After 15 mins, solved it..
For anyone wondering, I changed name attribute of provider from
android:name=".GenericFileProvider"

to
android:name="android.support.v4.content.FileProvider"

I don't even know why I have created a file provider class myself but I remember following a tutorial for it.

A: I hade the same problem but in my case it was the line:
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

that was missing.

A: For my case adding -
/* If set, the new activity is not kept in the history stack.
 * As soon as the user navigates away from it, the activity is finished. */

 intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

was worked !!!