text:
Q: How to run Django channels with StreamingHttpResponse in ASGI I have a simple app that streams images using open cv and the server set in wsgi. But whenever I introduce Django channels to the picture and change from WSGI to ASGI the streaming stops. How can I   stream images from cv2 and in the same time use Django  channels? Thanks you in advance
My code for streaming:
def camera_feed(request):
    stream = CameraStream()
    frames = stream.get_frames()
    return StreamingHttpResponse(frames, content_type='multipart/x-mixed-replace; boundary=frame')

settings.py:
ASGI_APPLICATION = 'photon.asgi.application'

asgi.py
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns))
})

A: First, we don't need StramingHTTPResponse for sending image data at all ...
For this, first, ensure you have a Django version with 3.x and Python 3.7+.
Then, install django-channels third party package.
Configure the ASGI application as follows:
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import .routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
        URLRouter(
            app.routing.websocket_urlpatterns
        )
    )
})

Then You need to set ASGI_APPLICATION constant in the settings.py file:
ASGI_APPLICATION = "myproject.asgi.application"

After that, just create an async WebSocket consumer in the consumers.py file present in the application :
import json
from channels.generic.websocket import AsyncWebsocketConsumer

class PairingChat(AsyncWebsocketConsumer):

    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self):

        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Asyncwebsocket consumer can send any type of data ...

    async def receive(self, text_data):
        data_json = json.loads(your_data)
        message = data_json['message']

        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': '# send your data from here ...',
                'message': message,
                'user': self.scope['session']['name']
            }
        )

    async def chat_message(self, event):
        message = event['message']

        await self.send(data=json.dumps({
            'user': event['user'],
            'message': message,
        }))

Create a route for asyncwebsocket consumers as well ...
from django.urls import re_path
from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat1/(?P<room_name>\w+)/$', consumers.PairingChat.as_asgi()),
]

Then, just create a WebSocket client in javascript ... and you are good to go ...
Link for JS Websocket Create : javascript-websocket


text:
Q: VBA date of last macro executed in a xlsm File i want to write in 2 cells the following informations :
Sheets("Dates").Range("A1").Value = Date '(today 's date)
Sheets("Dates").Range("A2").Value= ' ??? Date of macro executed

Is there a code that can tell us when the macro is executed ? Not the date of last modified ,  so i can compare the two dates ?
Thanks

A: I do something similiar on a hidden worksheet with this code on run:
Dim LastRunDate As Date
Dim LastRunTime As Date
Dim CurrentDate As Date
Dim CurrentTime As Date

CurrentDate = Format(Now, "dd/mm/yyyy")
CurrentTime = Format(Now, "hh:mm:ss")

LastRunDate = WB1.Names("LastRunDate").RefersToRange
LastRunTime = WB1.Names("LastRunTime").RefersToRange
LastRunTime = LastRunTime + TimeSerial(0, 10, 0)

If CurrentDate <= LastRunDate Then
    If CurrentTime <= LastRunTime Then
        End
    End If
End If

Range(WB1.Names("LastRunDate")) = CurrentDate
Range(WB1.Names("LastRunTime")) = CurrentTime

So this just works out if the code has been run in the last 10mins. I just force a save a little after that code

A: By last modified I'm presuming that you want the date of when the workbook was last saved? If so:
Private Sub Workbook_Open()
Sheets("Dates").Range("A1").Value = NOW()
End Sub

Sub YourMacro()
'Whatever code the macro runs
Sheets("Dates").Range("A2").Value = NOW()
End Sub

A: Excel doesn't store data like this by default, but what you can do is create a very hidden sheet to store data between instances.  In your case, make the hidden sheet with a row for each macro, then add code to the routine that will store the current date into a cell in that row, which you can later recall for your purposes

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which type should I specify? I'm using react-table library and I making custom cell (to render images instead of links or add buttons). Also I using TypeScript and I had some difficulty with types. I don't know which types i should specify instead of 'any' type in code below.
const tableHooks = (hooks: any) => {
    hooks.visibleColumns.push((columns: any) => [
        ...columns,
        {
            id: 'image',
            Header: 'Image',
            Cell: (cell: any) => (

            )
        },
        {
            id: 'action',
            Header: 'Actions',
            Cell: (cell: any) => (
                <>
                    <button className={ styles.table__button } onClick={ () => handleEditEquipment(cell.row.original) }>
                        Edit
                    </button>
                    <button className={ styles.table__button } onClick={ () => handleDeleteEquipment(cell.row.values.eid) }>
                        Delete
                    </button>
                </>
            ),
        }
    ]);
};


text:
Q: How can I combine 2 uses of connect()? I am calling connect() twice on my component and a code reviewer asked me to make it to one.
I have this which works as expected:
export default compose(
  connect(store => ({
    softlayerAccountId: store.global.softlayerAccountId,
  })),
  connect(
    ({ shipments }) => ({
      pagination: shipments.pagination,
      isFiltersModalOpened: shipments.filtersModalOpened,
      filters: shipments.filters,
    }),
    dispatch => ({...}),
  ),
)(GetShipments);

And they want me to do something like this:
export default compose(
  connect(
    store => ({
      softlayerAccountId: store.global.softlayerAccountId,
    }),
    ({ shipments }) => ({
      pagination: shipments.pagination,
      isFiltersModalOpened: shipments.filtersModalOpened,
      filters: shipments.filters,
    }),
    dispatch => ({...}),
  ),
)(GetShipments);

But I get this error:

Uncaught TypeError: Cannot read property 'pagination' of undefined

Or this:
export default compose(
  connect(
    ({ shipments }, store) => ({
      softlayerAccountId: store.global.softlayerAccountId,
      pagination: shipments.pagination,
      isFiltersModalOpened: shipments.filtersModalOpened,
      filters: shipments.filters,
    }),
    dispatch => ({...}),
  ),
)(GetShipments);

But I get this:

Uncaught TypeError: Cannot read property 'softlayerAccountId' of undefined

Any ideas?

