text:
Q: How can I prevent automatic image rotation? In Jasper report when the size of the image is huge it rotates the image automatically. How can I prevent that?

*

*First picture: 3024x3024 px 2MB

*Second picture: 1125x1500 px 300KB

A: I think your problem is with the Scale Image property. Try to change it to Retain Shape


text:
Q: How do I extend my disk space with wubi?
Possible Duplicate:
Is it possible to extend the disk space available to a wubi install?

i install ubuntu 12.04 a couple of months ago. i use the maximum space allowed in ubuntu which is 30g to install ubuntu. Because of ubuntu's updates my disk is now on low space. i wish to add more.. maybe another 50g to make it 80g. Ive seen some tutorial about wubi resize1.5b. BUt i dont know why it says this:
skadush@ubuntu:~/Downloads$ sudo bash wubi-resize_1.5b.sh 80
wubi-resize_1.5b.sh: The new disk cannot exceed 32 GB unless the
wubi-resize_1.5b.sh: --max-override option is used (not recommended).

Please help.. I realy want to extend may disk space on ubuntu.. thanks

A: Instead of sudo bash wubi-resize_1.5b.sh 80 type sudo bash wubi-resize_1.5b.sh --max-override 80.
Make sure the 50GB, next to your Ubuntu partition, are free.

A: 32 Gig should be more then enough for a wubi install with a small home directory. If you need significantly more you should probably do a full install of ubuntu, not wubi.
Since you said that the disk space is low because of updates you might want to try running sudo apt-get clean; sudo apt-get autoremove which will remove old files update files and programs that were automatically installed but are no longer needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to install OwlCarousel in Laravel 7? How can I install OwlCarousel in Laravel 7? I tried using cdnjs.
Within the HTML I have the code below:

        @include('inc.navbar')

            @include('inc.messages')
            @yield('content')

And in my index.blade.php I have this:

 Your Content

 Your Content

 Your Content

 Your Content

 Your Content

 Your Content

 Your Content

When I load the page I get the following error:
Uncaught TypeError: $(...).owlCarousel is not a function
How can I install the OwlCarousel in Laravel project?


text:
Q: AngularJS - Selection of text triggers ng-click in parent in Chrome I am experiencing a problem, to which I currently have no suitable solution:
Having an input field and when selecting the text and the mouse cursor is moved beyond the input field, the ng-click-event on the parent gets triggered when releasing the mouse button. It seems to make sense, since mouseup is triggered, but this is not the behaviour I want.
However, this only occurs in Chrome-Browser, in Firefox, I can't reproduce this issue.
Here's a simple plunker to demonstrate:
https://next.plnkr.co/edit/tNvKNdDRIE9CUqlk?preview
Just try to mark the text and move the mouse beyond the input-field.

*

*Expected Behaviour: Background stays Gray.

*Actual Behaviour:
   Background gets Green, showing that the ng-click in the background
   has happened.

How can I fix this?

A: A working Plnkr
I'm saving the last "mousedown" element - and than decide whether to init Background color change ("$scope.active")


text:
Q: Can't rely on target typing when chaining methods In Java 8, type inference has been extended to target typing which enables to write:
Comparator<String> ascending = comparingInt(String::length);

without having to use a type witness (Comparator.<String> comparingInt). However the last statement below does not compile. Is there a reason? Is there a workaround?
Comparator<String> ascending = comparingInt(String::length);                //ok
Comparator<String> descending = ascending.reversed();                       //ok
Comparator<String> descending = reverseOrder(comparingInt(String::length)); //ok
Comparator<String> descending = Comparator.<String>comparingInt(String::length)
                                                  .reversed();              //ok
Comparator<String> descending = comparingInt(String::length).reversed();    //error

A: The problem is fixed with build 129 (but appears until build 128).


text:
Q: Running Program on Different Linux Distros I have this program 'prog' that I can run with no problem on my server. When attempting to run it on my own machine (64-bit Ubuntu), I get the message:
 bash: ./prog: cannot execute binary file

I've made sure all the permissions for all files involved are set to 777 just to be sure it's not a permissions issue. I believe the server is 32-bit, which may be the reason. However, shouldn't the 64-bit os be able to run a 32-bit program since it's just a subset of architectures? If not, is there some emulator I can download for Ubuntu that will allow me to run 32-bit programs if that is indeed the problem?
I understand the 'cannot execute binary file' error is somewhat encompassing, so the above is just my guess at why I'm getting the message, but perhaps someone else has another theory?
Thanks again all.

A: You need the 32-bit (shared) libraries used by prog on your 64-bit computer. Otherwise prog cannot get executed.
Try to install them using
apt-get install ia32-libs

(if prog requires even more libraries, also install their 32-bit versions)
This should do the trick.
Note that if you have the source of prog, it might be more convenient (less installing of 32 bit libraries) to recompile prog on your 64-bit computer.


text:
Q: MS Graph API Client - Cannot get Expand to work in Queries I am trying to expand all items of MS Teams drive (SharePoint document library) using the Graph API.
I can access the team (group) but am unable to directly expand the Items collection. It would be great if that would be possible, so I don't need another query for that (performance!).
According to the documentation there is the $expand= option, in C# I have the Expand() extension method. Unfortunately I cannot find any working example of how to use it. Well, there is one example in the official documentation:
 string messageId = "<guid>";
 Message message = await graphClient.Me.Messages[messageId]
            .Request()
            .Expand("attachments")
            .GetAsync();

But I am unable to reproduce it successfully. The property should be "Items", so I guess I should use lowercase "items" (but I also tried it with "Items").
Here is the teamsDrive, when I won't expand anything, you see the properties is "Null" (it should have items, documents are present in the library):
teamDrive
{Microsoft.Graph.Drive}
Activities [IDriveActivitiesCollectionPage]:null
AdditionalData [IDictionary]:Count = 3
Bundles [IDriveBundlesCollectionPage]:null
CreatedBy:{Microsoft.Graph.IdentitySet}
CreatedByUser [User]:null
CreatedDateTime:{30/05/2020 23:46:46 +00:00}
Description [string]:""
DriveType [string]:"documentLibrary"
ETag [string]:null
Following [IDriveFollowingCollectionPage]:null
Id [string]:"b!QXf1ydGT80WWzfKB0A5IvAkI2isDR2NEh9jgSseDzmFpXz0eAriVS6TXSBEiZhVP"
Items [IDriveItemsCollectionPage]:null
LastModifiedBy [IdentitySet]:null
LastModifiedByUser [User]:null

So, I tried the following:
var teamDrive = await graphClient.Groups[group.Id].Drive.Request().Expand("items").GetAsync();

But this gives me an exception:
Status Code: BadRequest
Microsoft.Graph.ServiceException: Code: invalidRequest
Message: The request is malformed or incorrect.
Inner error:
    AdditionalData:
    request-id: 93ab7efd-0a33-4ff0-800e-d7e95acd8eb4
    date: 2020-06-17T08:41:39
ClientRequestId: 93ab7efd-0a33-4ff0-800e-d7e95acd8eb4

   at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)