A: you are making it wrong. connect() takes two arguments: mapStateToProps callback and mapDispatchToProps. In you second variant your are trying to pass 3 arguments where 2nd actually also refers to store(so it's like you put mapStateToProps onto mapDispatchToProps place).
You need it to have 2 arguments:
export default compose(
  connect(
    ({global: {softlayerAccountId}, shipments }) => ({
        softlayerAccountId: store.global.softlayerAccountId,
        pagination: shipments.pagination,
        isFiltersModalOpened: shipments.filtersModalOpened,
        filters: shipments.filters,
    }),
    dispatch => ({...}),
)(GetShipments);

Why 3rd variant does not work? The same reason: you are trying to put arguments where there are cannot work.
({ shipments }, store) => ({

Here you declare function that takes two arguments. First is destructuring and second is just passed in. But connect will pass just single argument of store. It will not pass store for several times just because you expect that.


text:
Q: Setting scroll step/jump/snap distance with html/css I swear I've done this before, but maybe it was in the pre-standards bad old days. Now I can't even figure out the keywords to find possible workarounds.
So I have a table that is in a wrapper so that the x-overflow is inside the wrapper instead of expanding the window.  Let's say each column is hard-set with css to be 150px.  I want it so that when horizontally scrolling the wrapper, the scrollbar "jumps" 150 pixels so that the right edge of the next column is aligned with the left margin of the wrapper. In other words, you scroll by column, not by pixel, so that the left-side of the viewport is never a partial column.
By extension, it would be ideal if this could be variable-width jumping so that the columns aren't forced to be a unified width, and I'd like to have this and all of the above for vertical scrolling as well.
I thought this was a standard but overlooked option for css or at least a deprecated html style attribute, but like I said, now I can't even find the idea/concept when I Google they keywords that come to mind.
Any help (even somewhat hackish ones that get me started) is appreciated.

A: This ain't exactly CSS, but you can use the DOM attribute scrollLeft (and also scrollTop if you need that direction).
For more information and a bit of an example, you can refer to this page.


text:
Q: HTML/CSS Blink Animation Website I'm trying to create a flashing effect for an image and I've come across that you can use "Blink" Animations. But I'm clueless on how to set a time limit e.g. Flash on and Off in 4 seconds.
I have used Keyframe (blink) with opacity on different percentage.
Is there any chance you guys could help me it would be much appreciated.
Here is my code that I have tried.

A: First thing to note here is: The opacity property can take a value from 0.0 - 1.0. The lower value, the more transparent
IE8 and earlier use filter:alpha(opacity=x). The x can take a value from 0 - 100. A lower value makes the element more transparent.
I have made the changes to your code and you can find the snippet below.
Hope it works!

javascript jquery html css
shareeditflag


text:
Q: Combined div elements combined with jQuery I got an html page like this:

  first

    second

Now, I want to use the jQuery click method but should only work when clicking first, not second. But if doing something like
$("#foo").click(function() { do things });

If I click inside the second, its like clicking also on the first and the above function will run. Can I avoid this? So, clicking in second, won't run the above function of the first?

A: Yes you can!
$("#foo div.second").click(function(event) {
    event.stopPropagation();
});

That will stop propagation to elements "above" in the tree.

A: $('#foo').click(function(e) {
    // Do your snazzy stuff.
});

$('#foo div').click(function(e) {
    e.stopPropagation();
});

= OR =
$('#foo').children().click(function(e) {
   e.stopPropagation();
});


text:
Q: How do I boot a virtual machine image from my network? I have many machines which require the same configurations. My goal is to boot them all from the network and load a virtual machine. It would be wonderful to have one image for all of our customer service machines. That way, I could load the virtual image, perform updates, and know the next time they boot up they will have all the changes. Ideally, the machines would store the image locally and only download a new image if there has been a change.
With all the information out there on "desktop virtualization", "PXE booting", and "virtual machines", I feel lost. I have been reading for hours and feel like I have only just scratched the surface.
I would like to do this using open source or free software. Any suggestions?

A: You are combining two things: (1) diskless booting which is common in HiPC clusters, where tools like compilers, libraries, etc, are stored on a clustered file system like Lustre or NFS; (2) virtual disk images (vmdk or vdi, or whatever else).
In case (1), you need a tftp server and a dhcp server, along with a modified initrd image for customized drivers, scripts, etc.
http://www.pixelchaos.net/2009/02/15/diskless-booting-with-pxe-and-nfs/
In case (2), given all machines are same, including configurations, you can nfs mount the virtual disk image. Write a script that checks for any changes like whether the existing image is same as nfs mounted; if they are not same, copy this image to boot partition and reboot it. You need to add this script in initrd. You can play with that.
http://www-conf.slac.stanford.edu/afsbestpractices/Slides/afsboot.pdf
The paper above gives you some clues. You better focus on how the whole boot process works, etc.
If you are using ESXi, there is a better way to achieve what you want: export nfs to esxi hosts. Keep the vmdk and -flat.vmdk files on the nfs server, and change vmdk location in .vmx file. During the next boot, it picks up your new image.

A: First let define some terms you are messed up.
PXE Booting:
It's an utility that replace the BIOS and it's capable of networking. Such as a diskless computer that download a kernel image from a server and execute it. After the kernel mount a distant partition as the root filesystem.
Virtual machine:
A virtual machine is a machine run by software. If I work on a particular OS then I can run the a VM to boot another OS without rebooting. There is some OSes that are dedicated to virtualisation. The virtual machine is not an answer for your problem.
Ok now I'll explain what I suggest, I did not work with it and I think it's not free software, but you should try to find a replacement. Northon Ghost is a PXE that boot up before the principal OS to check if the disk image is the same of what is on the server. If I come to a computer like that and clear out the OS, and reboot...the OS will be recovered by the server, but not the data.

A: I don't think you can do this with Free software and avoid hours and hours of reading. In fact I don't think you can do it with the "shiny pay for" software easily either. It's difficult & time consuming to understand all the ins and outs because its difficult & time consuming to configure all the ins and outs.
You're looking for something like netboot.me I think. Making things like this work on a couple of machines in the lab isn't difficult. You'll find making it work all across a complex routed LAN somewhat more complex - we use Apple's variation of this to run an installer to install our standard OSX desktop image on to mac workstations.
Desktop Virtualisation, by the way, is something totally different from what you actually describe yourself as wanting to do. It might well be a valid method of solving the problem you are looking at, but I'd try not to consider it at the same time as you consider this way of going about things - you'll only make the problem more difficult to understand than it needs to be.

A: I had the same problem some time ago and I used pxe successfully.
What You are looking for is gPXE (free). It is a bit of a hassle to set up, but You boot from an ftp server or iSCSI for example. If you boot from local lan, You can also use ata over ethernet (AOE). PXE can be started from any bootable drive about the size of a floppy or from boot rom if applied to the NICs.
You would start from the image or load the image into ramdisk via tftp or ISCSI or whatever and run the image from there. Or You give each VM it's own target and leave it that way.

A: Microsoft has a product for doing exactly this, it's called Microsoft Enterprise Desktop Virtualization (aka MED-V):
http://www.microsoft.com/windows/enterprise/products/mdop/med-v.aspx


text:
Q: Check if textbox contains text, if it does then send I have this email form, with "Sender, "Subject" and "Message".
But i haven't linked it to make sure they have written something, so if someone press the "Send" button without typing anyting, i get a blank email. So i want it to abort the email sending if the textbox is empty, and send it if it contains any text.
code for the send button:
<input type="submit" name="submit" value="Submit" class="submit-button" />

ID for the textbox is: textbox_text

A: You can use jquery to validate the form like this-

<form action="" method="post">
  Sender
  <input type="text">

Subject
  <input type="text">

Message
  <input type="text" id="txtMessage">

  <input type="submit" value="Send" name="btnSend">
</form>

A: I dont know this is your exact answer but it will helps you to validate:
$('#checkSubmit').click(function(){
     var chec=$("#textContent").val();
    if(chec=="")
        alert("Please add your content");
    else
        alert("successfully submitted");
});

check out this fiddle:
http://jsfiddle.net/0t3oovoa/

A: Java Script function

HTML
<form name="frm">
  <input type="submit" name="submit" onclick="return IsEmpty();" value="Submit"     class="submit-button" />
</form>

EDIT Check textbox2 in if condition
if(document.forms['frm'].textbox1.value == "" && document.forms['frm'].textbox2.value == "")

A: You can achieve it two ways:
1. Client Side( Which i recommend) use the form validation to validate the form data if it is empty tell them to fill it. You chose the submit button to trigger validation that is not recommended instead validation is triggered on form submission or on change of input elements(for real-time validation). Anyways below is an example for validation using the click event on submit button.

 var validateTextBox = function(textBox) {
     var val = textBox.value;
     if(val=="") {   // Check for empty textbox
         return false;
     }
     return true;
 }
 documnet.querySelector('#SubmitButton').onclick(function () {
  var textbox = document.querySelector("#SubjectORMessage").value;
  if(validateTextBox(textbox)){
    // Do something to let page know that form is valid
  } else {
    // Let the user know that he has done something wrong
    alert("Please fill the content");
  }
})

2. Server Side if unfortunately empty data is send to the server, then use server side validation (Server side validation requires a little more thing to do at more than one place, i.e., html, php/python/perl)

A: You need to check that on server side (with php) and you can also check it on client side(Javascript).
Client side test is good if you want the user to get fast response, but you still need to check it on server side because javascript on your website can ALWAYS be changed by user.
You could also just add "required" on your input elements.
for server side check with php:
<?php
//Check if variables exist
if(isset($_POST['sender']) && isset($_POST['subject']) && isset($_POST['message'])){
    //Check if sender value is empty
    if(empty($_POST['sender'])){
      //If empty, go back to form.Display error with $_GET['error'] in your form page
      header('location: backToFormPage.php?error=send');
    }
    //...
}
//Variables doesn't exist
else{
//Redirect to page or other action
}

?>


text:
Q: How to highlight the current line of a Text widget? I'm working on a simple GUI code editor in Python, and I want to have the line of text on which the cursor sits to be highlighted at all times.
Right now, my TextEditor class looks like:
class TextEditor:

   def __init__(self, container):
      self.scrollbar = Scrollbar(container)
      self.scrollbar.pack(side=RIGHT, fill=Y)

      self.textbox = Text(container, height=40, undo=True, width=80,
                          font=tkFont.Font(family="Consolas", size=12))
      self.textbox.pack(side=LEFT)

      self.textbox.config(yscrollcommand=self.scrollbar.set)
      self.scrollbar.config(command=self.textbox.yview)

How can I do this?

A: There is nothing built in to tkinter that directly supports that. However, something that is good enough for most purposes would be to write a function that polls for the cursor position and updates the highlighting at regular intervals.
For example:
import Tkinter as tk

class MyApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.text = tk.Text(self)
        self.text.pack(side="top", fill="both", expand=True)
        self.text.tag_configure("current_line", background="#e9e9e9")
        self._highlight_current_line()

    def _highlight_current_line(self, interval=100):
        '''Updates the 'current line' highlighting every "interval" milliseconds'''
        self.text.tag_remove("current_line", 1.0, "end")
        self.text.tag_add("current_line", "insert linestart", "insert lineend+1c")
        self.after(interval, self._highlight_current_line)

app = MyApp()
app.mainloop()

Obviously, the longer the interval the more "lag" that will be introduced, and the shorter the interval the more CPU is used, but there's a pretty large sweet spot between the extremes where there's almost no perceptible lag, and an imperceptible bump in CPU usage.
There's another way to do it that doesn't involve polling and is absolutely foolproof. You can move the highlight to precisely when the insertion cursor actually moves, but it involves writing some embedded Tcl code to create a proxy of the actual tk widget that is hidden in the implementation of the Tkinter Text object.
Finally, a third way is to set up custom bindings for all of the possible events that modify the cursor location. While possible, it's difficult to get 100% right since you have to account for all events that modify the cursor position, as well as handle places in your code that that might move the cursor without using an event. Still, using bindings is a perfectly good solution, it just requires a bit more work.

A: There's absolutely no need to poll like Bryan Oakley says in his answer, nor do you need to embed Tcl code in your Python code. My solution is to just bind to the events which may end up moving the cursor, namely <Key> and <Button-1>.
import tkinter as tk

class CurrentHighlightedLineText(tk.Text):

    """Text widget with current line highlighted"""

    def __init__(self, root, *args, **kwargs):
        tk.Text.__init__(self, root, *args, **kwargs)

        self.tag_configure('currentLine', background='#e9e9e9')
        self.bind('<Key>', lambda _: self.highlightCurrentLine())
        self.bind('<Button-1>', lambda _: self.highlightCurrentLine())
        self.highlightCurrentLine(delay=0)

    def highlightCurrentLine(self, delay=10):

        def delayedHighlightCurrentLine():
            self.tag_remove('currentLine', 1.0, "end")
            self.tag_add('currentLine', 'insert linestart', 'insert lineend+1c')
        # This bound function is called before the cursor actually moves.
        # So delay checking the cursor position and moving the highlight 10 ms.

        self.after(delay, delayedHighlightCurrentLine)

if __name__ == "__main__":
    root = tk.Tk()

    text = CurrentHighlightedLineText(root)
    text.grid(row=0, column=0, sticky='nesw')

    root.grid_rowconfigure(0, weight=1)
    root.grid_columnconfigure(0, weight=1)

    root.mainloop()

A: Just to expand on Bryan Oakley's answer: Simply highlighting the current line becomes a pain when you want to select some text that includes part, but not all, of the current line, because the part of the current line that is selected is colored using the current-line color, not the selected-text color, so it's harder to see at a glance what part of the current line is selected.
So I modified Bryan's example code to NOT highlight the current line if any text is selected:
import Tkinter as tk

class MyApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.text = tk.Text(self)
        self.text.pack(side="top", fill="both", expand=True)
        self.text.tag_configure("current_line", background="#e9e9e9")
        self._highlight_current_line()

    def _highlight_current_line(self, interval=100):
        '''Rehighlights the 'current line' every "interval" milliseconds'''
        self.text.tag_remove("current_line", 1.0, "end")

        # If text is selected, DON'T highlight the current line.
        try:
            text = self.text.get(tk.SEL_FIRST, tk.SEL_LAST)
        except tk.TclError:
            self.text.tag_add("current_line",
                                "insert linestart", "insert lineend+1c")

        self.after(interval, self._highlight_current_line)

app = MyApp()
app.mainloop()

I hope this helps somebody.


text:
Q: What is the proper way to pass a hash as a parameter to function call? I have a function:
def a p
  p
end

and a hash of symbols :a => :b. How should I pass it as a's parameter? What are possible ways?
I can use parentheses or the shorter form:
a(:a => :b) # => {:a=>:b}
a(a: :b)    # => {:a=>:b}

Is there any way to pass this hash as a parameter without setting a variable and using parens? Just omitting them doesn't work.
a :a => :b # => SyntaxError: (irb):103: syntax error, unexpected ':', expecting end-of-input
a a: :b    # => SyntaxError: (irb):105: syntax error, unexpected ':', expecting end-of-input


text:
Q: Данные с другой стены сообщества VK (VK API, JSON, Retrofit, JAVA) Делаю Api запрос на получение постов тестовой группы VK (все по докам Вконтакте):
https://api.vk.com/method/wall.get?owner_id=-116125443&offset=0&count=5&v=5.52&access_token=THIS_IS_SECRET_DATA

В браузере получаю JSON:
{"response":{"count":30,"items":[{"id":31,"from_id":-116125443,"owner_id":-116125443,"date":1503404720,"marked_as_ads":0,"post_type":"post","text":"Еще одно подтверждение, как здорово заходят хиты даже через 15 лет. Немцы Reamonn в начале 2000-х сделали прорыв со своей меланхоличной \"Supergirl\". В 2017 году их успеть решили повторить Anna Nackab.","signer_id":276417933,"can_delete":1,"can_pin":1,"attachments":[{"type":"audio","audio":{"artist":"Программа \"Сэмпл один на Всех!\"","id":456241280,"owner_id":2000147926,"title":"Reamon vs. Anna Naclab","duration":25,"url":"https:\/\/vk.com\/mp3\/audio_api_unavailable.mp3","date":1503404721,"genre_id":1001}}],"post_source":{"type":"vk"},"comments":{"count":2,"can_post":1},"likes":{"count":5,"user_likes":1,"can_like":0,"can_publish":1},"reposts":{"count":1,"user_reposted":1}},{"id":30,"from_id":-116125443,"owner_id":-116125443,"date":1480571513,"marked_as_ads":0,"post_type":"post","text":"В 1991 году песня Марка Коэна \"Walking in Memphis\" появилась в эфирах радиостанций. За все время своего существования песня \"обросла\" каверами и ремиксами, использовалась в качестве саундтреков к фильмам. И по сей день припев песни является самым узнаваемым! Кстати, и по сей день это один из успешных синглов США и Великобритании.","can_delete":1,"can_pin":1,"attachments":[{"type":"audio","audio":{"artist":"Программа \"Сэмпл один на Всех!\"","id":456240538,"owner_id":2000129726,"title":"DJ Smash vs. Marc Cohn","duration":25,"url":"https:\/\/vk.com\/mp3\/audio_api_unavailable.mp3","date":1480571513,"genre_id":18}}],"post_source":{"type":"vk"},"comments":{"count":0,"can_post":1},"likes":{"count":5,"user_likes":1,"can_like":0,"can_publish":1},"reposts":{"count":1,"user_reposted":1}},{"id":29,"from_id":-116125443,"owner_id":-116125443,"date":1480338116,"marked_as_ads":0,"post_type":"post","text":"В 2000-х хит от группы \"Руки Вверх\" \"Песенка №5\" зазвучала на европейских танцполах в англоязычном варианте. Вот это, действительно оказалось приятным. Русскоязычная песня стала основой для многих кавер-версий и ремиксов от Атлантики до Тихого океана! Как это произошло - в нашей программе!","can_delete":1,"can_pin":1,"attachments":[{"type":"audio","audio":{"artist":"Программа \"Сэмпл один на Всех!\"","id":456240399,"owner_id":2000124826,"title":"Руки Вверх vs. ATC","duration":25,"url":"","date":1480338116,"genre_id":18,"no_search":1,"content_restricted":1}}],"post_source":{"type":"vk"},"comments":{"count":0,"can_post":1},"likes":{"count":7,"user_likes":1,"can_like":0,"can_publish":1},"reposts":{"count":1,"user_reposted":1}},{"id":28,"from_id":-116125443,"owner_id":-116125443,"date":1480337719,"marked_as_ads":0,"post_type":"post","text":"Музыка преображает человека. Напевая любимый мотив, Вы преображаете все вокруг. А припев современной песни так и просится запомнится... А если мотив песни Вы можете вспомнить через несколько лет, то главная задача автора решена - Вы стали его поклонником . Как изменялась одна популярная песня на протяжении нескольких лет. Добро пожаловать в мир программы.","can_delete":1,"can_pin":1,"attachments":[{"type":"audio","audio":{"artist":"Программа \"Сэмпл один на Всех!\"","id":456240300,"owner_id":2000124943,"title":"Frida Gold vs. Gala","duration":25,"url":"https:\/\/vk.com\/mp3\/audio_api_unavailable.mp3","date":1480337719,"genre_id":18}}],"post_source":{"type":"vk"},"comments":{"count":0,"can_post":1},"likes":{"count":4,"user_likes":1,"can_like":0,"can_publish":1},"reposts":{"count":1,"user_reposted":1}},{"id":27,"from_id":-116125443,"owner_id":-116125443,"date":1467535791,"marked_as_ads":0,"post_type":"post","text":"Этой истории уже более 10-ти лет. Для современной музыкальной истории не такой большой срок, но тем не менее, изменения очевидны.  DJ David Guetta еще раз подтвердил свое умение делать хорошие хиты, пусть и на старом материале. Об этом в нашей программе.","can_delete":1,"can_pin":1,"attachments":[{"type":"audio","audio":{"artist":"Программа \"Сэмпл Один на Всех!\"","id":456239491,"owner_id":2000338373,"title":"David Guetta vs. Alice Deejay","duration":25,"url":"https:\/\/vk.com\/mp3\/audio_api_unavailable.mp3","date":1467535791,"genre_id":18}}],"post_source":{"type":"vk"},"comments":{"count":0,"can_post":1},"likes":{"count":6,"user_likes":1,"can_like":0,"can_publish":1},"reposts":{"count":1,"user_reposted":1}}]}}

Делаю запрос Get:
public interface WallInterface {
@GET("/method/wall.get?")
Call<String> getresponse (@Query("owner_id=") String OWNER_ID, @Query("offset") String OFFSET, @Query("count") String COUNT, @Query("v") String version,@Query("access_token") String access_token);

}

Достаю данные:
private void getresponse() throws IOException {
        Retrofit retrofit = NetworkClient.getRetrofitClient();
        WallInterface wallInterface = retrofit.create(WallInterface.class);
        Call<String> call = wallInterface.getresponse("-116125443", "0", "5", "5.52", "THIS_IS_SECRET_DATA");
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful()){
                    if (response.body() !=null){
                        System.out.println("onSuccess - " +response.body().toString());
                        String jsonresponse = response.body().toString();
                        textView.setText(jsonresponse);

                    } else {
                        System.out.println("not Success");
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

Мне возвращается jsonresponse в виде постов на моей личной стене, а не группы. Как так???

A: Рабочий код следующий:
@GET("/method/wall.get")
Call<String> getresponse (@Query("owner_id") String OWNER_ID, @Query("offset") String OFFSET, @Query("count") String COUNT, @Query("v") String version,@Query("access_token") String access_token);
}

Лишний символ "=" был в параметре @Query("owner_id")...  и знак "?" в @GET (см. выше).


text:
Q: The number of injective functions if there is not the same number of elements on each side I'm having a hard time really understanding the logic. If my domain has 3 elements, and my codomain has 2 elements, how many injective functions are possible? I know there are 3^2 functions possible, but I do not know how to reason after.
Domain = a,b,c and Codomain = a,b
If a has an image, there's only one possibility for b or c to have an image after. That's is how I see it.
Thanks for the help.


text:
Q: iPhone back camera cannot focus correctly I've been making an iOS camera app and trying to solve this problem for two days (but cannot solve this).
What I'm working on now is change the focus and exposure automatically depending on the user's tapped location. Sometimes it works fine (maybe about  20% in total), but mostly it fails. Especially when I try to focus on a far object (like 5+metre) or when there are two objects and try to switch the focus of one object to another. The image below is an example.

The yellow square locates where the user tapped and even though I tapped the black cup in the first picture, the camera still focuses on the red cup.
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touchPoint = touches.first! as UITouch
        let focusPoint = touchPoint.location(in: lfView)
        print("focusPoint \(focusPoint)")

        showPointOfInterestViewAtPoint(point: focusPoint)
        setFocus(focusMode: .autoFocus, exposureMode: .autoExpose, atPoint: focusPoint, shouldMonitorSujectAreaChange: true)
    }

    func setFocus(focusMode: AVCaptureDevice.FocusMode, exposureMode: AVCaptureDevice.ExposureMode, atPoint devicePoint: CGPoint, shouldMonitorSujectAreaChange: Bool) {

        guard let captureDevice = captureDevice else { return }

        do {
            try captureDevice.lockForConfiguration()
        } catch let error as NSError { return }

        if captureDevice.isFocusPointOfInterestSupported, captureDevice.isFocusModeSupported(focusMode) {
            captureDevice.focusPointOfInterest = devicePoint
            captureDevice.focusMode = focusMode
            print("devicePoint: \(devicePoint)")

        }

        // other codes in here...

        captureDevice.isSubjectAreaChangeMonitoringEnabled = shouldMonitorSujectAreaChange
        captureDevice.unlockForConfiguration()
    }

I called the setFocus function in touchesBegan function and both focusPoint & devicePoint comments show the same coordinate, like (297.5, 88.0).
When I tapped the black cup in the picture, I can see the iPhone camera is zooming in and out a little bit, like same as when I use the default iPhone camera app and try to focus on an object. So I guess my camera app is trying to focus on the black cup but it fails.
Since this is not an error, I'm not sure which code to change. Is there any clue what is going on here and what causes this problem?
ADD THIS PART LATER
I also read this document and it says

This property's CGPoint value uses a coordinate system where {0,0} is the top-left of the picture area and {1,1} is the bottom-right.

As I wrote before, the value of devicePoint gives me more than 1, like 297.5, 88.0. Does this cause the problem?

A: Thanks to @Artem I was able to solve the problem. All I needed to do was convert the absolute coordinate to the value used in focusPointOfInterest (min (0,0) to max (1,1)).
Thank you, Artem!!


text:
Q: Mostrar nombre de mes en dropdownlist en ASP.NET C# Hola amigos estoy haciendo una aplicación donde tengo 3 dropdownlist en cascada mi problema es que quiero mostrar el nombre del mes en mi dropdownlist y no el numero cuando mando a traer mi procedimiento almacenado. Estoy usando Asp.net c#. Les muestro mi código espero puedan ayudarme Gracias.
Capa Datos
    public DataTable Mes(int id_Pais, int Año)
    {
        SqlParameter[] sqlparameter =
        {
            new SqlParameter("@Id_Pais", SqlDbType.Int),
            new SqlParameter("@Año", SqlDbType.Int)
        };

        sqlparameter[0].Value = id_Pais;
        sqlparameter[1].Value = Año;

        return _conexion.ExecuteDataTable("mes",sqlparameter);
    }

este es mi primero código donde solo llamo a mi procedimiento "mes" y le paso los parametros.
Capa de Negocio
 public DataTable Listar_Mes(int id_Pais, int Año)
    {
        return conexion.Mes(id_Pais,Año);
    }

Capa Presentacion
int id_Pais = Convert.ToInt32(this.ddlPais.SelectedValue);
            int Año = Convert.ToInt32(this.ddlAño.SelectedValue);
            DataTable dt = new DataTable();
            dt = t.Mes(id_Pais, Año);
            ddlMes.DataSource = dt;
            ddlMes.DataTextField= "".ToString(); //Aqui es donde quiero mostrar los nombres de los meses y no el numero
            ddlMes.DataValueField = "mes".ToString();
            ddlMes.DataBind();

Este es el resultado de mi interfaz
Este es el resultado de mi procedimiento almacenado

A: Recomendaria que inspecciones el datatable cuando este retorna una respuesta evaluando que nombre le asigna a este campo sin alias en el procedure

Entonces al detenerse la ejecucion en el breakpoint usa la lupa que se visualiza al inspeccionar la variable y alli obtendras la estructura del datatable pudiendo observar que nombre la asigna a esa columna
El nombre que le asigne lo usaras en DataTextField


text:
Q: Ignore first two special characters, and grab everything after that The nature of problem i am in is like, as described below:
I have string like that radiobutton1_2_3_4 or imagelist_1_34_54
what I want to do is to grab everything after 3rd underscore(_).
id.substring(id.indexOf('_') I tried to this but in my case it did not worked.
Regards

A: If it's always going to be the last underscore you could use id.substring(id.lastIndexOf('_')), otherwise id.split('_')[3] should work.
var split = id.split('_');
var a = split[1], b = split[2], c = split[3];

That will store your three numbers in a,b,c


text:
Q: Can someone show me how I can pause my code until an onDataChange() Value event listener has completed? Can someone please show me how I can pause my code in onCreate() until the event listener getting data from my firebase realtime DB has completed?
I have been stuck on this for a while now, anything that does not involve me completely reformatting my code would be awesome.
My code works but when getting data from the firebase my code continues to run without waiting for the EventListener to recieve the data...
I need to be able to stop the code but I do not know how...
-Just a suggestion: is it possible to use Thread.wait() and Thread.notify()?
I don't understand how threads/tasks/runnables work that well so a good explanation would be appreciated.

    public void createNullRoom() {
        room.setPlayerWhoIsSpyer(0);
        room.add(1);
        room.add(2);
        room.add(3);
        room.add(4);
        room.add(5);
        room.add(6);
        room.setRoomCode("room_0");
        room.setWinner(0);
        room.setScene(0);
        room.setRoundHasEnded(true);
        room.setSecretWord("");
        this.gameRoom.add(0,room);
        pref.child(room.getRoomCode()).setValue(room);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.w(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "Game.onCreate");
        setContentView(R.layout.gameview_public);
        pId = 0;
        room = new Room();
        AssignUser = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                gameRoom.clear();
                long v = snapshot.child("gameRoom").getChildrenCount();
                int count = (int) v;
                for (int i = 0; i < count + 1; i++) {
                    Room r = new Room();
                    boolean temp = true;
                    try {
                        r = snapshot.child("gameRoom").child("room_" + i).getValue(Room.class);
                    } catch (IndexOutOfBoundsException e) {
                        temp = false;
                    }
                    if (temp) {
                        gameRoom.add(r);
                    }
                }
                Log.i(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "gameRoom data retrieved");
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        };

// ---- VALUE EVENT LISTENER TO GET DATA ------
AssignUser = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                gameRoom.clear();
                long v = snapshot.child("gameRoom").getChildrenCount();
                int count = (int) v;
                for (int i = 0; i < count + 1; i++) {
                    Room r = new Room();
                    boolean temp = true;
                    try {
                        r = snapshot.child("gameRoom").child("room_" + i).getValue(Room.class);
                    } catch (IndexOutOfBoundsException e) {
                        temp = false;
                    }
                    if (temp) {
                        gameRoom.add(r);
                        Log.i(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "\tSize: " + gameRoom.size());
                    }
                }
                Log.i(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "gameRoom data retrieved");
                Log.e(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "inside the snapshot, gamerooms.size: " + gameRoom.size() + " line 343");
                assignUser();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        };

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

        ref.addListenerForSingleValueEvent(AssignUser);

        createNullRoom();

       // ===================================THIS NEEDS TO PAUSE HERE

        int i = 0;
        while(playerjoined == false) {
            boolean exists = true;
            Log.i(this.getClass().getName() +".java/"+ new Throwable().getStackTrace()[0].getLineNumber(), "line 431: if");
            try {
                this.room = this.gameRoom.get(i);
            } catch (IndexOutOfBoundsException e) {
                exists = false;
            }
            if (exists) {
                this.room = gameRoom.get(i);
                this.roomcode = this.room.getRoomCode();
                for (int q = 1; q < 7; q++) {
                    if(this.getFalse() == q) {
                        this.room.add(q);
                        this.pref.child(this.roomcode).setValue(this.room);
                        this.pId = q;
                        q = 6;
                        playerjoined = true;
                    }
                }
                if(playerjoined == false) {
                    i++;
                }
            } else {
                CreateNewPublicRoom(i);
                Log.i(this.getClass().getName() +".java/"+ new Throwable().getStackTrace()[0].getLineNumber(), "Game.java/" + Thread.currentThread().getStackTrace()[1].getLineNumber() + "\tNew Public Room Made");
                pref.child(this.roomcode).setValue(this.room);
                Log.e(this.getClass().getName() +".java/"+ new Throwable().getStackTrace()[0].getLineNumber(),"OUTSIDE the snapshot, gamerooms.size: " + gameRoom.size() + " line 403");
                Log.i(this.getClass().getName() +".java/"+ new Throwable().getStackTrace()[0].getLineNumber(),  "\tThis.playerjoined == "+playerjoined);
            }
        }
   ref.child("gameRoom").child(this.room.getRoomCode()).setValue(this.room)

etc...


text:
Q: On C# WinForm ListBox how to clear the selection of multiple items with a key pressed? I'm trying to clear the selection of all items in a WinFom ListBox when the escape key is pressed.
I created a KeyPress event handler in order to catch the event. It works when only one item is selected, but when multiple items are selected the event never triggers, . Any idea of what is happening?
Thanks in advance.
Here I attached my event handler:
private void EscapeKeyPressed(object sender, KeyPressEventArgs e)
    {
        try
        {
            if (e.KeyChar == (char)Keys.Escape)
            {
                switch (sender.GetType().GetProperty("Name").GetValue(sender, null).ToString())
                {
                    case "LineLB":
                        LineLB.ClearSelected();
                        break;
                    case "ApplicationLB":
                        ApplicationLB.ClearSelected();
                        break;
                    default:
                        break;
                }
            }
        }
        catch(Exception ex) { MessageBox.Show(ex.Message); }

--20150526--
Thanks all you guys for your comments and suggestions. It was a focus problem as some of you mentioned before. I add a line of code in the SelectedIndexChange event handler, and here the comparison.
Before
private void LineLB_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (LineLB.SelectedItems.Count > 1)
                ClearControlsFromPanel(PanelUser);
            else{
                   ...

After
    private void LineLB_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (LineLB.SelectedItems.Count > 1){
                ClearControlsFromPanel(PanelLine);
                LineLB.Focus();
            }
            else{
                   ...

A: this is due to focus out with one ListBox when you working with other ListBox, you need to work with KeyPress event of the Form instead of ListBox.


text:
Q: "is_logged_in" templatetag does not render for some reason, templatetags do not render in templates for django admin.
with this snippet from:
http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#shortcut-for-simple-tags
{% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %}

when placed in admin index.html, if a user is logged in, it shows "Please log in"
same with templatetags, can not get any app ones to show, do anything. there is no error/they do not get processed either

A: That's only an example, the is_logged_in variable is not actually defined in any templates unless you put it in the context.
If you added that line and got Please log in. it does mean that the tag is rendering.  If it fails the if and goes to the else it is clearly being run.  You need to find something in the template you can actually use for the if case, though.  I haven't messed with the admin templates in newforms-admin, but depending if they use RequestContext and on which ContextProcessors you have enabled - you might be able to say {% if not request.user.is_anonymous %} ... or something similar.

A: I just tried this one:
request.user.is_authenticated
Right in the template and just worked as we wish!


text:
Q: Error in or another way of calculating $\frac{1}{2} \in \mathbb{Q}_3$ I want to find the $p$-adic expansion of $\frac{1}{2} \in \mathbb{Q}_3$. I begin with noting that $- \frac{1}{2} = \frac{1}{1-3} = \sum_{n=0}^{\infty} 3^n$. Therefore, $\frac{1}{2} = 1 - \frac{1}{2} = 2 + 3 + 3^2 + \ldots$. So far so good. However; Note that $$\frac{1}{2}= -4 \cdot \frac{1}{1-3^2} = -4 \sum_{n=0}^{\infty} 3^{2n} = -4(1 + 3^2 + 3^4 + \cdots ).$$ I'm relatively new at the $p$-adic theory, but as I understand it, the coefficients all have to be considered modulo $p$, so in this case $-4 = 2$. So where did I went wrong?
As always, any help would be greatly appreciated.
EDIT As pointed out, it's a really big error just to set $-4=2$. However, if one should choose to continue with the reasoning that $$1/2 = -4\sum_{n=0}^{\infty} 3^{2n},$$ how could one then find a $p$-adic expansion of $1/2$?

A: This "gotcha" illustrates a feature that has deceived many people: yes, a $p$-adic integer has what looks like a sort of power series expansion $\sum_{n\ge 0} c_n\cdot p^n$ with $0\le c_n<p$, but these expansions do not behave stably under addition or multiplication. That is, regrouping or rearranging is required to put the result of such operations back in this form. Also, there are many other (convergent!) expansions of $p$-adic numbers (as this example illustrates), much like there are many other expansions of real numbers beside decimal expansions $\sum c_n/10^n$ with $0\le c_n\le 9$.
Altogether, the situation argues for not thinking of $p$-adic numbers as being "exactly" those special expansions, although that does give a transitional viewpoint. Instead, a $p$-adic integer is "represented" by any sequence of ordinary integers $a_n$, such that $a_{n+1}=a_n \mod p^n$. Correctly-enough, this makes things look a bit different from the real numbers.

A: If $a_k=b_k$ for all $k\ne n$ and $a_n=b_n+c$ then $\sum a_k3^k=3^nc+\sum b_k3^k$ so that $\sum a_k3^k\ne\sum b_k3^k$ if $c\ne0$, even if $3\mid c$. Thus you cannot use $-4=2$ just like that here.


text:
Q: Font Awesome Icons not displaying anymore (2020) I checked my code for missing semicolons in the styles and missing brackets in the html but everything looks fine but the Font Awesome icons are not displaying.
For example, there are supposed to be down carets at the end of every navigation item in the second navigation bar.
When I inspected the page, the icons are still in the DOM but I do get this error in the console: Failed to load resource: the server responded with a status of 404 ().
Can someone please help me figure out what is going on here? I don't think it's my code, I think it's something to do with Font Awesome but I could be wrong.
EDIT: Upon further inspection, it seems that all of my font awesome icons have a 0 width value. Not sure why.
CodePen
Here is my kit code:
<script src="https://kit.fontawesome.com/2641fe0f3e.js" crossorigin="anonymous"></script>


text:
Q: Wxpython: TreeCtrl: Iteration over a tree I am using the following method to iterate over all the nodes of a wxpython treectrl.
 def get_desired_parent(self, name, selectednode = None):
    if selectednode == None:
        selectednode = self.treeCtrl.RootItem
    # First perform the action on the first object separately
    childcount = self.treeCtrl.GetChildrenCount(selectednode, False)
    if childcount == 0:
        return None

    (item,cookie) = self.treeCtrl.GetFirstChild(selectednode)
    if self.treeCtrl.GetItemText(item) == name:
        return item

    while childcount > 1:
        childcount = childcount - 1
     # Then iterate over the rest of objects
        (item,cookie) = self.treeCtrl.GetNextChild(item,cookie)
        if self.treeCtrl.GetItemText(item) == name:
            return item
    return None

This problem of excess code becomes even more apparent when I am iterating inside the structure recursively.
Is there another way of performing the same actions in more compact manner, to make my code more concise / pythonic.

A: You could use a function that is inside this one (in its namespace only) that will check if it matches the conditiin or not. If it does return the item if it doesn't, continue.
Otherwise you could check your condition just after the while line. This way the item variable will be defined by the first child before the loop and evaluated like any other.
Still another way: (or a mix of the two)
(child, cookie) = self.GetFirstChild(item)
while child.IsOk():
    do_something(child)
     (child, cookie) = self.GetNextChild(item, cookie)

A: Here a full example that traverses the tree going depth first. The function was bound to the right button.
def OnRightDown(self, event):
    def showChildren(item,cookie):
        # functions goes recursively down the tree
        if item.IsOk():
            child, cookie = self.tree.GetFirstChild(item)
            while child.IsOk():
                child, cookie = self.tree.GetNextChild(child, cookie)
                if child:
                  print(self.tree.GetItemText(child)) #show child label name
                  showChildren(child,cookie)
    pt = event.GetPosition()
    item, flags = self.tree.HitTest(pt)
    if item:
        print(self.tree.GetItemText(item)) #show parent label name
        showChildren(item,0)  #iterate depth first into the tree

A: The best way to make your code highly readable here is to make it short and highly functional.
If you need to iterate through all the tree items and do so through depth first. Here's that as a single quick function. Hand it a function that gets each item, and where you start (usually self.root). It's also quite reusable since you might be doing this a lot.
    def depth_first_tree(self, funct, item):
        (child, cookie) = self.tree.GetFirstChild(item)
        while child.IsOk():
            self.depth_first_tree(funct, child)
            funct(child)
            (child, cookie) = self.tree.GetNextChild(item, cookie)


text:
Q: Getting Data From Rows Comparing it However All Cells Gets Updated good day so we encontered a problem witho ur javascript problem
what it does is that it gets the data of rows and puts it in an array. and compares it
if its empty the inner text becomes "pay" otherwise "paid" here's the code:
$(document).ready(function() {
    var arr = [];
    var arr2 = [];
    var oTable = document.getElementById('example');

    //gets rows of table
    var rowLength = oTable.rows.length;

    //loops through rows
    for (i = 0; i < rowLength; i++){

      //gets cells of current row
       var oCells = oTable.rows.item(i).cells;

       //gets amount of cells of current row
       var cellLength = 1;

       //loops through each cell in current row
       for(var j = 0; j < cellLength; j++){

              // get your cell info here

              var cellVal = oCells.item(1).innerText;
              arr.push(cellVal);
           }
    }

    for (a = 0; a < rowLength; a++){

      //gets cells of current row
       var oCells = oTable.rows.item(a).cells;

       //gets amount of cells of current row
       var cellLength = 1;

       //loops through each cell in current row
       for(var b = 0; b < cellLength; b++){

              // get your cell info here

              var cellVal = oCells.item(7).innerText;
              console.log(oCells.item(7).innerText);

              if (arr[b] == '') {
                oCells.item(7).innerText = "Pay";
              } else {
                oCells.item(7).innerText = "Paid";
              }

              arr2.push(cellVal);
       }
    }
    });

this script  does what is said above, this is actually taken from another source we tried to incorporate on our software, but yeah
it doesn't work the way we want it to.
It does make the change but the change happens for all the cells instead of one. we tried to generate it in the inspec console however we see our rows were clearly generated.
Any help is appreciated. Thankyou very much!


text:
Q: Reading from app.config in .NET Core application referencing .NET Standard library I'm converting over some existing code from .NET Framework to .NET Standard for use in .NET Core apps.  The library project has been converted over and is building fine.  It contains some database access code that uses EF Core.  Due to the legacy nature of the consumers for this code I wanted to continue using the App.Config or Web.Config files with Configuration Manager.  To do this I added the System.Configuration.ConfigurationManager NuGet package to the library project.
The library is validated with a unit test project that uses MSTest.  The project was targeting .NET Framework 4.7.1, which could consume the .NET Standard 2.0 library package.  When targeting .NET Framework, all of the unit tests were passing.
After changing the unit test project to target .NET Core 2.0, the database code is no longer able to find the connection strings stored in the App.Config file of the unit test project.  When I debug the test and inspect the ConfigurationManager.ConnectionStrings collection, I only see one defined that appears to be a SQL Express connection likely coming from the Machine.Config file.
Has anyone had success accessing App.Config from a .NET Core app passing through a .NET Standard library with the ConfigurationManager compatibility library?

A: Still there is a known issue in Microsoft.Net.Test.Sdk and it is because when you use ConfigurationManager in test applications using .Net Core, ConfigurationManager is looking for testhost.dll.config and not your standard assembly config file.
There is a non-pleasant workaround for this issue based on this discussion in github which you can copy your App.Config file into your output directory with name testhost.dll.config by putting this element in your test csproj file:
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
    <Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
</Target>

And then you can use ConfigurationManager.OpenMappedExeConfiguration to load your config file.
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "testhost.dll.config";

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

And for example for reading an appsetting you can do like this:
var setting = Config.AppSettings.Settings[key];


text:
Q: How to compare Variable with CSV file content in Jmeter I have HTTP request whose response is below
{
  "DATA": {
     "G_1": {
      "OR_ID": "100400",
      "LEGAL_ENTITY": "TEST",
      "BUSINESS_UNIT": "TEST BU"
    },
    "G_2": {
      "OR_ID": "100500",
      "LEGAL_ENTITY": "Test1 ",
      "BUSINESS_UNIT": "Test1 "
    },
    "G_2": {
      "OR_ID": "100100",
      "LEGAL_ENTITY": "TEST3 ",
      "BUSINESS_UNIT": "Test3"
    }
}

I need to get OR_ID from the above response, which I am able to do it using Regular exp extractor.
There is Input CSV file which has multiple rows. For the CSV file, i need to check the OR_ID exists or not in column 2, if exists then I have to take columns 5 and 7 and pass it to my next post request in the body. In CSV the same OR_ID repeated, so i need repeat post request for all the repeated values of OR_ID in csv.  CSV file has no header.
441919244,100010,QUTRN,TEST Inc.,100100,TEST,VCG and A, INC,USD,3409.0900,O,ICO-VCG-0140,2019-10-31,52 945,USD,USD,359409.0900,359409.0900,359409.0900,Processed,93901372,File,2019111NG52.csv,
441919028,100400,QUQED,TEST MEDICAL EDUCATION INC.,100020,QUINC,TEST INC.,USD,12.340,O,ICO-INC-8718,2019-10-31,52 729,USD,USD,12.3400,12.3400,12.3400,Processed,93901372,,File,20191113NG52.csv,

Can you please help.

A: Assuming that you can extract the OR_ID from the JSON response following solution could be useful.

*

*In the CSV Data Set Config Element or Random CSV Data Set Config plugin read the CSV file assign the variable names to the respective columns

variable names = C1,OR_ID,C3,C4,C5,C6,C7,C8,C9

*Add a While Controller as a parent to the CSV Data Set config elements and the HTTP Request where you want to send data from the CSV file.

${__jexl3("${OR_ID}"!="EOF")}
  This will check EOF in the column 2 of the CSV file. Hence please add
  ,EOF,,
  as the last line of the CSV file.

*Add IF controller to the HTTP Request with following condition

${__jexl3("${OR_ID}"=="${OR_ID_J}")}

OR_ID_J  is the OR_ID picked from the JASON response.

*Use ${C5} and ${C7} in the places where you want to insert the data from the CSV file.

*Reset the OR_ID to "" using a JSSR223 Sampler with following

vars.put("OR_ID", "");

Sample Test Plan is available in GitHub


text:
Q: C++ is there a difference between dereferencing and using dot operator, vs using the arrow operator Let's say I have the following variable:
MyObject* obj = ...;

If this object has the field foo, there are two ways of accessing it:

*

*obj->foo

*(*obj).foo
Are there any differences between using one method over the other. Or is the first method just syntactic sugar for the second?
I was thinking maybe the first one could cause the copy constructor of the object to be called since it is now holding onto the value.

A: There is no difference when obj is a pointer.
If obj is an object of some class, obj->foo will call operator->() and (*obj).foo will call operator*(). You could in theory overload these to do totally different behavior, but that would be a very badly designed class.

A: According to §7.6.1.5 ¶2 of the ISO C++20 standard, the expression obj->foo is converted to (*obj).foo. So it is just syntactic sugar. Both are equivalent.

I was thinking maybe the first one could cause the copy constructor of the object to be called since it is now holding onto the value.

No constructor will be called, because no new object is created.

A:
is the first method just syntactic sugar for the second?

Yes.

I was thinking maybe the first one could cause the copy constructor of the object to be called

No.

Technically, there is a difference that operator. cannot be overloaded for classes while operator-> can be overloaded. Operators -> and * should be overloaded such that it->foo and (*it).foo remain equivalent, although the language technically doesn't enforce that.


text:
Q: Как на WordPress сделать pdf фаил только для просмотра? Как можно на WordPress защитить фаил от скачивания и принта и сделать его только для просмотра?

A: Я на своих клиентских проектах использую сервис infoprotector, который защищает от копирования и pdf и doc и video. Товарищи пиарят плагин под WordPress под названием CopySafe PDF Protection. Попробуйте, может и вам подойжет.

A: Максимум, что вы можете сделать, это усложнить получение документа с помощью какой-нибудь DRM. Но DRM работает только тогда, когда просмотрщик с ней совместим, а значит, от произвольного пользователя это не спасёт. Только если вы планируете показывать документ с машин, которым вы доверяете, и на которых нет средств, чтобы его скачать или напечатать.
Вот одно из бурных обсуждений о добавлении DRM-подобных фич в pdf.js. Как видно, они ещё не добавлены.
Так что для широкой аудитории — никак.


text:
Q: Eliminar archivos desde el controlador Estoy usando laravel 6
Tengo 2 tablas:
Tabla 1: id, descripción.
Tabla 2: id, tabla1_id, file, file2
la tabla1 tiene la relacion de hasMany
la tabla2 tiene relacion de belongsTo
Al eliminar la tabla1 tambien se elimina la tabla2. Lo que quiero hacer es que al eliminar la tabla1 se borre la tabla2 junto a todos los archivos que tengo en el proyecto cuya ruta está en la base de datos en los campos file
si elimino por aparte un campo de la tabla2 se elimina junto al archivo con el siguiente codigo:
unlink(storage_path('app/public/'.$tabla2->file));
unlink(storage_path('app/public/'.$tabla2->file2));

Pero al intentar eliminar todo desde la tabla1 no me funciona, he intentado con esto:
public function destroy($id){
   $tabla1    = Tabla1::find($id);
   $tabla2    = Tabla2::all()->where('tabla1_id', $id);

   if(isset($tabla2->file)){
     unlink(storage_path('app/public/'.$tabla2->file));
   }
   if(isset($tabla2->file2)){
     unlink(storage_path('app/public/'.$tabla->file2));
   }

   $tabla1->delete();
}

A: Por una lado, la consulta la puedes hacer así, en vez de traer todas las filas y después filtrar la colección:
$tabla2 = Tabla2::where('tabla1_id', $id)->get();

Luego, para eliminar los archivos, te sugiero usar File Storage.
Puedes declarar un array para ir guardando los nombres de los archivos que existan en el disco. Usando Storage::disk('public') ya no tendrás que especificar la ruta con storage_path('app/public/'. ...), pues es la ruta predeteminada de ese disco de Storage:
$array_de_archivos = [];

foreach($tabla2 as $fila) {
    if( Storage::disk('public')->exists($fila->file) )
        $array_de_archivos[] = $fila->file;
    if( Storage::disk('public')->exists($fila->file2) )
        $array_de_archivos[] = $fila->file2;
}

Una vez que tengas el array con todos los nombres de archivos existentes, puedes pasárselo directamente al método delete() de Storage:
Storage::disk('public')->delete($array_de_archivos);

A: Para eliminar registros podes usar
DB::table('table_name')->delete();

Y para hacer un truncate
DB::table('table_name')->truncate();


text:
Q: What's the best way to store and maintain the order of items? I have an EAV table of pages that houses the relationship between all pages and the books they belong to.
I need to be able to store and manipulate the order of the pages.
Now the obvious solution is to keep a page index for the pages.
+---------+---------+------------+
| page_id | book_id | page_index |
+---------+---------+------------+
|       1 |       1 |          1 |
|       2 |       1 |          2 |
|       3 |       1 |          3 |
|       4 |       1 |          4 |
|       5 |       1 |          5 |
|         |         |            |
|       6 |       2 |          1 |
|       7 |       2 |          2 |
|         |         |            |
|       8 |       3 |          1 |
+---------+---------+------------+

But now imagine you have 5000 pages, and you move the last page to the front. That means you have to append the page_index in 4999 rows, which I imagine can get heavy.
I considered implementing a linked list in MySQL like so:
+---------+---------+-----------+-----------+
| page_id | book_id | prev_page | next_page |
+---------+---------+-----------+-----------+
|       1 |       1 | NULL      | 2         |
|       2 |       1 | 1         | 3         |
|       3 |       1 | 2         | 4         |
|       4 |       1 | 3         | 5         |
|       5 |       1 | 4         | NULL      |
|         |         |           |           |
|       6 |       2 | NULL      | 7         |
|       7 |       2 | 6         | NULL      |
|         |         |           |           |
|       8 |       3 | NULL      | NULL      |
+---------+---------+-----------+-----------+

That way if you move a page, all you have to change is it's own row and the row of the page you swapped with. However, I also need to implement sorting multiple rows at once (and they don't have to be in a "line" (they can be cherry picked from anywhere and combined into a line), and the supporting PHP to accomplish that with this linked list method would be substantially more complex than with a simple page_index.
I could also add a column to the books table called page_order in which I could store a comma delimited array of page indices which would be easier to maintain as the new array would be generated using PHP and not MySQL. But I'm hesitant to do so because array's aren't officially supported by MySQL. It would be more of a hack.
Is there a better solution to my problem?


text:
Q: Eclipse Xtext : How to force Xtext to look for a reference with a specific Name I defined a gramar like this

grammar org.xtext.example.mydsl1.MyDsl with org.eclipse.xtext.common.Terminals
generate myDsl "http://www.xtext.org/example/mydsl1/MyDsl"

Model:
    persons+=(Person | David)
    greetings=(GreetDavid | Greet);

Person returns Person:
    'Holla. My name is' name=ID         //First "create" a person
;
David returns Person:
  'Holla. My name is' name='David'          //David is a special person. He has name David
;
GreetDavid returns Greeting:
    'Hello' person=[David]           //Only greet David with Hello
;
Greet returns Greeting:
    'Hi' person=[Person]           //Greet other persons with Hi
;

Of course, Xtext complains that David is not a known type : "Cannot resolve type null"
How can I simply tell Xtext that David is a person that will be created with name "David"?
I dont want to change the Ecore and create a class specifically for David.
Thanks in advance

A: You could use a data type rule.
e.g.
DAVID:'David';
David returns Person:
    'Holla. My name is' name=DAVID
;
GreetDavid returns Greeting:
    'Hello' person=[Person|DAVID]           //Only greet David with Hello
;


text:
Q: Why does pg_dump ignore .pgpass? I have created a .pgpass file which works perfectly for my psql command.
chris@ap2155489:~$ psql --host=my.example.com --port=12345 --username=chris -d example_db
psql (9.6.13)
SSL connection (protocol: TLSv1.2, cipher: xxx, bits: 256, compression: off)
Type "help" for help.

example_db=> \q

When I try to run pg_dump I get my password asked.
I did chmod 0600 to my .pgpass file
chris@ap2155489:~$ pg_dump --host=my.example.com --port=12345 --username=chris -d example_db -f dbs/test.sql --clean
Password:

What am I doing wrong?
Both commands run from home directory
UPDATE:
~$ ll /usr/bin/pg_dump
lrwxrwxrwx 1 root root 37 May  9  2019 /usr/bin/pg_dump -> ../share/postgresql-common/pg_wrapper*
~$ ll /usr/bin/psql
lrwxrwxrwx 1 root root 37 May  9  2019 /usr/bin/psql -> ../share/postgresql-common/pg_wrapper*

A: So it seems like you're using an Ubuntu system that has postgresql-client-common installed.  pg_dump is overloaded by pg_wrapper, but .pgpass is supposed to work (I tried it on my test system and it's fine).  It seems that your sysadmin may have done something (possibly with Perl?) that has the side effect of making you unable to use .pgpass with pg_dump.
One possible way to know what's going on is by doing perl -e "exec env" and see what the $HOME var is set to (or maybe it got cleared out).  You can also possibly do an strace pg_dump and see which directories are touched -- this will generate a lot of output, so it might be hard for you to work with.
Ultimately, you will likely need to 1) talk with your sysadmin and see if the environment can be fixed up so that you can use .pgpass with the pg_wrapper's pseudo-pg_dump, or 2) Use pg_dump directly (Usually, that would be located in /usr/lib/postgresql/<version_number>/bin/pg_dump, but you should probably locate it with find /usr -name "pg_dump")


text:
Q: Android - Cannot send data to the next activity (extending ListActivity) after pulling JSON data through AsyncTask First and foremost, I am an android newbie.
I am creating a simple app which pulls some data from the server through a PHP script and showing them in a ListView in the next Activity. However, I find that if the script returns nothing, the app crashes. So I kept a check that only if the script returns some data, the app would switch to the next activity.This is my code.
public class HomeScreen extends ActionBarActivity {

String message3;
String message_short;
String[] items;
String[] short_items;
int check = 0;

private ProgressDialog dialog;

public String readJSONFeed(String URL)
{
    StringBuilder sb = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet hg = new HttpGet(URL);
    try
    {
        HttpResponse response = client.execute(hg);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if(statusCode == 200)
        {
            HttpEntity en = response.getEntity();
            InputStream content = en.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
        }
        else
        {
            Log.e("JSON", "Failed to download File");
        }
    }
    catch(ClientProtocolException e)
    {
        e.printStackTrace();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    return sb.toString();
}

private class ReadJSONFeedTask extends AsyncTask<String, Void, String>
{
    protected void onPreExecute()
    {
        super.onPreExecute();
        dialog = new ProgressDialog(HomeScreen.this);
        dialog.setMessage("Downloading Notifications. Please wait . . .");
        dialog.setIndeterminate(false);
        dialog.setCancelable(false);
        dialog.show();
    }
    protected String doInBackground(String...urls)
    {
        return readJSONFeed(urls[0]);
    }
    protected void onPostExecute(String result)
    {
        dialog.dismiss();
        try
        {
            JSONArray jsonArray = new JSONArray(result);
            items = new String[jsonArray.length()];
            short_items = new String[jsonArray.length()];
            for(int i = 0; i < jsonArray.length(); i++)
            {
                JSONObject jobj = jsonArray.getJSONObject(i);
                message3 = "SUBJECT : " + jobj.getString("subject") + "\n\n" +
                        "DATE : " + jobj.getString("date") + "\n" + jobj.getString("time") + "\n\n"
                         + "NOTICE : " + jobj.getString("notice");
                message_short = "SUBJECT : " + jobj.getString("subject") + "\n"
                        + "NOTICE : " + jobj.getString("notice").substring(0, 20) + "..."
                        + "\n" + jobj.getString("time");
                items[i] = message3;
                short_items[i] = message_short;

                check += 1;
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

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

public void notificationPane(View view)
{

    String localhost = "http://10.0.2.2/example/json/notification.php";
    new ReadJSONFeedTask().execute(localhost);

    if(check != 0)
    {
        Intent i = new Intent(HomeScreen.this, NotificationPanel.class);
        i.putExtra("items", items);
        i.putExtra("short_items", short_items);
        startActivity(i);
    }
    else
    {
        Toast.makeText(getBaseContext(), "Either there is no notification to display or there might be a problem with your internet connection.", Toast.LENGTH_SHORT).show();
    }
}

public void recentNotice(View view)
{

    String localhost = "http://10.0.2.2/example/json/recent_notification.php";
    new ReadJSONFeedTask().execute(localhost);

    if(check != 0)
    {
        Intent i = new Intent(HomeScreen.this, NotificationPanel.class);
        i.putExtra("items", items);
        i.putExtra("short_items", short_items);
        startActivity(i);
    }
    else
    {
        Toast.makeText(getBaseContext(), "Either there is no notification to display or there might be a problem with your internet connection.", Toast.LENGTH_SHORT).show();
    }
}
}

The int check is where I check whether the server has returned any JSON data. If the check is not 0, it does not switch to  the next activity.But problem with this code is that when I click the button, it shows me the TOAST Either there is no notification to display or there might be a problem with your internet connection. even before it has pulled data from the server, thus it never goes to the next Activity NotificationPanel.class. I understand this is due to the AsyncTask. What is more weird is if I keep clicking the button several times, the app suddenly switches to the next activity showing the data in ListView. But it doesn't always work. Is there a work around to this problem?Please help.Thank you in advance.

A: Move your code with if else to the last in onPostExecute. AsyncTask is still in execution when you check the result.

A: You should put this piece of code in the onPostExecute method:
if(check != 0)
{
    Intent i = new Intent(HomeScreen.this, NotificationPanel.class);
    i.putExtra("items", items);
    i.putExtra("short_items", short_items);
    startActivity(i);
}
else
{
    Toast.makeText(getBaseContext(), "Either there is no notification to display or there might be a problem with your internet connection.", Toast.LENGTH_SHORT).show();
}

Put them after your current code and tell me if it worked.
"What is more weird is if I keep clicking the button several times, the app suddenly switches to the next activity showing the data in ListView. But it doesn't always work. Is there a work around to this problem?"
What you are saying here is prety clear. You cannot run your intent at first, because json is not yet fetched, when you click the button first few times. But if you continue clicking it, it will eventually fetch JSON and be able to go to next activity.
SO I'm prety sure what I said is what needs to be done.
EDIT
I'm prety sure your async task should looklike this:
private class ReadJSONFeedTask extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute()
{
    super.onPreExecute();
    dialog = new ProgressDialog(HomeScreen.this);
    dialog.setMessage("Downloading Notifications. Please wait . . .");
    dialog.setIndeterminate(false);
    dialog.setCancelable(false);
    dialog.show();
}
 //no need a return statment
@Override
protected Void doInBackground(Void... params)
{

    try
    {
        JSONArray jsonArray = new JSONArray(readJSONFeed(urls[0]));
        items = new String[jsonArray.length()];
        short_items = new String[jsonArray.length()];
        for(int i = 0; i < jsonArray.length(); i++)
        {
            JSONObject jobj = jsonArray.getJSONObject(i);
            message3 = "SUBJECT : " + jobj.getString("subject") + "\n\n" +
                    "DATE : " + jobj.getString("date") + "\n" + jobj.getString("time") + "\n\n"
                     + "NOTICE : " + jobj.getString("notice");
            message_short = "SUBJECT : " + jobj.getString("subject") + "\n"
                    + "NOTICE : " + jobj.getString("notice").substring(0, 20) + "..."
                    + "\n" + jobj.getString("time");
            items[i] = message3;
            short_items[i] = message_short;

            check += 1;
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
@Override
protected void onPostExecute(String result)
{

    if(check != 0)
     {
       Intent i = new Intent(HomeScreen.this, NotificationPanel.class);
       i.putExtra("items", items);
       i.putExtra("short_items", short_items);
       startActivity(i);
     }
    else
     {
     Toast.makeText(getBaseContext(), "Either there is no notification to display or there might be a problem with your internet connection.", Toast.LENGTH_SHORT).show();
}

dialog.dismiss();
}
}


text:
Q: Getting the value of a specific div inside a table row I have a dynamic table with data from a database.
Each row contains 4 div elements, with some text.
I would like to be able to get the value of one of those div's.
Here is a little bit of the table:
function addData(Dato, BookedBy, Fra ,Til) {

              var tbl = document.getElementById('bookingListe');
              var lastRow = tbl.rows.length;

              // if there's no header row in the table, then iteration = lastRow + 1
              var iteration = lastRow;
              var row = tbl.insertRow(lastRow);

              // left cell
              var cellLeft = row.insertCell(0);
              var person = document.createElement("div");
              var dato = document.createElement("div");

              var fra = document.createElement("div");
              var til = document.createElement("div");
              var checkbox = document.createElement("input");
              checkbox.type = "checkbox";
              checkbox.name = "delete";

              dato.innerHTML ="Booket for: " + Dato;
              person.innerHTML ="Booket av: " + BookedBy;
              fra.innerHTML ="Fra: " + Fra;
              til.innerHTML ="Til: " + Til;

              cellLeft.appendChild(person);
              cellLeft.appendChild(dato);
              cellLeft.appendChild(checkbox);
              cellLeft.appendChild(til);
              cellLeft.appendChild(fra);

Here is the method for getting one of those divs.
function Slett(){
   $('#bookingListe').find('tr').each(function () {
      var row = $(this);
      if (row.find('input[type="checkbox"]').is(':checked')){
          alert(row.find('div').val());
        // Since there are 4 divs, the code above isn't going to work
      }
  });
 }

This isn't working, and Javascript isn't my strong side.
Any suggestions are appreciated.

A: I would recommend you to add unique class to div like
var dato = document.createElement("div");
d.className = "dato";

Then you can access it using class selector. As dato is a div element you need to use .html() or .text()
var dataText = row.find('.dato').html();


text:
Q: Need to create an HTML file that uses a javascript function to automatically send and email I want to create an HTML file that uses a javascript function to take HTML inputs and send them to a predetermined email address.
So far I have this, but my sendMail function isn't working and I'm not sure how to go about fixing it.
<!DOCTYPE html>

Complete fields and click submit:

<form id="from">

  Contacts First name: <input type="string" id="fname">

  Contacts Last name: <input type="string" id="lname">

  Contacts Phone Number: <input type="string" id="phoneNum">

  E-mail Address: <input type ="string" id="email">

  Description: <input type="string" id="desc"

  Attachments: <input type="file" id="fileupload" accept="image/*"

  <input type="button" onclick="sendMail()" value="Submit">

</form>

A: Variables aren't expanded inside strings (unless you use ES6 template strings). You need to concatenate:
var address = document.getElementById("email").value;
window.location.href = "mailto:yourAddress?subject=" + encodeURIComponent(subject) + "&body=" + encodeURIComponent(message);

BTW, this won't attach the file in the email.


text:
Q: Extract GZIP content to String for large data bytes java I have a big String content, compressed as GZIP and stored as BLOB in database. While extracting from DB, I am able to retrieve the string out of it as:
        try (
             ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             BufferedInputStream bufis = new BufferedInputStream(new GZIPInputStream(bis));
             ByteArrayOutputStream bos = new ByteArrayOutputStream()
        ) {
            byte[] buf = new byte[4096];
            int len;
            while ((len = bufis.read(buf)) > 0) {
                bos.write(buf, 0, len);
            }
            retval = bos.toString();
        }

My problem here is for some input records, I have this BLOB too big, and I have to grep hardly 5-6 lines from BLOB. And I have to process these records in bulk which is shooting up memory footprints.
Is there a way to extract content from GZIP in chunks, and I can discard all leftover chunks if I get those lines in initial parts only.
Thanks for the help in advance.

A: Don't read all the bytes from the BLOB into memory at once.  Read your BLOB as an InputStream.
Use a BufferedReader to read and check one line at a time.
A BufferedReader wraps another Reader.  To translate your decompressing InputStream into a Reader, use InputStreamReader.  It is very important that you specify the charset of the text you're decompressing;  you do not want to rely on the default charset of whatever computer you happen to be running on, since it could be different depending on where you run it.
So it would look something like this:
List<String> matchingLines = new ArrayList<>();
String targetToMatch = "pankaj";

try (BufferedReader lines = new BufferedReader(
        new InputStreamReader(
            new GZIPInputStream(
                blob.getBinaryStream()),
            StandardCharsets.UTF_8))) {

    String line;
    while ((line = lines.readLine()) != null) {
        if (line.contains(targetToMatch)) {
            matchingLines.add(line);
        }
    }
}

Since you mention grep, you can also use a regular expression to match lines, though I would prefer String.contains over a regular expression for performance reasons, unless you really need a regular expression.
List<String> matchingLines = new ArrayList<>();
Matcher matcher = Pattern.comple("(?i)pankaj.*ar").matcher("");

try (BufferedReader lines = new BufferedReader(
        new InputStreamReader(
            new GZIPInputStream(
                blob.getBinaryStream()),
            StandardCharsets.UTF_8))) {

    String line;
    while ((line = lines.readLine()) != null) {
        if (matcher.reset(line).find()) {
            matchingLines.add(line);
        }
    }
}


text:
Q: Issue using custom insert media for plugin - Wordpress I have this sample code I am using to insert media as attachments for custom made orders.  I downloaded a Role Plugin which allowed me to be able to see Media but I don't want to see media of another user so I had a question about how to show only media I uploaded or this user uploaded.  But back to the main question.  This is the code I am using to open the media upload window once a button is clicked:
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id
var set_to_post_id = 10; // Set this

  $('.upload_image_button').on('click', function( event ){

    event.preventDefault();

    // If the media frame already exists, reopen it.
    if ( file_frame ) {
      // Set the post ID to what we want
      file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
      // Open frame
      file_frame.open();
      return;
    } else {
      // Set the wp.media post id so the uploader grabs the ID we want when initialised
      wp.media.model.settings.post.id = set_to_post_id;
    }

    // Create the media frame.
    file_frame = wp.media.frames.file_frame = wp.media({
      title: jQuery( this ).data( 'uploader_title' ),
      button: {
        text: jQuery( this ).data( 'uploader_button_text' ),
      },
      multiple: true  // Set to true to allow multiple files to be selected
    });

    file_frame.on( 'select', function() {

        var selection = file_frame.state().get('selection');

        selection.map( function( attachment ) {

          attachment = attachment.toJSON();

          // Do something with attachment.id and/or attachment.url here
        });
     });

    // Finally, open the modal
    file_frame.open();
  });

  // Restore the main ID when the add media button is pressed
  jQuery('a.add_media').on('click', function() {
    wp.media.model.settings.post.id = wp_media_post_id;
  });

Now the issue here is, once I upload an image.  I just get an error returned which states An error occurred in the upload. Please try again later.  That is it.  I am not sure why I would be getting this error?
Source code I got was from http://mikejolley.com/2012/12/using-the-new-wordpress-3-5-media-uploader-in-plugins/
Suggestions, thoughts?

A: you could try something in php....mess with this i cant remember the filenames offhand...
function filter_media_files( $wp_query_obj ) {

     global $pagenow;
     global $current_user;

    if( !is_a( $current_user, 'WP_User') ) // users not admins
       return;

    if( 'upload.php' == $pagenow && 'media-upload.php' == $pagenow) {
       $wp_query_obj->set('author', $current_user->id );
    } else {
       return;
    }

return;
}

add_action('pre_get_posts', 'filter_media_files');


text:
Q: Unable to switch to second frame in a window using SwitchTo() When trying to Switch to the seconf frame packageFrame, getting the following exception.
Exception in thread "main" org.openqa.selenium.NoSuchFrameException: No frame element found by name or id packageFrame is displayed.
Please find my code below,
System.setProperty("webdriver.chrome.driver", "E://MyEclipse//jars//chromedriver//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://demo.guru99.com/selenium/deprecated.html");

driver.switchTo().frame("classFrame");
driver.findElement(By.linkText("Deprecated")).click();

driver.switchTo().frame("packageFrame");
driver.findElement(By.xpath("//*[contains(text(),'AbstractWebDriverEventListener')]")).click();

A: You can use driver.switchTo().defaultContent() method before switching to second frame as given below.
//launch browser
System.setProperty("webdriver.chrome.driver", "E://MyEclipse//jars//chromedriver//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://demo.guru99.com/selenium/deprecated.html");

driver.switchTo().frame("classFrame"); //switching to frame 1
driver.findElement(By.linkText("Deprecated")).click();
driver.switchTo().defaultContent(; //swithc to parent window

driver.switchTo().frame("packageFrame");//switching to frame 2
driver.findElement(By.xpath("//*[contains(text(),'AbstractWebDriverEventListener')]")).click();

This may works for you.

A: First come to parent frame and then go to second frame
//Switch to parent window
driver.switchTo().defaultContent();

//switching to frame 2 i.e. packageFrame

driver.switchTo().frame("packageFrame");
//locate AbstractWebDriverEventListener and click
driver.findElement(By.xpath("//[contains(text(),'AbstractWebDriverEventListener')]")).click();

A: Focusing to frame is based of the DOM structure.
1. This code is used to focus to parent frame. Which means the driver instance moves the focus from current frame to patent frame.
 WebDriver.switchTo().parentFrame();

2. This code is used to focus to root(about the root frame). Which means the driver instance moves the focus from current frame to out of the all frames.
 WebDriver.switchTo().defaultContent();

3. This code is used to focus to child frames. Which means the driver instance moves the focus from current frame to child frames.
Here you can pass parameter as frame name, frame id, frame element and index.
if index is 0, then it is first child frame.
 WebDriver.switchTo().frame(parameter);

Note: If u want to focus sibling frames, first you have to focus to parent frame and then only possible to focus next.


text:
Q: In Spring Boot what is the difference between CrudRepository and JpaRepository in extending a Java repository interface when building respositories in spring, in my repository interface i extend it using the below
extends CrudRepository<EntityName, EntityType> where EntityName is the name of my Entity Class and EntityType is set to default type Long  see sample code below
@Repository
public interface RoomRepository extends CrudRepository<Room, Long> {
}

I have noticed however the use of JpaRepository see example below
public interface RoomRepository extends JpaRepository<Room, UUID>{

    public Boolean existsRoom(String roomNumber);

}

A:
JpaRepository extends PagingAndSortingRepository which in turn extends CrudRepository.

*

*CrudRepository mainly provides CRUD functions.

*PagingAndSortingRepository provides methods to do pagination and sorting
records.

*JpaRepository provides some JPA-related methods such as flushing the persistence context and deleting records in a batch.

Because of the inheritance mentioned above, JpaRepository will have all the functions of CrudRepository and PagingAndSortingRepository.
So if you don't need the repository to have the functions provided by JpaRepository and PagingAndSortingRepository, use CrudRepository.
Reference:
https://www.javatpoint.com/spring-boot-crud-operations#:~:text=CrudRepository%20does%20not%20provide%20any,works%20as%20a%20marker%20interface.


text:
Q: Is there a tool to convert i18n yaml files to gettext po format? I'd like to convert rails i18n yaml files to gettext po format. I tried https://github.com/pejuko/i18n-translators-tools but it doesn't worked as expected in my case. Any suggestion?

A: Don't know if this helps, but it showed up in a quick search:
https://github.com/pejuko/i18n-translators-tools:

This package brings you useful utility and library which can help you to handle locale files and translations in your Ruby projects. It is build upon i18n library and extends it's simple format so you can simply track field changes or keep translator's notes. Conversion back to simple format is possible and as simple as call 'i18n-translate strip'. Offers also built-in simple console editor.

And from the documentation:

Simple conversion from one file format to another:
i18n-translate cze.yml cze.po
i18n-translate cze.po cze.properties

A: See http://github.com/unho/yaml2po for one solution that works for me (after working around one bug, so check its Issues page on github)


text:
Q: How to choose columns from a query and display in datagrid I want to choose columns from a query with using the checkbox and Display in datagrid . In the following figure is an overview of the program :
App screenshot
and with this code for search :
Database1Entities DBE = new Database1Entities();
var search = from c in DBE.Tbl_PersonalInformation
                     where
                     string.IsNullOrEmpty(textBoxFirstName.Text) || (textBoxFirstName.Text) == (c.First_Name)
                     &&
                     string.IsNullOrEmpty(textBoxLastName.Text) || (textBoxLastName.Text) == (c.Last_Name)
                     select new { c.First_Name, c.Last_Name };
        dataGrid.ItemsSource = search.ToList();

I would, for example if checkBoxFirstName.IsChecked==true and checkBoxLastName.IsChecked==false only FirstName  be displayed on the datagrid .

A: you could pass a filter method
public object FilterMethod(Person person)
{
var condition = false; // checkBoxFirstName.IsChecked==true
if (condition)
    return new {person.Name};
else
    return new { person.Name, person.SurName};
}

and use it in the select line
    select FilterMethod(c);

A: I am assuming from your screenshot you are using WinForms and not WPF.
You can use:this.yourGridView.Columns["First_Name"].Visible =  checkBoxFirstName.IsChecked==true;

To set the the visibility of the First_Name column.
see https://msdn.microsoft.com/en-us/library/0c24a0d7(v=vs.110).aspx


text:
Q: Run PSQL command from bash script I would like to know how to run \du within a script, and output that to a file.
Something like the following:
# some_script.sh

psql <database connection> & \du > output_of_du.txt

I can find information about running .sql files via psql, but I can't find information about running psql commands themselves.
I found the following whilst searching:

*

*https://stackoverflow.com/questions/35347368/unable-to-run-psql-command-from-within-a-bash-script - about running SQL not a PSQL command

*https://stackoverflow.com/questions/54619776/cannot-get-psql-command-to-run-in-bash-script - seems to be about running a .sql script

But they're not what I'm after.

A: You can use the -c flag and combine it with -L to gather the output:
psql <database connection> -c \du -L output_of_du.txt

See psql-tip number 1 (https://psql-tips.org/psql_tips_all.html#tip001) and psql-tip number 26 (https://psql-tips.org/psql_tips_all.html#tip026)


text:
Q: C# utf string conversion, characters which don't display correctly get converted to "unknown character" - how to prevent this? I've got two strings which are derived from Windows filenames, which contain unicode characters that do not display correctly in Windows (they show just the square box "unknown character" instead of the correct character). However the filenames are valid and these files exist without problems in the operating system, which means I need to be able to deal with them correctly and accurately.
I'm loading the filenames the usual way:
string path = @"c:\folder";
foreach (FileInfo file in DirectoryInfo.EnumerateFiles(path))
{
    string filename = file.FullName;
}

but for the purposes of explaining this problem, these are the two filenames I'm having issues with:
string filename1 = "\ude18.txt";
string filename2 = "\udca6.txt";

Two strings, two filenames with a single unicode character plus an extension, both different. This so far is fine, I can read and write these files no problem, however I need to store these strings in a sqlite db and later retrieve them. Every attempt I make to do so results in both of these characters being changed to the "unknown character", so the original data is lost and I can no longer differentiate the two strings. At first I thought this was an sqlite issue, and I've made sure my db is in UTF16, but it turns out it's the conversion in c# to UTF16 that is causing the problem.
If I ignore sqlite entirely, and simply try to manually convert these strings to UTF16 (or to any other encoding), these characters are converted to the "unknown character" and the original data is lost. If I do this:
System.Text.Encoding enc = System.Text.Encoding.Unicode;
string filename1 = "\ude18.txt";
string filename2 = "\udca6.txt";
byte[] name1Bytes = enc.GetBytes(filename1);
byte[] name2Bytes = enc.GetBytes(filename2);

and I then inspect the bytearrays 'name1Bytes' and 'name2Bytes' they are both identical. and I can see that the unicode character in both cases has been converted to a pair of bytes 253 and 255 - the unknown character. and sure enough when I convert back
string newFilename1 = enc.GetString(name1Bytes);
string newFilename2 = enc.GetString(name2Bytes);

the orignal unicode character in each case is lost, and replaced with a diamond question mark symbol. I have lost the original filenames altogether.
It seems that these encoding conversions rely on the system font being able to display the characters, and this is a problem as these strings already exist as filenames, and changing the filenames isn't an option. I need to preserve this data somehow when sending it to sqlite, and when it's sent to sqlite it will go through a conversion process to UTF16, and it's this conversion that I need it to survive without losing data.

A: If you cast a char to an int, you get the numeric value, bypassing the Unicode conversion mechanism:
foreach (char ch in filename1)
{
    int i = ch; // 0x0000de18 == 56856 for the first char in filename1
    ... do whatever, e.g., create an int array, store it as base64
}

This turns out to work as well, and is perhaps more elegant:
foreach (int ch in filename1)
{
    ...
}

So perhaps something like this:
string Encode(string raw)
{
    byte[] bytes = new byte[2 * raw.Length];
    int i = 0;
    foreach (int ch in raw)
    {
        bytes[i++] = (byte)(ch & 0xff);
        bytes[i++] = (byte)(ch >> 8);
    }

    return Convert.ToBase64String(bytes);
}

string Decode(string encoded)
{
    byte[] bytes = Convert.FromBase64String(encoded);
    char[] chars = new char[bytes.Length / 2];
    for (int i = 0; i < chars.Length; ++i)
    {
        chars[i] = (char)(bytes[i * 2] | (bytes[i * 2 + 1] << 8));
    }

    return new string(chars);
}