I am using the BETA Graph endpoint (https://graph.microsoft.com using an access token retrieved from https://login.microsoftonline.com/{our tenant Id}) with the Microsoft.Graph.Beta NuGet Package (Version 0.18.0-preview - the latest version).
Note that I don't use any select or filter statements in this request, as others have mentioned that this is not allowed when expanding: Expanding and Filtering MS Graph API Does Not Work

A: OK, I found out what was wrong in my request.
The Items collection can only be used, when I want to access a single item. When I want to access the item collection (all items of the collection) I have to expand the Root property of the drive. This Root property then has a Children property containing the items inside the root folder of the drive (note: it doesn't contain all items of document library, only the items of the top level folder).
So basically that means, that I can use:
var teamDrive = await graphClient.Groups[group.Id].Drive.Request().Expand(d => d.Root).GetAsync();

And then can iterate over the children with:
foreach(var childItem in teamDrive.Root.Children) { ... }
The following threads helped in finding the solution:

*

*Getting the drive's items from Microsoft Graph API: The request is malformed or incorrect

*Get all SharePoint files and folders of a drive using Microsoft Graph API


text:
Q: Django : TypeError at "?" __str__ returned non-string (type NoneType) I tried to make a crud using Django but i got error
TypeError at  "?" __str__ returned non-string (type NoneType)

the model :
from django.db import models

class Module(models.Model):
    Module = models.CharField("Module", max_length=255, blank = True, null = True)
    createdAt = models.DateTimeField("Created At", auto_now_add=True)

    def __str__(self):
        return self.Module

class Matiere(models.Model):
    Matiere = models.CharField("Matiere", max_length=255, blank = True, null = True)
    ModuleId = models.ForeignKey(Module, on_delete=models.CASCADE)
    createdAt = models.DateTimeField("Created At", auto_now_add=True)

    def __str__(self):
        return self.Matiere

the view error line:
__str__ returned non-string (type NoneType)
34

35

36                  <form method="post" novalidate>
37                      {% csrf_token %}
38                      {% for hidden_field in form.hidden_fields %}
39                      {{ hidden_field }}
40                      {% endfor %}
41                      {% for field in form.visible_fields %}
42

43                          {{ field.label_tag }}
44                          {% render_field field class="form-control" %}
45                          {% if field.help_text %}
46                          {{ field.help_text }}
47                          {% endif %}
48

49                      {% endfor %}
50                      <button type="submit" class="btn btn-primary">post</button>
51                  </form>
52

53

54

i don't know how to fix this error ,i searched for error its seems the error in the model exactly in return self the last line but i can't fix the issue , Could you help me please ?

A: Most likely that you're returning anything other than a string in yout __str__ function. I will first suggest you to try to change your field to a string while returning your fields.
Plus, your error sounds like that you didn't apply your migrations properly, and please double-check on that.


text:
Q: PHP unable to load Memcached extension due to json? It says "undefined symbol: php_json_encode" but json is installed already? also, when i add json.so to the php.ini, it say that module is already loaded?

A: Because you add json.so into php.ini and do not remove the php.d/json.ini
Error shows the reason: json.so should be loaded before memcached.so
Please use php -m | grep memcached to check whether memcached.so is loaded successfully.

*

*If it shows memcached, this means it has succeeded.

*If its show like PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/memcached.so' - /usr/lib64/php/modules/memcached.so: undefined symbol: php_json_decode_ex in Unknown on line 0
Here is the solution:
e.g. your php.ini is /etc/php.ini, your php.d is /etc/php.d/
Solution 1

*

*comment 'memcached.so' in php.ini

*vim /etc/php.d/memcached.ini

*add extension=memcached.so in /memcached.ini

*php -m | grep memcached to check whether memcached is successfully loaded

Solution 2

*

*rm /etc/php.d/json.ini

*add extension=json.so in php.ini before extension=memcached.so

*php -m | grep memcached to check whether memcached is successfully loaded


text:
Q: AngularJS and JQuery -- Combining $(document).ready(function()) with Angular Controller Help me understand this. I have an angular controller that essentially follows this construct:
angular.module('myApp', [])
    .controller('ListCtrl', function($scope, $timeout, $http){

    // Make calls to the API for Health List
    function initialFetch(){
        $http.get('healthInfo.json')
            .then(function(response){ $scope.healthinfo= response.data; });

    //More code here for color implementation
};

Essentially, I call a data source that lists items and an associated "value" between 0 and 100. In my front-end, I want to render this list and change the background color based on the associated value.
I have accomplished this in my JSFiddle, but I don't know how to combine this with my angular controller. Any thoughts?

A: $(document).ready(...) makes sure that your code gets executed when the page is ready (done loading).
Your controller function will also get executed when the page is ready. Does it work when you assume that .controller('ListCtrl', function($scope, $timeout, $http){ is the same as $(document).ready(...)? There shouldn't really be any difference, except of course how you pass data from your controller to your HTML (using $scope, for instance).

A: First, you don't need $(document).ready(). In fact, I would get rid of jQuery since both jQuery and Angular are DOM manipulation frameworks and will end up causing issues that are difficult to debug.
As for assigning the class based on value, you could use ng-repeat and a monster ng-class to apply the appropriate class based on the value. Here's a working example sans your web service call.

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.healthInfo = [{
        value: 23
      },
      {
        value: 10
      },
      {
        value: 39
      },
      {
        value: 88
      },
      {
        value: 57
      },
      {
        value: 94
      },
      {
        value: 69
      }
    ];
  });
.list-item {
  flex-grow: 1;
  width: 300px;
  padding: 20px;
  border: 1px solid white;
}

.value-range-0-10 {
  background-color: rgba(255, 0, 0, 0.5)
}

.value-range-11-20 {
  background-color: rgba(255, 77, 0, 0.5)
}

.value-range-21-30 {
  background-color: rgba(255, 128, 0, 0.5)
}

.value-range-31-40 {
  background-color: rgba(255, 179, 0, 0.5)
}

.value-range-41-50 {
  background-color: rgba(255, 230, 0, 0.5)
}

.value-range-51-60 {
  background-color: rgba(229, 255, 0, 0.5)
}

.value-range-61-70 {
  background-color: rgba(179, 255, 0, 0.5)
}

.value-range-71-80 {
  background-color: rgba(128, 255, 0, 0.5)
}

.value-range-81-90 {
  background-color: rgba(77, 255, 0, 0.5)
}

.value-range-91-100 {
  background-color: rgba(0, 255, 0, 0.5)
}

    <div class="list-item" ng-repeat="item in healthInfo" ng-class="{'value-range-0-10':item.value <= 10, 'value-range-11-20':item.value > 10 && item.value <= 20, 'value-range-21-30':item.value > 20 && item.value <= 30, 'value-range-31-40':item.value > 30 && item.value <= 40, 'value-range-41-50':item.value > 40 && item.value <= 50, 'value-range-51-60':item.value > 50 && item.value <= 60, 'value-range-61-70':item.value > 60 && item.value <= 70, 'value-range-71-80':item.value > 70 && item.value <= 80, 'value-range-81-90':item.value > 80 && item.value <= 90, 'value-range-91-100':item.value > 90}">{{item.value}}


text:
Q: How is this Firebase list displayed in order in the browser, even though JS objects are unordered? As far as I understand, JavaScript objects are an unordered collection of properties, whereas Firebase lists use IDs as property keys, which the docs say are chronologically ordered.
Taking Firebase's AngularFire chat code example (below), which stores messages as a Firebase list, the client presumably always displays the messages in the correct order, even though the object pointed to by $scope.messages is, I assume, a JavaScript object like any other.
How are the messages always displayed in the correct order?
angular.module("myChatRoom", ["firebase"])
  .factory("ChatService", ["$firebase", function($firebase) {
    var ref = new Firebase("https://<my-firebase>.firebaseio.com/chat");
    return $firebase(ref);
  }])
  .controller("ChatController", ["$scope", "ChatService",
    function($scope, chatService) {
      $scope.user = "Guest " + Math.round(Math.random()*101);
      $scope.messages = chatService;
      $scope.addMessage = function() {
        $scope.messages.$add({from: $scope.user, content: $scope.message});
        $scope.message = "";
      };
    }
  ]);

HTML:

{{message.from}}: {{message.content}}

    <form ng-submit="addMessage();">
      <input type="text" ng-model="message"/>
      <input type="submit" value="Send Message"/>
    </form>

Other Firebase examples use .on('child_added', cb) and new messages are added to an array in the callback, or are simply displayed. With these examples I understand how the messages are displayed in order as I'm guessing that the callback is passed the message snapshots in the order determined by Firebase. However that isn't the case with the example above.

A: Perhaps you can utilize the setPriority API to order your data. I believe with setPriority, children are sorted based on this priority using the following rules:

*

*Children with no priority come first.

*Children with a number as their priority come next. They are sorted numerically by priority (small to large).

*Children with a string as their priority come last. They are sorted lexicographically by priority.

*Whenever two children have the same priority (including no priority), they are sorted by

*name. Numeric names come first (sorted numerically), followed by the remaining names (sorted lexicographically).

So if you set the priority numerically for all your children, you can expect your set to behave in an ordered manner. Check docs on setPriority [here][https://www.firebase.com/docs/javascript/firebase/setpriority.html]

A: In general, objects are ordered correctly. There are only a couple of notable exceptions, like chrome's inexplicable handling of numeric keys. So your data appears correct because as long as you haven't run afoul of any of chrome's thick skull.
To ensure proper ordering when working with raw Firebase data, you can utilize forEach:
firebaseRef.once('value', function(snap) {
   snap.forEach(function(ss) {
      console.log(ss.name()); // prints names in guaranteed order
   });
});

The child_added events provide a prevChild that helps you order incoming values in your UI:
firebaseRef.on('child_added', function(snap, prevChild) {
   console.log('put ' + snap.name() + ' after ' + prevChild);
});

AnglularFire provides special tools for dealing with this. In the upcoming 0.8 release (releasing in a couple weeks), there will be a $asArray() method for getting sorted results in guaranteed order.
$scope.messages = $firebase(ref).$asArray();

And in the current iteration, you can utilize the orderByPriority filter (less efficient, but effective):

{{message|json}}


text:
Q: Why does WebView.InvokeScriptAsync throw exception 0x80020101 when calling an object added via AddWebAllowedObject? I have a UWP app in which I have defined the following class in a Windows Runtime Component project within my solution:
[AllowForWeb]
public sealed class WebViewCallback
{
    public string Cookie { get; set; }

    public void reportCookie(string cookie)
    {
        Cookie = cookie;
    }
}

From my main app assembly, I have a WebView (navigated to some URL) where I do the following:
private async void MyWebView_FrameDOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
{
    var callback = new WebViewCallback();
    MyWebView.AddWebAllowedObject("WebViewCallback", callback);

    await MyWebView.InvokeScriptAsync("eval", new[] { "WebViewCallback.reportCookie(document.cookie);" });
}

This throws 0x80020101 (SCRIPT_E_REPORTED), suggesting that the JS engine was not able to find (or not allowed to call) my callback object.
I suspect that somehow I'm not fulfilling the requirements for AddWebAllowedObject as documented in MSDN:

The object passed into AddWebAllowedObject must be imported from a
  Windows Runtime component that is separate from the app assembly. This
  is necessary for the AllowForWeb attribute to be property identified
  by the WebView security subsystem. If you use a class from your app
  project, AddWebAllowedObject does not work.

Is there maybe something else I need to do with my Windows Runtime Component assembly? I simply added it to my solution like I would any C# assembly.
I'm using VS2017 and Win10 Creators Update.

A: Figured it out! Apparently AddWebAllowedObject is very sensitive to when it is called. Everything works great if (and apparently only if) AddWebAllowedObject is called in the NavigationStarting event of the WebView. It will silently fail if it is called in some other event handler right before script that uses it is invoked (as I was doing in my repro code).


text:
Q: Smallest $1\ 000$ digit number $x$ , such that $x$ , $x+2$ and $x+6$ are all prime? I am currently searching for the smallest $1\ 000$ digit number $x$, such hat $x,x+2,x+6$ are all prime (Such a triple is also called a prime constellation). For this, I wrote this PARI/GP - program :
? x=prod(j=1,10,prime(j));z=prod(j=1,3*10^4,prime(j));a=10^999-1;gef=0;while(gef
==0,a=a+2;if(gcd(a*(a+2)*(a+6),x)==1,if(gcd(a*(a+2)*(a+6),z)==1,if(ispseudoprime
(a,1)==1,print(a-10^999);if(ispseudoprime(a+2,1)==1,print(a);if(ispseudoprime(a+
6,1)==1,gef=1))))))

Since my computer is not the fastest, I only arrived at about $x=10^{999}+491\cdot 10^6$ and found no triple.
My strategy was

*

*Checking that $x(x+2)(x+6)$ has no prime factor upto $29$

*Checking that $x(x+2)(x+6)$ has no prime factor upto the $30\ 000$ th prime

*Checking the numbers $x$,$x+2$,$x+6$ one after another.

Can I further accelerate the program ? Maybe, there is a sieve method suitable for this task.

Of course, I invite everyone to run the task on another, perhaps more powerful software. I will continue my search, but it could be still a long way to find the smallest triple.

A: There are fast sieve methods for finding prime clusters.  Generally these work with chunks of some primorial size, having built acceptable residues for the cluster.  E.g. mod 30 there are only 2 possible values for starting a triple (0,2,6), only 8 mod 210, 64 mod 2310, etc.  The larger the cluster, the fewer acceptable residues so the faster it works.  Unfortunately with a triple we don't get nearly the benefit from this method as we do with larger clusters.
Charles has some ideas and Pari/GP code for triplets in this post on Mersenneforum.
I have some code in Perl/ntheory that does a decent job of finding clusters.  I'm sure there is faster software, but I haven't found anything open source.  Separately some researchers currently working on this area include Sorenson, Waldvogel, and Wroblewski.  I've discussed ideas with Waldvogel and we seem to be doing basically the same thing, though it is hard to compare since their work, like the others, is closed source.
For your example, searching to 10^7 took 45 seconds with no solutions found.  That's only 2x faster than your code.  But there is also an example script that runs these in parallel, so on a fast machine we can get some linear speedup.
After about 2 hours it found 10^999 + 5537073001.

A: The most trivial of improvements is using the fact that $x$ (or $a$ in your program) must be $5$ modulo $6$ (it must be odd, and none of $x$, $x+2$, $x+6$ can be a multiple of $3$). So you can start $a$ at $10^{999}-5$ and increase it in steps of 6.
Sieving is also possible, and can replace the gcd calculations of your program. I suspect it will speed things up.
Simply set up an array of flags, representing the numbers $10^{999}$ to $10^{999}+n$. Then mark off all multiples of 2, all multiples of 3, all multiples of 5, ... all multiples of prime p, ... for however many primes you want to use. The numbers represented by the unmarked array entries are the remaining potential primes, so if you have $x$, $x+2$, $x+6$ unmarked you can primality-test them to see if they form a constellation.


text:
Q: How to adjust font size ord font alignment in col-md bootstrap I am a beginner but usually I somehow find a solution to my problem. But not this time.
I managed to code a box: Centered in the box there is the text "#01 Grunderna". This box looks nice.
#01 GRUNDERNA
However, when the text in the middle of the box is longer like "#02 Profil & Scensamlingar" then the text is overwrapping the box. Moreover, the text is not centered vertically.
#02 PROFIL & SCENSAMLING
Is there a way to be able to adjust this? I tried with font-size but it is still overwrapping the box, it is still not adjusted to the middle and the space between the lines stands the same.
Sorry for my lack of knowledge. Would be awesome to get some help.
By the way: Here you can see the mess
enter image description here

A: Remove the css rule padding: 1rem 1rem; from .home-service a. And add below css rule:
.home-service {
  display: flex;
  align-items: center;
  justify-content: center;
}

Links in those boxes will be justified vertically and horizontally.
If you are using bootstrap, you may make use of the classes it provides. Check this page: https://getbootstrap.com/docs/5.0/utilities/flex/ especially "Justify content" and "Align items" sections. If you want to dig deeper about how flex in css works, check this link https://css-tricks.com/snippets/css/a-guide-to-flexbox/ then bookmark it for future use:)

A: Thank you so very much for solving my problem. It is like magic :) You should see my smile!
Anyway, I added it as additional css in the customize theme section as I did not find it in the theme editor yet.
I guess it is better to do the changes exactly as you mentioned in the theme-editor or does it not matter?


text:
Q: Remove default pi flexform fields from plugin configuration - typo3 I created a typo3 extension.I have a flex form for configuring my pluggin.The form contains some default typo3 configuration like pluggin mode,storage folder and recursive.I want to hide these fields.How can it is possible?

A: Try the following in your ext_tables.php file
$TCA['tt_content']['types']['list']['subtypes_excludelist'][$pluginSignature] = 'recursive,select_key,pages';


text:
Q: GraphicsMagick / ImageMagick replace all non-transparent pixels (like Photoshop's Color Overlay) I'm trying to replace all non-transparent pixels to a given color using GraphicsMagick for Node.
Using a composite image is not an option, I simply need to change every non-transparent pixel to a given color.
Original image:

Goal:

Transparent pixels should stay transparent. I'm trying to achieve Photoshop's Color Overlay effect:

A: This is a bit simpler. In ImageMagick do the following:
convert 84xHk.png -fill "#E91FCB" +opaque none result.png

A: I'm not familiar with Node's GraphicsMagick library, but there are a few methods to achieve this. Here's a few I can think of...
Extract alpha, and replace colors
convert 84xHk.png -alpha extract \
        -negate -fill '#E91FCB' -fuzz 50% \
        -opaque black output.png

Create solid color image, and copy alpha channel
convert 84xHk.png \
       \( +clone -alpha off \
          -fill '#E91FCB' \
          -draw 'color 0,0 reset' \
       \) +swap -compose CopyOpacity -composite output.png

Use FX expressions
 convert 84xHk.png -fx 'p.a==1?#E91FCBFF:#E91FCB00' output.png


text:
Q: Using a class as props in a react native component I'm learning react (coming from a native iOS/Swift background) and I'm a bit confused about something I can't get to work.
I have a component that accepts props, so I figured I would write a class to model those props:
class HeaderProps {
  text: string;
  constructor(headerText:string) {
    this.text = headerText;
  }
}

// Make a component
const Header = (props:HeaderProps) => {

  const { textStyle, viewStyle } = styles;

  return (
    <View style={viewStyle}>
      <Text style={textStyle}>{props.text}</Text>
    </View>
  );
};

and I'm exporting from my component like so:
export {Header, HeaderProps};

I'm then importing it:
import {Header, HeaderProps} from './src/components/header';

// Create a component
const App = () => ( <Header headerText={ new HeaderProps('Album') } />);

No text is appearing in my component.
If I just pass a string through as props it works fine, can't think of any reason why sending a class through wouldn't work.
I'm using flow type to declare the types of my arguments, not sure if that might be causing any issues.
A point in the right direction would be much appreciated!


text:
Q: Oracle SQL Developer does not show the grids in the query result When executing a query on Oracle SQL Developer the result is text rather than a grid. I'd like it to display a grid, but I do not know how to display them.

A: That's because you're pressing F5, which is "Run Script" command.
You need to press green triangle at the top, or CTRL+Enter shortcut.


text:
Q: Can't attach event handler on VoiceConnection in Discord.js In short: I have been trying to make some UI in electron (electron-react-boilerplate) for my discord bot. The bot should connect to voice channel and on command, play some mp3 files into the mic. I've made it work in development, but not in production. Whenether i run npm run package, it packages the app, and exactly when the connection is established (bot actually connects and is in the channel), I cannot attach the ".on('event', fn)" to this connection.
The original error states:
Cannot read properties of undefined (reading 'handle')
at Object.t [as VOICE_STATE_UPDATE]
https://imgur.com/a/V5jCj2d
Here's the snipper of connection function:
public static async joinVoice(guildId: string, id: string) {
    if (this.currentVoiceConnection) {
      this.currentVoiceConnection.destroy();
    }

    constguild = this.client.guilds.cache.get(guildId);

    if (!guild) {
      throw new Error('This channel does not exist.');
    }

    const channel = guild.channels.cache?.get(id);

    if (!channel) {
      throw new Error('This channel does not exist.');
    }

    // connection is created here.
    // bot actually connects and is in the channel!
    const connection = joinVoiceChannel({
      channelId: channel.id.toString(),
      guildId: guild.id.toString(),
      adapterCreator: channel.guild.voiceAdapterCreator,
    });

    // does get here after initializing connection

    connection.once(VoiceConnectionStatus.Ready, () => {
    // DOES NOT ENTER HERE
      console.log('Connected to voice! ');

      connection.subscribe(this.audioPlayer);

      this.audioPlayer.on('error', (err) => {
        console.log(err);
      });
    });

    connection.on('stateChange', (prev, next) => {
    // DOES NOT ENTER HERE
      console.log(prev, next);
    });

    connection.on(VoiceConnectionStatus.Disconnected, async () => {
      // DOES NOT ENTER HERE
      try {
        await Promise.race([
          entersState(connection, VoiceConnectionStatus.Signalling, 5_000),
          entersState(connection, VoiceConnectionStatus.Connecting, 5_000),
        ]);
      } catch (error) {
        connection.removeAllListeners();
        connection.destroy();
      }
    });

    this.currentVoiceConnection = connection;

    return true;
  }

This is what the connection varible is in the production debug console:
VoiceConnection {
  _events: [Object: null prototype] {}, // <<< EMPTY??
  _eventsCount: 0,
  _maxListeners: undefined,
  rejoinAttempts: 0,
  _state: {
    status: 'signalling',
    adapter: {
      sendPayload: [Function: sendPayload],
      destroy: [Function: destroy]
    }
  },
  joinConfig: {
    selfDeaf: true,
    selfMute: false,
    group: 'default',
    channelId: '946026122380972076',
    guildId: '946026122380972072',
    adapterCreator: [Function (anonymous)]
  },
  packets: { server: undefined, state: undefined },
  receiver: VoiceReceiver {
    voiceConnection: [Circular *1],
    ssrcMap: SSRCMap {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      map: Map(0) {},
      [Symbol(kCapture)]: false
    },
    subscriptions: Map(0) {},
    connectionData: {},
    speaking: SpeakingMap {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      users: Map(0) {},
      speakingTimeouts: Map(0) {},
      [Symbol(kCapture)]: false
    },
    onWsPacket: [Function: bound onWsPacket],
    onUdpMessage: [Function: bound onUdpMessage]
  },
  debug: null,
  onNetworkingClose: [Function: bound onNetworkingClose],
  onNetworkingStateChange: [Function: bound onNetworkingStateChange],
  onNetworkingError: [Function: bound onNetworkingError],
  onNetworkingDebug: [Function: bound onNetworkingDebug],
  [Symbol(kCapture)]: false

I've been banging my head about this problem for a couple of days now, never have I ever wrote a question on stackoverflow, and this is my last option. What am i missing here?
I've tried different recommended packages for @discord/voice.
I've tried migrating to a fresh electron-react-boilerplate project, with all of my files.
I've did install ffmpeg for discord audio.
I've tried getting voice connection with getVoiceConnection.


text:
Q: GStreamer recording a stream to a wav file with wrong duration I'm recording a wav file using GStreamer receiving G711 flow through a UDP port.
Any wav player can play the file, but shows a wrong duration and cannot fast forward.
I believe that GStreamer writes the header at the beginning with empty data.
This pipeline can reproduce the issue:
gst-launch-1.0 udpsrc port=3000 caps="application/x-rtp,media=(string)audio, payload=0,clock-rate=(int)8000" ! rtpjitterbuffer ! rtppcmudepay ! mulawdec ! wavenc !  filesink append=true location=c:/recordings/audio-zz.wav

Florian Zwoch suggested to use -e and the file will be closed properly.
  Indeed it works perfectly.
I'm using this pipeline inside a Java program with the gst1-java-core library.
  Seems that I'm missing something closing the pipeline.
  My program has the same behaviour as gst-launch without -e parameter.
Before stopping the pipeline I send an EOS Event.
pipeline.sendEvent(new EOSEvent());
How can I fix it?
The append parameter of filesink element does not allow rewriting the header.
Thank you.

A: How do you stop the pipeline? If you interrupt the pipeline with ctrl-c it may indeed be that the header finalization is skipped. Run your pipeline with the -e option so that on ctrl-c your pipeline gets stopped gracefully.


text:
Q: Netcdf timeseries subplots using cartopy and geopandas I am unable to 24 timesteps subplots in one page using for loops. The subplots are ploting in the first row only. There is np errors in the code.
from netCDF4 import Dataset;import numpy as np;
from shapely.geometry import Polygon;from cartopy.io import shapereader;
import cartopy.io.img_tiles as cimgt;import cartopy.crs as ccrs;
import geopandas;import matplotlib.pyplot as plt
def rect_from_bound(xmin, xmax, ymin, ymax):
    """Returns list of (x,y)'s for a rectangle"""
    xs = [xmax, xmin, xmin, xmax, xmax]
    ys = [ymax, ymax, ymin, ymin, ymax]
    return [(x, y) for x, y in zip(xs, ys)]

resolution='10m'; category='cultural'; name='admin_0_countries';
countries= ['Ivory Coast', 'Ghana', 'Nigeria', 'Cameroon'];
shpfilename = shapereader.natural_earth(resolution, category, name)
df=geopandas.read_file(shpfilename);extent=[-20, 18, 0, 25];
fig, axs = plt.subplots(nrows=6, ncols=4, figsize=(20, 25), subplot_kw={'projection': ccrs.PlateCarree()})
for country, ax in zip(countries, axs.flatten()):
    poly = [df.loc[df['ADMIN'] == country]['geometry'].values[0]]
    st_proj = ccrs.PlateCarree(); ll_proj = ccrs.PlateCarree();
    ax.add_geometries(poly, crs=ll_proj, facecolor='none', edgecolor='black');
    pad1 = 0.3; exts = [poly[0].bounds[0] - pad1, poly[0].bounds[2] + pad1, poly[0].bounds[1] - pad1, poly[0].bounds[3] + pad1];
    ax.set_extent(exts, crs=ll_proj); msk = Polygon(rect_from_bound(*exts)).difference(poly[0].simplify(0.01));
    msk_stm = st_proj.project_geometry(msk, ll_proj); ref_dat = Dataset("era5_wa.nc", mode='r');
    lat = ref_dat.variables["latitude"][:];lon = ref_dat.variables["longitude"][:];
    time = ref_dat.variables["time"];t2 = ref_dat.variables["t2m"][:, :] - 273.15;
    nlon, nlat = np.meshgrid(lon, lat);
    for i in range(24):
        hour = i * 3600
        p = ax.contourf(nlon, nlat, t2[hour % 24, :, :], np.arange(10, 48, 2), transform=ccrs.PlateCarree(), cmap='jet')
        cbar = plt.colorbar(p, ax=ax, orientation='horizontal')
        cbar.set_label('Temperature [C]', rotation=0, fontsize=12, labelpad=1)
        cbar.ax.tick_params(labelsize=12, length=0)
        ax.add_geometries(msk_stm, st_proj, zorder=20, facecolor='white', edgecolor='none', alpha=1.)
        ax.set_title(country + ' ' + str(i) + 'h')
plt.tight_layout()
plt.show()


text:
Q: php setting session variables from form This is my main report page where I am sending session variables to another php page. I am running into issues when I try and post the form data to the session variables because then the query returns nothing. I have been searching and tinkering for a few days now but no results.
<!DOCTYPE html>
    <?php
      session_start();
     /* this works when the session variables are static*/
     $_SESSION["date"] = '2012-05-01';
     $_SESSION["ServiceOrders"] ='Network Error';
     /* when I try and post the form values the query returns nothing
      $_SESSION["date"] = $_POST['sdate'];
      $_SESSION["ServiceOrders"] =   $_POST['ServiceOrders'];
     */

    ?>

      <link rel='stylesheet' type='text/css' href='styles.css' />
      <link rel="stylesheet" href="grid.css" type="text/css" />
      <link rel="stylesheet" href="backgroundcss.css" type="text/css" />

    <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

  </script>

Home

Contacts

Inbound Calls Codes

Contact Free Form

Service Orders

Company Service Orders

Vendor Service Orders

Ad Hoc Report Builder

<form action="ServiceOReport.php" method="post">
<select name="ServiceOrders">
  <option value="Network Error">Network Error</option>
  <option value="Reverse Rotation Detected">Computer Failure</option>
  <option value="Cover Off">Misc</option>
  <input type="text" name="sdate"id="datepicker" >
  <input type="submit" id ="refresh" value=" Submit "/>

</select>
</form>

Copyright © 2014 Test

This is my ServiceOReport.php page where I am taking the session variables and executing them in the query.

      <link rel='stylesheet' type='text/css' href='styles.css' />
      <link rel="stylesheet" href="grid.css" type="text/css" />
      <link rel="stylesheet" href="backgroundcss.css" type="text/css" />

        <?php
 session_start();

        // Make a MySQL Connection
    mysql_connect("localhost", "****", "********") or die(mysql_error());
    mysql_select_db("Test_DB") or die(mysql_error());

    $ServiceOrders= $_SESSION["ServiceOrders"];
    $string=$_SESSION["date"];
    $timestamp = strtotime($string);
    $correctedDate = date("Y-m-d H:i:s", $timestamp);

    $result = mysql_query("Select EquipmentID,StreetNumber,StreetName,City,ZipCode,ZipPlusFour,CreatedDate,ServiceOrderdesc
                            From CSS_ServiceOrders
                            Where ServiceOrderdesc = '$ServiceOrders' and CreatedDate > '$correctedDate'
                            order by CreatedDate,StreetName,StreetNumber;")
    or die(mysql_error());

    echo '

        EquipmentID
        ZipPlusFour
        StreetNumber
        StreetName
        City
        ZipCode
        CreatedDate
        ServiceOrderdesc

';

    // keeps getting the next row until there are no more to get
    while($row = mysql_fetch_array( $result )) {

        echo "
";
        echo $row['EquipmentID'];
        echo "	";
        echo $row['ZipPlusFour'];
        echo "	";
        echo $row['StreetNumber'];
        echo "	";
        echo $row['StreetName'];
        echo "	";
        echo $row['City'];
        echo "	";
        echo $row['ZipCode'];
        echo "	";
        echo $row['CreatedDate'];
        echo "	";
        echo $row['ServiceOrderdesc'];
        echo "
";

    }

    echo "

";
?>

A: You must put session_start() at the top of the page before any output.
<?php
    session_start();
?>
<!DOCTYPE html>
<?php

and
<?php
    session_start();
?>

      <link rel='stylesheet' type='text/css' href='styles.css' />
      <link rel="stylesheet" href="grid.css" type="text/css" />
      <link rel="stylesheet" href="backgroundcss.css" type="text/css" />

        <?php

A: As @John said you need to put session_start() at the beginning of the file the main reason for this is as soon as the interpreter sees any non PHP code or echo, it sends out the headers. It has to otherwise it cant send anything but once the headers are sent they cant be resent.
PHP sessions rely heavily on headers, it has to to set and make the page send over cookie details so it knows which session it has to look up.
Make sure there are no spaces or empty lines before you php tag and that there are no echos before your session_start() command. These are hard to debug, easy to make a mistake with so I always mention them to people.


text:
Q: I need to iterate table using css selectors
I am trying to automate a page using selenium webdriver. The page contains a table which has the following xpath.
Find below a sample xpath validation which works fine.
I am iterating it through div as rows are considered as div under which there will be a table which has all the rows mentioned.
table = common.getObjectByXpath("html/body/div[4]/div[4]/div[1]/div/div/div[3]/div/div[2]/div/div/div/div");
rows = table.findElements(By.tagName("div"));

    for(int i=1;i<=rows.size();i++){
        if(driver.findElement(By.xpath("html/body/div[4]/div[4]/div[1]/div/div/div[3]/div/div[2]/div/div/div/div/div["+i+"]/table/tbody/tr/td[5]/span").getText().equals("endnode 11.1"))){
            System.out.println(" print Something");
        }
    }

It works fine with xpath. But I want to do it with css selector. I am attaching the sample format of the table.
In the below figure, each div is considered as a row and under which you will see a table which has entries for columns.

A: The xpath you are using is a very fragile one since it starts right from the html element and heavily depends on the HTML structure of the page. Needless to say - it is huge and is not quite readable and easily understandable.
Instead rely on the element attributes - classes or ids. For example:
div#dojox_grid__View_11 div.dojoxGridContent div.dojoxGridRow


text:
Q: Vagrant provisioning Noobie question. I am attempting to write a shell script for my Vagrantfile that loading a database exported, self contained file after the server environment is built. The goal is to build the server, install mariadb, and then load a self contained sql file to populate the database with data.
I added a bootstrap.sh file to the directory with my Vargantfile and in it I added the sequence I do to access the mysql cli. My question is, I know when I put mysql -u username -p, it prompts my next action as the password. Can I put that on the second line to run next or is there something I need to add since its a password prompt.
Something like (bootstrap.sh):
#!/usr/bin/env bash

mysql -u username -p
secret-password

Any advice or links to better information is greatly appreciated.

A: You can put the password on the same command line:
mysql --user='username' --password='password' ...

But I prefer not to put passwords on the command-line. Instead, I create a defaults file containing the credentials. Here's the format of such a file:
[client]
user = <username>
password = <password>

The mysql client will automatically read options from your global /etc/my.cnf file or the current user's $HOME/.my.cnf. You can also use a flag to give a specific alternative option file. For example:
mysql --defaults-file=/vagrant/my.cnf ...

See https://dev.mysql.com/doc/refman/5.7/en/option-files.html
If you want to be even more secure, and you're using MySQL 5.6 or later, you can create an encrypted file containing the credentials. Then use another option to read it:
mysql --login-path=/vagrant/mylogin.cnf ...

See https://dev.mysql.com/doc/refman/5.7/en/mysql-config-editor.html for details on how to create the mylogin.cnf file.


text:
Q: How to use oneof as a type in proto3? Given a message that looks like this,
message Event {
    required int32 event_id = 1;

    oneof EventType {
        FooEvent foo_event = 2;
        BarEvent bar_event = 3;
        BazEvent baz_event = 4;
    }
}

I want to define another map which uses the EventType oneof as a type. Precisely, I want to define something like this
message Sample {
    map<string, Event.EventTypeCase> someMap = 1;
}

But, this is not working. I get the error that
PROTOC FAILED: "Event.EventTypeCase" is not defined.

A:
I want to define another map which uses the EventType oneof as a type.

It isn't a type in the DSL, so: you can't. It is a conceptual grouping of fields in a specific message. The existence of Event.EventTypeCase is an implementation detail, not something that is not even mentioned in the DSL specification as far as I know (although protoc may or may not detect conflicts if you define your own enum or message with the same name)


text:
Q: get value of selected  element in dart how i can obtain selected option of  element?
document.query("#id") - returns Element which hasn't value propery
so i can't do:
var val = document.query("#id").value;

var val = (SelectElement)(document.query("#id")).value; // - "SelectElement is class and cannot be used as an expression"

how to do type conversion in dart correctly?

A: In general, when dealing with any HTML element, I usually query the HTML element first:
InputElement myElement = document.query(#myInputElement);

Then use some event to capture the value contained in that element:
int val = Math.parseInt(myElement.value);

So for example, in HTML I could have an input element of type range:
<input id="mySlider" type="range" min="1000" max="10000" step="20" value="5000" />

In Dart, I would grab the value of this slider using a mouse up event:
InputElement mySlider = document.query('#mySlider');
mySlider.on.mouseUp.add((e) {
  int _val = Math.parseInt(mySlider.value);
  document.query('#status').innerHTML = "$_val";
});

Edit: In M1, you can now just use the cast operator as.  If your HTML looked like this:

This is some text

You could retrieve the text from the paragraph tag by doing this:
String str = (query('#text') as ParagraphElement).text;

A: just need:
String str = document.query("#idOfSelect").value;

will be warning, but you can ignore it

A: I used:
var val = int.parse(query("#id").value, onError: (_) => 1);
This prevents an exception in case query("#id").value is null and assigns a default value (1).


text:
Q: VARIANT data type size limit What is the size limit imposed by VARIANT data type? 16MB compressed or 16MB uncompressed?
There are two places in the documentation which are conflicting. Which is correct ?

A: AFTER
The VARIANT data type imposes a 16 MB (compressed) size limit on individual rows.
https://docs.snowflake.net/manuals/user-guide/semistructured-considerations.html

A: This is one of the most common misunderstandings about variant columns ( thanks to the repeating error in the docs). A VARIANT can store values to a maximum size of 16 MB uncompressed.
https://docs.snowflake.com/en/sql-reference/data-types-semistructured.html#variant
The above page is updated recently, and you can see that the older version had the same error:
https://web.archive.org/web/20210522195216/https://docs.snowflake.com/en/sql-reference/data-types-semistructured.html
The limitation comes from a 16 MB limit on "internal" in-memory representation, which is uncompressed. I will report the one which is misleading:
https://docs.snowflake.com/en/user-guide/semistructured-considerations.html


text:
Q: How to change math font to monospace, only inside \texttt Related with "Can I change all math output to use monospaced text?", is it possible to use the monospace math only inside \texttt (or other custom command)?
I tried to include the \everymath inside a group, but it seems it's not working until after I use some math:
\documentclass{minimal}
\usepackage{amsmath}
\newcommand{\ttmath}{\everymath{\mathtt{\xdef\tmp{\fam\the\fam\relax}\aftergroup\tmp}}}
\newcommand{\val}[1]{\bgroup\ttmath\texttt{#1}\egroup}
\begin{document}

\val{1\ensuremath{\ensuremath{\cdot}10\ensuremath{^{-6}}}}

\ensuremath{a_0}, \ensuremath{m_{\text{e}}}).

\val{1\ensuremath{\ensuremath{\cdot}10\ensuremath{^{-6}}}}

\end{document}

Note that the first 10^-6 does not use monospace font, but the second does. a_0 and m_e use normal math font, which is fine.
I can get it fixed by adding \ensuremath{} between \ttmath and \texttt, but is there a cleaner way?
PS. Please forgive the ugly code full of \ensuremath, it's being generated from XML.
PPS. Without XeTeX or LuaLaTeX, please.

A:
You just need to encourage latex to initialise the font setup in scriptstyle as well as the main textstyle. As you notice, it doesn't do this until it thinks it is needed:
\documentclass{minimal}
\usepackage{amsmath}
\newcommand{\ttmath}{%
  \everymath{%
    {\scriptstyle\mathtt{}}%
    {\scriptscriptstyle\mathtt{}}%
    \mathtt{\xdef\tmp{\fam\the\fam\relax}\aftergroup\tmp}}}
\newcommand{\val}[1]{\bgroup\ttmath\texttt{#1}\egroup}
\begin{document}

\val{1\ensuremath{\ensuremath{\cdot}10\ensuremath{^{-6}}}}

\ensuremath{a_0}, \ensuremath{m_{\text{e}}}).

\val{1\ensuremath{\ensuremath{\cdot}10\ensuremath{^{-6}}}}

\end{document}


text:
Q: Who are these people from V for vendetta? Who are the two people each in the picture from v for vendetta? I guess the second one is gordon deitrich.

A: They appear to be The Leader (Adam Susan) and Gordon Dietrich. Note that both of these are ridiculous, not least because Evey saw Gordon dead.


text:
Q: С чего начать изучение API? У меня такая ситуация,  У нас есть 1  урок по ASP.Net и другой урок по разработке Android приложений, и я хочу написать веб  приложение на ASP и его мобильное прил. для Android. И препод  говорит что можно просто добавить API от веб приложения в мобилку и чтоб  вся обработка шла туда. То есть  написать бэк-енд на ASP и использовать его и в мобильном андроид  приложении(хотя бэк Андроида вроде на Java). Как это сделать или как правильно задавать вопросы гуглу или как искать уроки по этой теме ??

A: Если вы будете самостоятельно писать бэк для своего приложения то начинать нужно с изучения всего что связано с серверной частью. Если же вам уже будут давать готовое апи для вашего приложения, то нужно начинать изучать принципы отправки запросов на сервер и обработки его ответов. Я на данный момент занимаюсь разработкой клиент-серверного приложения, и мне дают документацию по апи, где прописаны все запросы необходимые для полного замещения веб-сервиса моим приложением. Для работы с апи я использую библиотеку Retrofit, хотя есть и Volley - это уже кому какая придется по душе. Лично я бы вам советовал начать читать про сами клиент-серверные приложения. Библиотеку я вам посоветую использовать Retrofit потому-что она более удобная и гибкая, и лично мне более понятна в использовании. Ниже я привожу несколько ссылок которые облегчат выполнение ваших задач:

*

*Инструмент для создания классов-моделей, которые будут использоваться в запросах.

*Сервис, который показывает структуру вашего ответа с сервера.

*Туториал для работы с ретрофитом.

*Статья по библиотекам которые я указывал.

*Еще статья по работе с retrofit
Надеюсь хоть чем-то помог, если будет что-то не понятно - не стесняйтесь и спрашивайте. Удачи, я верю что у вас все получится :)


text:
Q: Python - Searching items in a text file I am writing a script in Python that searches a text file for various items and once it finds the item it moves onto the next.  In this case I am finding a person then the items attributed to that person.  But what is happening is I keep getting the first person repeated the amount of times a person is found in the list.  I was able to do this successfully with other items outside of finding the person but it seems that when it comes to finding the person, it repeats.  Please see what I have so far.  I have stripped everything that works out just to concentrate on this one particular issue.
    text = open("Register.txt",'rt') #opens the Register text file
    Register = text.read()

    length = len(Register)
    lines = Register.splitlines() #Breaks the .txt file down into their own lines

    for line in lines: #searches each line for the following statement
        if line.find("Per End")!=-1:  #searches each line for the ("*") item and asks if it is True
            nameline = Register.index(line)
            namebegin = nameline-15
            print nameline
            print Register[namebegin:nameline]

There are about 60 people in the text and this code will only list the first one 60 times. Each one is followed by the "Per End" which is why I used it to find the people in the text.  From there it is supposed to locate the index and subtract by a few items to make sure the whole name outputs.


text:
Q: (1/1) ErrorException array_merge(): Argument #2 is not an array in ProviderRepository.php line 95 My site is working on local but when I merge live on it shows the error (1/1) ErrorException array_merge(): Argument #2 is not an array  in ProviderRepository.php line 95
I have tried the solution from google StackOverflow, GitHub but most of them solved the problem by deleting the file services.json
but in my bootstrap/cache it doesn't create
any alternate solution???


text:
Q: how to select element or delete output string I have a json contents
 "objects" : [ {
    "uid" : "2272dba0-9ffb-49d4-88b7-0a18f38a3cdc",
    "name" : "All_Internet",
    },
    {
    "uid" : "b83fd31c-3cb3-406e-b46b-816a138e8ea1",
    "name" : "Public FTP",
  } ]

I used :
jq '.objects[] | .name

and got the resule:
"All_Internet"
"Public FTP"

how to select the secondary "name" string, or removing the first "name" "All_Internet" of output
the "All_Internet" is fixed string.
Regards and thanks

A: It's unclear whether you want an answer like @KiranKandel's, namely:
.objects[].name | select(. != "All_Internet")

or something like:
.objects[1:][].name


text:
Q: Returning most recent record, grouped by one field whilst returning another I'm trying to return the most recent record grouped on a specific ID, but I need to return the unique identifier (change_guid) from each returned record so that I can use it later.
Using the below correctly returns 28,908 records:
SELECT account_id, MAX(InsertDateTime) FROM change_records_archive WHERE change_type = 'Programme' GROUP BY account_id

I need to somehow include change_guid so without including it in the grouping. I've considered using an OUTER/CROSS apply, returning the Top 1 per account_id ordered by InsertDateTime Desc, but that doesn't apply the 'grouping' correctly.
Can someone please advise on what the best approach is for this?


text:
Q: Excel Scrolling Marquee vb script not working with formatted text We've tried various vb scripts to scroll text in a range of cells in Excel 2010. I found a great one we could tweak but, unfortunately, I can only get this to work with text that has no formatting to it. I also can't seem to get it to repeat the text with no gaps.
I've attached a screen shot of what the text looks like in the format we'd like to scroll it.
It does work with a picture of the copied cells entered into the target range, but, the edge of the excel spreadsheet cuts off the picture scrolling from off screen.
HELP! We're not serious coders by any means. Can anyone point us in the right direction? If it isn't possible, that would be great to know as well.
Thanks for any suggestions.
scrolling marquee text with formatting
    Option Explicit

Private Type POINTAPI
    x As Long
    y As Long
End Type

Private Type RECT
    Left As Long
    Top As Long
    Right As Long
    Bottom As Long
End Type

Private Declare Function FindWindow Lib "user32.dll" _
Alias "FindWindowA" _
(ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long

Private Declare Function FindWindowEx Lib "user32.dll" _
Alias "FindWindowExA" _
(ByVal hWnd1 As Long, _
ByVal hWnd2 As Long, _
ByVal lpsz1 As String, _
ByVal lpsz2 As String) As Long

Private Declare Function GetDeviceCaps Lib "gdi32" ( _
ByVal hdc As Long, _
ByVal nIndex As Long) As Long

Private Declare Function GetDC Lib "user32" _
(ByVal hwnd As Long) As Long

Private Declare Function ReleaseDC Lib "user32" ( _
ByVal hwnd As Long, _
ByVal hdc As Long) As Long

Private Declare Function CreateCompatibleDC Lib "gdi32" _
(ByVal hdc As Long) As Long

Private Declare Function CreateCompatibleBitmap Lib "gdi32" _
(ByVal hdc As Long, _
ByVal nWidth As Long, _
ByVal nHeight As Long) As Long

Private Declare Function SelectObject Lib "gdi32" _
(ByVal hdc As Long, _
ByVal hObject As Long) As Long

Private Declare Function DeleteObject Lib "gdi32" _
(ByVal hObject As Long) As Long

Private Declare Function BitBlt Lib "gdi32" _
(ByVal hDestDC As Long, _
ByVal x As Long, _
ByVal y As Long, _
ByVal nWidth As Long, _
ByVal nHeight As Long, _
ByVal hSrcDC As Long, _
ByVal xSrc As Long, _
ByVal ySrc As Long, _
ByVal dwRop As Long) As Long

Private Declare Function ScreenToClient Lib "user32" ( _
ByVal hwnd As Long, _
lpPoint As POINTAPI) As Long

Private Const SRCCOPY As Long = &HCC0020
Private Const LOGPIXELSX As Long = 88
Private Const LOGPIXELSY As Long = 90
Private Const POINTSPERINCH As Long = 72

Private tPrevRect As RECT
Private oTargetCell As Range
Private bStop As Boolean
Private bRangeRectHasChanged As Boolean
Private vNumberFormat As String
Private vHorzAlignment As Long
Private lMemoryDC As Long
Private lWBHwnd As Long
Private i As Long

Public Sub StartScrollingRow()

    '//Scroll the text in Cell Range from Right to Left.
    Call ScrollCell(Range("B4:R4"), 0.01, True)

End Sub

Private Sub TakeCellSnapShot(Target As Range)

    Dim lDC As Long
    Dim lXLDeskhwnd As Long
    Dim lBmp As Long

    '//Get the workbook Wnd hwnd.
    lXLDeskhwnd = _
    FindWindowEx(FindWindow("XLMAIN", Application.Caption) _
    , 0, "XLDESK", vbNullString)
    lWBHwnd = FindWindowEx _
    (lXLDeskhwnd, 0, "EXCEL7", vbNullString)

    '//Get the Wbk window DC.
    lDC = GetDC(lWBHwnd)

    '//Create a memory DC.
    lMemoryDC = CreateCompatibleDC(lDC)

    '//Get the target cell metrics in pixels.
    tPrevRect = GetRangeRect(ByVal Target)

    With tPrevRect

        '//create a compatible Bmp the same size as the target cell.
        lBmp = CreateCompatibleBitmap _
        (lDC, (.Right - 1 - .Left), (.Bottom - .Top))

        '//Select the Bmp onto our mem DC.
        DeleteObject SelectObject(lMemoryDC, lBmp)

        '//Copy the target cell image onto the Mem DC.
        BitBlt lMemoryDC, 0, 0, (.Right - .Left), (.Bottom - .Top), _
        lDC, .Left, .Top, SRCCOPY

    End With

    '//CleanUp.
    ReleaseDC 0, lDC
    ReleaseDC lMemoryDC, 0

End Sub

Private Sub ScrollCell _
(ByVal Target As Range, ByVal Delay As Single, _
Optional ByVal RightToLeft As Boolean)

    '//Make sure the target range is one Cell.
    If Target.Cells.Count < 1 Then Exit Sub

    bStop = False

    '//Store the target cell for later use.
    Set oTargetCell = Target

    '//Unselect the target cell to avoid the selection borders.
    If ActiveCell.Address = _
    Target.Address Then oTargetCell.Offset(1).Select

    If Not bRangeRectHasChanged Then

        vHorzAlignment = Target.HorizontalAlignment

        Target.HorizontalAlignment = xlLeft

    End If

    '//copy the target cell image onto memory.
    Call TakeCellSnapShot(Target)

    If Not bRangeRectHasChanged Then

        vNumberFormat = Target.NumberFormat

        Target.NumberFormat = ";;;"

        '//call the text scrolling routine.
        Call UpdateCell(Target, Delay, RightToLeft)

    End If

End Sub

Private Sub UpdateCell _
(ByVal Target As Range, ByVal Delay As Single, _
Optional ByVal RightToLeft As Boolean)

    Dim lDC As Long

    '//store the Wbk window DC.
    lDC = GetDC(lWBHwnd)

    '//Scroll the Target Cell Text.
    Do

        '//Do nothing if not on the target sheet.
        If ActiveSheet Is oTargetCell.Parent Then
            '//Update the tPrevRect Struct if the Target Cell
            '//screen location/size have changed.
            If tPrevRect.Left <> GetRangeRect(Target).Left Or _
            tPrevRect.Top <> GetRangeRect(Target).Top Or _
            tPrevRect.Right <> GetRangeRect(Target).Right Or _
            tPrevRect.Bottom <> GetRangeRect(Target).Bottom Then
                bRangeRectHasChanged = True
                tPrevRect = GetRangeRect(Target)
                Target.NumberFormat = vNumberFormat
                ScrollCell oTargetCell, Delay
                Target.NumberFormat = ";;;"
            End If

            '//do the actual text scrolling here.
            With tPrevRect

                If RightToLeft Then
                    BitBlt lDC, .Left + 1, .Top, (.Right - .Left), _
                    (.Bottom - .Top), _
                    lMemoryDC, i - (.Right - .Left), 0, SRCCOPY
                Else
                    BitBlt lDC, .Left, .Top, (.Right - .Left), _
                    .Bottom - .Top, _
                    lMemoryDC, (.Right - .Left) - i, 0, SRCCOPY
                End If

                If i >= (.Right - .Left) * 2 Then i = 0

            End With

            i = i + 1
            SetDelay Delay  'Secs.

        End If

        DoEvents

    Loop Until bStop

    ReleaseDC 0, lDC

End Sub

'//===============================
'// Other Supporting routines...
'//===============================
Private Function ScreenDPI(bVert As Boolean) As Long

    Static lDPI(1), lDC

    If lDPI(0) = 0 Then
        lDC = GetDC(0)
        lDPI(0) = GetDeviceCaps(lDC, LOGPIXELSX)
        lDPI(1) = GetDeviceCaps(lDC, LOGPIXELSY)
        lDC = ReleaseDC(0, lDC)
    End If

    ScreenDPI = lDPI(Abs(bVert))

End Function

Private Function PTtoPX _
(Points As Single, bVert As Boolean) As Long

    PTtoPX = Points * ScreenDPI(bVert) / POINTSPERINCH

End Function

Private Function GetRangeRect(ByVal rng As Range) As RECT

    Dim tPt1 As POINTAPI
    Dim tPt2 As POINTAPI
    Dim OWnd  As Window

    On Error Resume Next

    Set OWnd = rng.Parent.Parent.Windows(1)

    With rng
        GetRangeRect.Left = _
        PTtoPX(.Left * OWnd.Zoom / 100, 0) _
        + OWnd.PointsToScreenPixelsX(0)
        GetRangeRect.Top = _
        PTtoPX(.Top * OWnd.Zoom / 100, 1) _
        + OWnd.PointsToScreenPixelsY(0)
        GetRangeRect.Right = _
        PTtoPX(.Width * OWnd.Zoom / 100, 0) _
        + GetRangeRect.Left
        GetRangeRect.Bottom = _
        PTtoPX(.Height * OWnd.Zoom / 100, 1) _
        + GetRangeRect.Top
    End With

     With GetRangeRect
         tPt1.x = .Left
         tPt1.y = .Top
         tPt2.x = .Right
         tPt2.y = .Bottom
         ScreenToClient lWBHwnd, tPt1
         ScreenToClient lWBHwnd, tPt2
        .Left = tPt1.x + 2
        .Top = tPt1.y
        .Right = tPt2.x - 2
        .Bottom = tPt2.y
    End With

End Function

Private Sub SetDelay(TimeOut As Single)

    Dim t As Single

    t = Timer

    Do
        DoEvents
    Loop Until Timer - t >= TimeOut

End Sub


text:
Q: Confused by Python find_element_by_id Error This should be a seemingly simple problem-
Python v3.10.6, Selenium v4.7.2
I'm attempting the most basic of webcrawling activities...but find_element_by_id (or any other find element methods for that matter) are returning a "AttributeError: 'WebDriver' object has no attribute 'find_element_by_id'" error
Trying to (at first) just click the help botton at https://www.mouser.com/
Am getting that element ID as "aHelp":

The code:

I always get this Attribute Error...

A: Selenium's newer versions no longer support using driver.find_element_by_*.
try driver.find_element(By.ID, "the id you want")
for your example :
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
driver = webdriver.Chrome("chromedriver.exe")
driver.get("https://www.mouser.com/")
time.sleep(2)
driver.find_element(By.ID,"aHelp").click()

Also for the rest of instructions(for instance XPath , ...) see this link

A: You should do
from selenium.webdriver.common.by import By

driver.find_element(By.ID, 'aHelp').click()

See https://selenium-python.readthedocs.io/locating-elements.html for details.


text:
Q: Change BLE device name using cordova-ble-plugin I am using corodova-ble-plugin (https://github.com/don/cordova-plugin-ble-central) with my ionic 4 project and I wanted to know if its possible to change the bluetooth device name with this plugin. I searched the ble plugin documentation and did not find anything. But have anyone done such thing with an ionic app before without native android dev?
** Update **
I was able to find the characteristics that has to be passed using the write method to set the name of the device. But the passed value has to be a array buffer type and not string. So I used the string to array buffer npm package, its passing the write value when I checked in the android studio console but in the device it shows up with symbols instead and not the actual name. What would be going wrong here?

A: I'm not an expert in Cordova but it looks like this plugin doesn't allow what you're looking for. The good news is if you change the name of the device using native code, it should work.
BluetoothAdapter.getDefaultAdapter().setName("myDeviceName");
You can use that in your MainActivity.


text:
Q: NHibernate ternary relationship mapping I have the following tables
CREATE TABLE track
ID
name

CREATE TABLE people
ID
firstname

CREATE TABLE role
ID
name

CREATE TABLE track_people_role
track_id
people_id
role_id

and the following mapping files
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="App.Data.BusinessObjects" assembly="App.Data">
<class name="App.Data.BusinessObjects.Track, App.Data" table="track" lazy="true">
    <id name="Id" column="ID">
        <generator class="native" />
    </id>
    <property name="Name" column="name" />
</class>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="App.Data.BusinessObjects" assembly="App.Data">
<class name="App.Data.BusinessObjects.People, App.Data" table="people" lazy="true">
    <id name="Id" column="ID">
        <generator class="native" />
    </id>
    <property name="Firstname" column="firstname" />

</class>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="App.Data.BusinessObjects" assembly="App.Data">
<class name="App.Data.BusinessObjects.Role, App.Data" table="role" lazy="true">
    <id name="Id" column="ID">
        <generator class="native" />
    </id>
    <property name="Name" column="name" />
</class>

I am having a hard time trying to configure the mapping for track_people_role table. Could anybody help me out please?
I have the rows below in the intermediate table. The primary key is the combination of the three columns.

track_id  people_id  role_id
14292     1          1
14292     1          2

track_id  people_id  role_id
1200      1         1
1200      2         1

A: Omitting all the subtleties, here's a working example.
Class:
class Track
{
    ...
    public virtual IDictionary<People, Role> PeopleRoles { get; set; }
}

Mapping:
<class name="Track" ...>
  ...
  <map name="PeopleRoles" table="track_people_role">
    <key column="track_id"/>
    <map-key-many-to-many column="people_id" class="People"/>
    <many-to-many column="role_id" class="Role"/>
  </map>
</class>

As simple as it is, it contains many assumptions... don't hesitate to ask.


text:
Q: how to display one row from SQLite database to textview/edittext I'm very new to android and about to create an app which holds customers and then related to it some actions.
My current unsolvable problem: After inserting customer data into database I want to switch the view and display the last entry with all fields. The inserted values like title, name but also automatically created fields like id and date. I can see that the data are in the database when I pull the database file from the DDMS but I don't know how to retrieve and display them in the desired view.
I saw dozens of examples for passing it to a listview but I couldn't find any example which would suit my needs. Maybe it's because I don't know how to ask correctly for it. If so, please point me in the right direction.
My DatabaseHelper:
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;

public class DbHelper  {

public static final String TABLE_CUSTOMERS = "customers";
public static final String COLUMN_CUSTOMER_ID = "_id";
public static final String COLUMN_CUSTOMER_TITLE = "title";
public static final String COLUMN_CUSTOMER_FIRST_NAME = "first_name";
public static final String COLUMN_CUSTOMER_LAST_NAME = "last_name";
public static final String COLUMN_CUSTOMER_DATE = "date";

 private DatabaseHelper mDbHelper;
 private SQLiteDatabase mDb;

private static final String DATABASE_NAME = "myround.db";
private static final int DATABASE_VERSION = 1;

 private final Context mCtx;

 private static final String DATABASE_CREATE = "CREATE TABLE if not exists "
        + TABLE_CUSTOMERS + " (" + COLUMN_CUSTOMER_ID
        + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_CUSTOMER_TITLE + " VARCHAR, "
        + COLUMN_CUSTOMER_FIRST_NAME + " VARCHAR, " + COLUMN_CUSTOMER_LAST_NAME + " VARCHAR, " + COLUMN_CUSTOMER_DATE + " VARCHAR);";

private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS" + TABLE_CUSTOMERS);
        onCreate(db);
    }

}

public DbHelper(Context ctx) {
    this.mCtx = ctx;
}

public DbHelper open() throws SQLException {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close() {
    if (mDbHelper != null) {
        mDbHelper.close();
    }
}

public long createCustomer(String Title, String FirstName, String LastName,
        String Date) {

    ContentValues initialValues = new ContentValues();
    initialValues.put(COLUMN_CUSTOMER_TITLE, Title);
    initialValues.put(COLUMN_CUSTOMER_FIRST_NAME, FirstName);
    initialValues.put(COLUMN_CUSTOMER_LAST_NAME, LastName);
    initialValues.put(COLUMN_CUSTOMER_DATE, Date);

    long id = mDb.insert(TABLE_CUSTOMERS, null, initialValues);
    return id;

}

public Cursor displayLastCustomer() {

      Cursor mCursor = mDb.query(TABLE_CUSTOMERS, new String[] {COLUMN_CUSTOMER_ID,
        COLUMN_CUSTOMER_TITLE, COLUMN_CUSTOMER_FIRST_NAME, COLUMN_CUSTOMER_LAST_NAME, COLUMN_CUSTOMER_DATE},
        null, null, null, null, null);

      if (mCursor != null) {
       mCursor.moveToLast();
      }
      return mCursor;
     }

}

And my CustomerHelper:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import android.widget.Toast;

public class CustomerHelper extends Activity implements OnClickListener {

public static final String TAG = "CustomerHelper";
EditText txtTtitle, txtFirstName, txtLastName,
          editID, editTitle, editFirstName, editLastName, editDate;
Button btn_add_customer_to_db;
DbHelper dbHelper;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_new_customer);
    txtTtitle = (EditText) findViewById(R.id.txt_title);
    txtFirstName = (EditText) findViewById(R.id.txt_first_name);
    txtLastName = (EditText) findViewById(R.id.txt_last_name);
    editID = (EditText) findViewById(R.id.ntxt_customer_id);
    btn_add_customer_to_db = (Button) findViewById(R.id.add_customer_to_db);
    btn_add_customer_to_db.setOnClickListener(this);

    dbHelper = new DbHelper(this);
    dbHelper.open();

}

private String getDateTime() {
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    Date date = new Date();
    return dateFormat.format(date);
}

public void onClick(View view) {
    if (view == btn_add_customer_to_db) {
        String Title = txtTtitle.getText().toString();
        String FirstName = txtFirstName.getText().toString();
        String LastName = txtLastName.getText().toString();
        String Date = getDateTime();

        long id = dbHelper.createCustomer(Title, FirstName, LastName, Date);
        if (id < 0) {
            Toast.makeText(this, "Error - Unsuccessful", Toast.LENGTH_LONG)
                    .show();
        } else {
            Toast.makeText(this, "Success - Record added",
                    Toast.LENGTH_LONG).show();

        }

    }

}

}

I'm looking for a solution to implement this view with the last entry into my CustomerHelperClass so that I can also modify or delete this entry.
For Inserting new customer I have add_new_customer.xml and I want to switch view to update_customer.xml with the last entry displayed. Both of them have the text fields for title, name etc
update_customer.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:gravity="center"
    android:text="@string/update_customer_xml_title"
    android:textSize="14sp" />

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true" >

    <Button
        android:id="@+id/add_activity_to_customer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.3"
        android:text="@string/add_activity_to_customer_sm_btn"
        android:textSize="10sp" />

    <Button
        android:id="@+id/go_to_view_customer_management"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.3"
        android:text="@string/go_to_customer_mgmt"
        android:textSize="10sp" />

    <Button
        android:id="@+id/go_to_main_menu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.3"
        android:text="@string/go_to_main_menu"
        android:textSize="10sp" />
</LinearLayout>

<Button
    android:id="@+id/delete_customer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/linearLayout1"
    android:layout_alignLeft="@+id/linearLayout1"
    android:layout_marginBottom="5dp"
    android:text="@string/delete_customer" />

<Button
    android:id="@+id/save_customer_changes"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/delete_customer"
    android:layout_alignBottom="@+id/delete_customer"
    android:layout_alignRight="@+id/linearLayout1"
    android:text="@string/save_customer_changes" />

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/save_customer_changes"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="5sp" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/ntxt_customer_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="TextView" />

        <EditText
            android:id="@+id/ntxt_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/ntxt_customer_id"
            android:hint="@string/title"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearance"
            android:textColor="@android:color/black" />

        <EditText
            android:id="@+id/ntxt_first_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/ntxt_title"
            android:layout_marginTop="8dp"
            android:hint="@string/first_name"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearance"
            android:textColor="@android:color/black" />

        <EditText
            android:id="@+id/ntxt_last_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/ntxt_first_name"
            android:layout_marginTop="8dp"
            android:hint="@string/last_name"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearance"
            android:textColor="@android:color/black" />

        <EditText
            android:id="@+id/ntxt_customer_date"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/ntxt_last_name"
            android:layout_marginTop="8dp"
            android:hint="date"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearance"
            android:textColor="@android:color/black" />

    </RelativeLayout>
</ScrollView>

edit:
 } else {
            Toast.makeText(this, "Success - Record added",
                    Toast.LENGTH_LONG).show();

            setContentView(R.layout.update_customer);

        }

    }

    DbHelper dbHelperInstance = new DbHelper(this); // Assuming it's running
                                                    // in an Activity
    Cursor cursor = dbHelperInstance.displayLastCustomer();
    if (cursor != null) {
        EditText editTextFirstName = (EditText) findViewById(R.id.ntxt_first_name);
        editTextFirstName.setText(cursor.getString(cursor
                .getColumnIndex(DbHelper.COLUMN_CUSTOMER_FIRST_NAME)));
    }
}
}

A: Hopefully you can build upon this answer, if you need further guidance, feel free to comment.
Let's assume you want the EditText with id ntxt_first_name to be populated with customer name. You'd write this code after you call displayLastCustomer()
DatabaseHelper dbHelperInstance = new DbHelper(this); //Assuming it's running in an Activity
Cursor cursor = dbHelperInstance.displayLastCustomer();
if(cursor != null) {
    EditText editTextFirstName = (EditText) findViewById(R.id.ntxt_first_name);
    editTextFirstName.setText(cursor.getString(cursor.getColumnIndex(DbHelper.COLUMN_CUSTOMER_FIRST_NAME)));
}

The above snippet tries to find the View (EditText) with id ntxt_frist_name within the inflated View hierarchy that was supplied using the setContentView(int resourceId) method (hopefully you have supplied R.layout.update_customer as its parameter. Then it simply sets its mText field to the value it obtains from the entry cursor is currently pointing at (set to last entry in the query by your displayLastCustomer() method) for the column DbHelper.COLUMN_CUSTOMER_FIRST_NAME.
Like I already wrote, I hope you can get from this snippet how to populate other Views obtaining data from other columns in your Cursor object.
Cheers and good luck!
EDIT: In case you are not running this code inside an Activity object (or object of a class derived from it) , you need to obtain the Context of the Activity which has the update_customer.xml file inflated.


text:
Q: Android is there a count down timer widget? I want to have a count down timer in my app. It's not a problem updating a TextView every second, but I want a widget which let the user choose the time of the count down when pressing it before everything starts...
a TimePicker is close but not quite as it got the AM/PM addition.

A: If an maximum of 24h is enought for the countdown, than may be you should just set setIs24HourView(true)


text:
Q: Mongo aggregate search results based on unique subcollection property with count? I've been trying to wrap my head around how to do this for many hours now, I have a collection called 'Jobs' -- inside, they have a subcollection 'Site' which is Jobs.site. This Site subcollection has the property 'UNID'.
I'm trying to retreive documents from the database based on a text search, that works fine.
But I'm trying to retreive only UNIQUE documents based on that Job.Site.UNID and perhaps have a count added as an extra property. The result should look like:
Job: { site: { field1: 'EXAMPLE', UNID: 'SITEID', count: 5  } }
Which would mean there are 5 jobs inside the job collection that have that site.UNID.
This is what I have so far:
[
// GETTING DOCS BASED ON TEXT SEARCH RESULTS
    {
      $match: {
        // clientId: req.user.client_id,
        $text: { $search: body.searchTerms }
      }
    },
// SORTING THEM BASED ON TEXTSCORE
    { $sort: { score: { $meta: 'textScore' } } },
// THE PROBLEMATIC GROUPING PART
    { $group: { site: { UPRN: '$UPRN', myCount: { $sum: 1 } } } },
// I ONYL WANT TO GET 20 DOCS AT A TIME
    { $limit: 20 },
// THE DATA THAT I WANT IN MY DOCUMENTS, MAYBE COUNT WOULD COME HERE?
    {
      $project: {
        site: true,
        score: { $meta: 'textScore' }
      }
    },
// GETTING RID OF POOR MATCHES BASED ON A SCORE CALCULATED IN ANOTHER
// FUNCTION BASED ON THE NUMBER OF WORDS IN THE TEXT SEARCH
    {
      $match: {
        score: { $gt: matchScore }
      }
    }
  ]

Here it hits me with The field 'site' must be an accumulator object
So I can't figure out the syntax to properly work on that subcollection property.
EDIT: V2 thanks to @Anthony work perfectly and have tested it thoroughly except it doesn't seem to count the total number of jobs, it's always 1 or whatever I set in $sum:  but there's 200+ results, still working on it.
 { $match: { $text: { $search: body.searchTerms } } },
    { $sort: { $score: { $meta: 'textScore' } } },
    // { $match: { score: { $gt: 0.1 } } },
    {
      $group: {
        _id: '$UNID',
        counter: { $sum: 1 },
        score: { $first: { $meta: 'textScore' } },
        title: { $first: '$title' },
        postcode: { $first: '$postcode' },
        addressLine1: { $first: '$addressLine1' },
        city: { $first: '$city' },
        projectName: { $first: '$projectName' },
        jobsCount: { $sum: '$counter' }
      }
    },
    { $limit: 20 },
    {
      $project: {
        UNID: '$_id',
        title: '$title',
        postcode: '$postcode',
        addressLine1: '$addressLine1',
        projectName: '$projectName',
        city: '$city',
        score: 1,
        jobsCount: true
      }
    }

SAMPLE DATA:

{
  "_id": "randomString0",
  "title": "Quality",
  "site": {
    "_id": "rKFRbvH8CEbJYdzDs",
    "title": "Title 1",
    "addressLine1": "address1",
    "UNID": "001",
    "city": "cityName",
    "createdAt": null
  }
},
{
  "_id": "randomString1",
  "title": "Some2123",
  "site": {
    "_id": "rKFRbvH8CEbJYdzDs",
    "title": "Title 1",
    "addressLine1": "address1",
    "UNID": "001",
    "city": "cityName",
    "createdAt": null
  }
},
{
  "_id": "randomString2",
  "title": "Random title",
  "site": {
    "_id": "rKFRbvH8CEbJYdzDs",
    "title": "Title 1",
    "addressLine1": "address1",
    "UNID": "001",
    "city": "cityName",
    "createdAt": null
  }
},
{
  "_id": "randomString3",
  "title": "Another unique job",
  "site": {
    "_id": "rKFRbvH8CEbJYdzDs",
    "title": "Title 1",
    "addressLine1": "address1",
    "UNID": "001",
    "city": "cityName",
    "createdAt": null
  }
},
{
  "_id": "randomString4",
  "title": "Other thing",
  "site": {
    "_id": "rKFRbvH8CEbJYdzDs",
    "title": "Title 1",
    "addressLine1": "address1",
    "UNID": "001",
    "city": "cityName",
    "createdAt": null
  }
},
{
  "_id": "randomString5",
  "title": "Something else",
  "site": {
    "_id": "rKFRbvH8CEbJYdzDs",
    "title": "Title 1",
    "addressLine1": "address1",
    "UNID": "001",
    "city": "cityName",
    "createdAt": null
  }
}

As you can see, the site data will always be unique under all those 5 documents, but the counter should count how many docs have the same unique

A: In $group stage the _id(to which you want to group by) expression is the required expression. And there are only few accumulators you can use with the $group aggregation stage.
So your aggregation must be something like this
[
  { "$match": { "$text": { "$search": body.searchTerms }}},
  { "$sort": { "score": { "$meta": "textScore" } } },
  { "$match": { "score": { "$gt": matchScore }}},
  { "$group": {
    "_id": "$UPRN",
    "myCount": { "$sum": 1 },
    "score": { "$first": "$score" }
  }},
  { "$limit": 20 },
  { "$project": {
    "site": "$_id",
    "score": 1,
    "myCount": 1
  }}
]


text:
Q: Export Android lib as JAR, and keeping RES folders I have a very short (but yet seems hard") question:
Is there any possible way to export an Android Library project in eclipse, and preserving all resources ?
Thank you all

A: For Android resources, JAR files won't work and full-fledged library projects are the way to go.
See https://developer.android.com/tools/projects/projects-eclipse.html.
[Edit]
Note that you can bundle your plain Java code in a JAR, then reference this JAR in an Android library project that contains resources.
This is useful when you don't want to make the Java code easily readable by anyone, and allows for code obfuscation.


text:
Q: Vertical alignment on mobile devices I'm having trouble vertically aligning an SVG on mobile devices. I've tested on an iPhone 5s, 6s and iPad Air 2. It seems to work perfectly on Chrome Responsive Mode but not on an actual mobile browser. I can't confirm if it's working on Android as I don't have one.
http://accoutrements.studio/
Here's how it's looking on my iPhone – https://i.imgur.com/GnRSEmn.png
It should be vertically and horizontally aligned in the centre of the page. It's displaying slightly off centre (vertically) on iOS Safari. Is there anything I can change in the code or is this a Safari bug?

A: The svg is being positioned by margin-top: 50vh. Try this instead:
.accoutrements {
 top: 50%;
 transform: translateY(-50%);
 position: absolute;
 width: 100%;
 cursor: pointer;
}


text:
Q: SLRequest with C# in Xamarin.iOS project returned code:215 Bad Authenticated I tried a sample of xamarin.iOS on http://docs.xamarin.com/guides/ios/platform_features/introduction_to_the_social_framework/
but
twitterRequestButton.TouchUpInside += delegate {

            if (SLComposeViewController.IsAvailable (SLServiceKind.Twitter)) {

                var parameters = new NSDictionary ();
                var request = SLRequest.Create (SLServiceKind.Twitter,
                                                SLRequestMethod.Get,
                    new NSUrl ("http://api.twitter.com/1.1/statuses/public_timeline.json"),
                                                parameters);

                request.PerformRequest ((data, response, error) => {

                    if (response.StatusCode == 200) {
                        InvokeOnMainThread (() => {
                            resultsTextView.Text = data.ToString (); });

                    } else {
                        InvokeOnMainThread (() => {
                            resultsTextView.Text = "Error: " + response.StatusCode.ToString (); });
                    }
                });
            }
        };

This SLRequest returned 215 code; Bad Authenticated.
I don't know why.
All I want to do is to get specific user's time line so if you have an idea about this, please help me.

A: well -- for one thing statuses/public_timeline does not exist as an endpoint for version 1.1 of their API.  Maybe you like https://dev.twitter.com/rest/reference/get/statuses/user_timeline or https://dev.twitter.com/rest/reference/get/statuses/home_timeline?


text:
Q: Converting numbers in binary form and saving them I need to convert some decimal numbers in binary form and store the strings made of 1s and 0s as rows in a matrix, in C++.
Regarding the conversion, I found this simple solution:
std::string binary = std::bitset<8>(128).to_string();

Now, I could simple scan the string and convert each character into a 1 or a 0, filling a matrix's row.
Is there a way, a C++ function (or a combo of functions) that allows me to avoid the cost of scanning every bits string?
Thanks for help.

A: There is no need to convert to a std::string first and then convert that to 1/0, you can simply access the bits inside the std::bitset using []:
#include <vector>
#include <bitset>
#include <iostream>

using BitRow = std::bitset<8>;
using BitMatrix = std::vector<BitRow>;

void print(const BitMatrix& bm)
{
    for(const BitRow& row : bm)
    {
        for (std::size_t i=0; i < row.size(); ++i)
        {
            std::cout << row[i] << " ";
        }
        std::cout << std::endl;
    }
}

int main()
{
    BitMatrix bitMatrix;
    bitMatrix.push_back(128);
    bitMatrix.push_back(64);

    print(bitMatrix);
}

live example


text:
Q: Can/Should C++ #pragma Preprocessors Reside In Functions In short, I am wanting to make a function that embeds the visual styles manifest and links to ComCtl32.lib, version 6 if available. Here is basically what I am hoping to do:
void InitVivify() {
    // Embed visual style XML manifest
    #pragma comment(linker,                           \
        "\"/manifestdependency:type='Win32'"          \
        "   name='Microsoft.Windows.Common-Controls'" \
        "   version='6.0.0.0'"                        \
        "   processorArchitecture='*'"                \
        "   publicKeyToken='6595b64144ccf1df'"        \
        "   language='*'\""                           \
    )

    // Link common controls library
    #pragma comment(lib, "ComCtl32.lib")

    // Initialize controls used
    INITCOMMONCONTROLSEX InitCtrlEx;
    InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
    InitCtrlEx.dwICC = ICC_LISTVIEW_CLASSES | ICC_TAB_CLASSES | ICC_USEREX_CLASSES;
    InitCommonControlsEx(&InitCtrlEx);
}

I realize this probably isn't good practice, but is it valid?

A: Pragma directives are pre-processor directives.
They cause the implementation to behave in a implementation defined way.
So it is valid but not encouraged.
C++11 Standard:
16.6 Pragma directive [cpp.pragma]

1 A preprocessing directive of the form
# pragma pp-tokensopt new-line

causes the implementation to behave in an implementation-defined manner. The behavior might cause translation to fail or cause the translator or the resulting program to behave in a non-conforming manner. Any pragma that is not recognized by the implementation is ignored.


text:
Q: Java: Exit Confirmation on game The code works fine until it reaches the no option, once clicked the no option stutters and then closes. on the other hand, the yes option works fine and closes instantly. "loader.cleanUP();" is for removing the vbos and vaos, therefore, it is needed. would appreciate some help.
while(!Display.isCloseRequested()) {
        renderer.render(model);
        renderer.prepare();
        // add logic!
        DisplayManager.updateDisplay();
    }
        int dialogButton = JOptionPane.YES_NO_OPTION;
        int dialogResult = JOptionPane.showConfirmDialog(null, "Would you like to exit?", "Exit Confirmation", dialogButton);

        if(dialogResult == 0) {
          System.out.println("Yes option");
          loader.cleanUP();
          System.exit(0);
        }

A: You have a while loop at the very start, checking for close requests and rendering the model. Once a close is requested, you break out of this loop, regardless of whether the user clicked yes or no. You need to wrap all of the code shown in another loop, which simply runs forever.

A: *

*Change your while to a do-while.

*Don't exit with System.exit(0);...The API you're using probably has an exit method of it's own, that unloads the resources before exiting. This is necessary because, usually, resources will be loaded to GPU and will not be unloaded by Java's native methods (only by the API's specialized methods).

*If your API has such, use Display.setCloseRequested(true) (or similar), instead of this int dialogResult gimmick. This is related to how you will exit the game while avoiding System.exit(0);, as instructed in the previous item.

*If your API doesn't provide it's own, you need a separate loop to run the game-world within. Preferably implementing Delta-Time to maintain the animations without time-drift bugs.


text:
Q: How to add external tools menu on different version of Visual Studio programmatically I need to write a small code, which need to add some items in external tools menu, but in programmatical way.
and it need to work on all different visual studios, 2008, 2010, 2012, 2013, and all express versions of these versions.
I know it's about add registry keys, but I heard several different locations of registry:
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\External Tools
HKEY_CURRENT_USER\Software\Microsoft\WDExpress\12.0\External Tools
HKEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\External Tools
and so on.
how to get the correct location from the user? because the names after the Microsoft are different.
or is there any other ways to add those tools programmatically?


text:
Q: formula for repeated finite differences I am looking for a proof of a well-known fact, whose proof must be very easy, though I've been struggling to find it. Let $\Delta$ be the map from real-valued functions of a real variable, given by $(\Delta g)(x) = g(x+1/2)-g(x-1/2)$. Let $u(x)=0$ if $x\le 0$ and $u(x)=x$ otherwise. We set $0^0 =0$. Then, for smooth functions $h$, and $n>0$,
$$(\Delta^n h)(0) = \frac{1}{(n-1)!}\int_{-\infty}^\infty h^{(n)}(x).
(\Delta^n(u^{n-1}))(x)\,dx.$$
Here $h^{(n)}$ denotes the $n$th derivative of $h$.
I tried proving this by induction and also by using the exact integral remainder in Taylor's Theorem, but couldn't get either of these two obvious approaches to work. I seem to be missing some trick in manipulation.

A: Taylor
$$g(y)=\sum_{k=0}^{n-1} g^{(k)}(x)\frac{(y-x)^k}{k!}+\int_x^y \frac{(y-z)^{n-1}}{(n-1)!} g^{(n)}(z)dz.$$
By induction on can prove
$$\Delta^n g(x)=\sum_{k=0}^n \binom{n}{k}(-1)^k g(x+n/2-k).$$
Note that $\Delta^n p=0$ for polynomials $p$ of degree smaller than $n$.
Now
\begin{eqnarray}
\Delta^n(u^{n-1})(x)&=&\sum_{k<n/2+x} \binom{n}{k}(-1)^k  (x+n/2-k)^{n-1}\\
&=&-\sum_{k\geq n/2+x} \binom{n}{k}(-1)^k  (x+n/2-k)^{n-1}\\
&=&\sum_{j<n/2-x} \binom{n}{j}(-1)^j  (-x+n/2-j)^{n-1}\\
&=&\Delta^n(u^{n-1})(-x)
\end{eqnarray}
and
\begin{eqnarray}
\Delta^nh(0)&=&\sum_{k=0}^n \binom{n}{k}(-1)^k h(n/2-k)\\
&=&\sum_{k=0}^n \binom{n}{k}(-1)^k \left(\sum_{l=0}^{n-1} h^{(l)}(0)\frac{(n/2-k)^l}{l!}+\int_0^{n/2-k} \frac{(n/2-k-z)^{n-1}}{(n-1)!} h^{(n)}(z)dz\right)\\
&=&\sum_{k=0}^n \binom{n}{k}(-1)^k \int_0^{n/2-k} \frac{(n/2-k-z)^{n-1}}{(n-1)!} h^{(n)}(z)dz\\
&=&\frac{1}{(n-1)!}\int_{0}^{n/2} h^{(n)}(z) \sum_{k<n/2-z} \binom{n}{k}(-1)^k  (n/2-k-z)^{n-1}dz\\
&&+\frac{1}{(n-1)!}\int_{-n/2}^{0} h^{(n)}(z) \sum_{k>n/2-z} \binom{n}{k}(-1)^k  (n/2-k-z)^{n-1}dz\\
&=&\int_{-\infty}^{\infty} h^{(n)}(z) \Delta^n(u^{n-1})(z)dz.
\end{eqnarray}

A: In fact, the proof by induction works perfectly well, starting with the obvious case $n=1$. To go from $n-1$ to $n$, note:
1. If $j\ge 1$, $\Delta^i(u^j)$ is a $C^{j-1}$-function.
2. If $i>j\ge1$, then $\Delta^i(u^j)$ has compact support. (By induction on $i$, $\Delta^i(u^j)$ is zero on $[-\infty,0]$ and a polynomial of degree $j-i$ near $\infty$.)
3. For any integrable function $g$, $\int_{-\infty}^\infty (\Delta g)(x)\,dx=0$.
4. $(\Delta(\alpha.\beta))(x)=\alpha(x+1/2)(\Delta\beta)(x) +(\Delta\alpha)(x)\beta(x-1/2).$
Taking $\alpha(x)=h^{(n-1)}(x)$ and $\beta(x)=\Delta^{n-1}u^{n-2}(x+1/2)$, we find
$$(\Delta^n h)(0) = (\Delta^{n-1}(\Delta h))(0)=
\frac1{(n-2)!}\int\Delta h^{(n-1)}(x).\Delta^{n-1}u^{n-2}(x)\,dx\text{ induction hypothesis}\\
=\frac{-1}{(n-2)!}\int h^{(n-1)}(x+1/2).\Delta^n u^{n-2}(x+1/2)\,dx \text{ by 3 and 4 above}\\
=\frac{-1}{(n-2)!}\int h^{(n-1)}(x).\Delta^n u^{n-2}(x)\,dx\\
= \frac{1}{(n-1)!}\int h^{(n)}(x).\Delta^n u^{n-1}(x)\,dx\text{ by integration by parts}.$$