text:
Q: Как сделать "обертку" на php для занесения блока html кода в переменную? Шаблон декоратор позволяет нам обернуть что-то.
У меня возник такой вопрос.
А есть ли решение (паттерн, подход) для того, чтобы загнать в переменную код страницы, который находится между некими "маркерами"?
Т.е. по сути повторить функционал Heredoc синтаксиса, но не встроенным средством в php.
Что-то хочется такого плана (желательно без ООП, но можно и предложить небольшое ООП решение):
beginBlock($variable);

Example...

<?= $needCount ? $object->countRows : '' ?>

...
endBlock($variable);

Только не спрашивайте "А зачем?". Бывает нужно. Например, когда внутри html блока сложные вычисления, а движек старый и реализован функциональным программированием (без ООП). Почему не подходит Heredoc? Бывает не устраивает(дает некий дискомфорт) из-за некоторых IDE или по другим причинам.
Еще раз - не надо пытаться меня сделать хорошим кодером. Я прекрасно использую в жизни ООП. Есть просто вопрос - нужен просто ответ. Без философии.
Даже если незачем - просто интересно знать.
Если есть подобные решения - намекните ссылкой или примером.
Заранее спасибо!

A: ob_start();

Тут любой код PHP, осуществляющий какой-то вывод

$variable = ob_get_clean();

Функции контроля вывода
sandbox

A: function foo(){
    ?>
        bar
    <?
}
foo();

Крайне нерекомендуемый метод, однако. Можно хранить темплейты в тех же XML, и разворачивать функцией на php в html. А "бывает нужно" - когда "не хочется делать нормально". Это с треском подойдет даже для разовых решений проблем, ибо существенно, просто в разы, ухудшает читаемость кода, умножает на ноль его гибкость и функциональность, изобилует закрывающими/открывающими тегами php, и вообще моветон.


text:
Q: Roboto font rendering poorly in new-look Gmail (Mac) The new-look Gmail has just been released and it replaces Arial in its UI with Roboto throughout. Roboto renders fine in other apps (Drive, e.g.) but in the new Gmail (both Chrome and Safari) the font rendering is blurry, with varying thicknesses, inconsistent kerning and poor anti-aliasing.
For example:

or:

Look at the differences between the vertical strokes of the R and the E in the word REMOTE. The font is heavily anti-aliased but not consistently. The default font size has also dropped and this, combined with the blurriness, has impacted the readability.
I'm using all the defaults for Gmail, Chrome. I've double-checked I don't have the Roboto font installed on my machine. I have tried installed Roboto (via Google's SkyFonts), though this had no effect. Font now uninstalled.
Would anyone know how I can diagnose this and understand why the font is rendering poorly?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the use of strictfp modifier and synchronized keyword in main method of java public static synchronized strictfp void main(String... arg)

In the above statement, can someone please explain the purpose of synchronized and strictfp for main method.

A: Few good explanation for java synchronized is given here - what-does-synchronized-mean and learning-java-use-of-synchronized-keyword
Now, if main method is synchronized, only one thread can enter into this method, which is the java main thread (assuming that the class is executed as main class).
For executing this method, the main thread will acquire the class level lock (being a static method). So, if the class is having more static synchronized methods, those will be blocked forever for other thread, until main thread completes the execution or go into wait state.
strictfp is Java is explained when-should-i-use-the-strictfp-keyword-in-java and strictfp-in-java
It does not have any different behavior with main().


text:
Q: HTML KnockoutJS intellisense in Visual Studio Code Using Visual Studio Code I want to enable HTML KnockoutJS intellisense, based on a binding. There's a snag as I use TypeScript (TS) and bind the model in code:
ko.applyBindings(myViewModel);

All TS files are generated and rendered into app.js
I want a similar functionality found here.
https://johnpapa.net/knockout-intellisense-in-visual-studio-2012/

NB: I'm using debug version of KnockoutJS

A: EDIT

Just noticed one thing after writing the answer, you are applying binding correctly but after that missing object name before function name, here what is difference here:
For Example,
Adding binding:
ko.applyBindings(seViewModel, document.getElementById("Div"));

Using binding :

                                                                            <input type="radio" group="implementationModelGroup" class="implementationModelCheck" data-bind="value: ImplementationModelId, click: seViewModel.ImplementationModelCheckBoxClick.bind($data), checked:seViewModel.ImplementationModelCheckedValue()" />

Here if I don't use viewmodel name seViewModel autocomplete doesn't work

Not sure about why it is not working for you, I opened an old project in VS code & it was already working. It is not only giving autocomplete for KO object but also for my viewmodel & controller action methods in C# class, I am adding a screenshot for reference

I am adding my current project setting & vs extensions, it might help you.
VS CODE Details :
Version: 1.26.1
Commit: 493869ee8e8a846b0855873886fc79d480d342de
Date: 2018-08-16T18:38:57.434Z
Electron: 2.0.5
Chrome: 61.0.3163.100
Node.js: 8.9.3
V8: 6.1.534.41
Architecture: x64

Extensions :

Which KO files I have added:
 <Content Include="Scripts\libs\knockout-3.4.0.js" />
 <Content Include="Scripts\libs\knockout.mapping-latest.js" />
 <Content Include="Scripts\libs\knockout.validation.min.js" />

It is ASP.NET MVC project, KO is used for model-attribute binding.


text:
Q: Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY android I'm fairly new to JSON parsing , I'm using the GJson library  and ran into this problem.
I'm trying to parse this JSON reponse:
This is a my model class:
public class JsonModel {
    public int posterId ;
    public String title ;
    public String descraption ;
    public String category ;
    public String director ;
    public String written ;
    public String stars ;
    public String georgia_time ;
    public String wold_time ;
    public String ipone_5 ;
    public String ipone_5_blur ;
    public String ipone_4 ;
    public String ipone_4_blur ;
    public String youtube ;
    public String MovieFbID ;
    public String imdb ;
    public Cinemas cinemas ;
}

class Cinemas{

    public List <Cinema> Cinemaname;
}

class Cinema{

    public String cinemaName ;
    public List<info> info ;
}

class info{

    public String time;
    public String hole ;
    public String start_time ;
    public String end_time ;
}

And i deserialize my json like this
try {

            Gson gson = new Gson();

            JsonModel[] res1 = gson.fromJson(SpleshScreen.my_json, JsonModel[].class);

            JsonModel jsonModel = new JsonModel();

            for (int i = 0; i < res1.length; i++) {

                ServerItems objItem = new ServerItems();
                objItem.setImage(imageurl+jsonModel.ipone_4);

                Log.e("imageee", objItem.getImage());
                arrayOfList.add(objItem);

            }

I have a error in last line a my code
this is a my logcat error

A: As you can see, the first character of the json is [. This is the character for the start of an array. When you deserialize the json, you tell Gson you want to get an object, while what Gson finds is an array. So what you want to change in your code is this:
JsonModel[] res1 = gson.fromJson(SpleshScreen.my_json, JsonModel[].class);

After that you can get the first one like this:
JsonModel jsonModel = res1[0];

A: Try this code:
res1 = gson.fromJson(SpleshScreen.my_json, JsonModel[].class);


text:
Q: Oracle regexp_substr to get first portion of a string I am stuck here. I am using oracle and I want to get the first part of a string before the first appearance of '|'. This is my query but it returns the last part i.e 25.0. I want it to return first part i.e 53. How do I achieve that?
select regexp_substr('53|100382951130|25.0', '[^|]+$',  1,1) as part1 from dual

A: Assuming you always have at least one occurrence of '|', you can use the following, with no regexp:
with test(string) as ( select '53|100382951130|25.0' from dual)
select substr(string, 1, instr(string, '|')-1)
from test

You could even use regexp to achieve the same thing, or even handle the case in which you have no '|':
with test(string) as (
    select '53|100382951130|25.0' from dual union all
    select '1234567' from dual)
select string,
       substr(string, 1, instr(string, '|')-1),
       regexp_substr(string, '[^|]*')
from test

You can even handle the case with no occurrence of '|' without regexp:
with test(string) as (
    select '53|100382951130|25.0' from dual union all
    select '1234567' from dual)
select string,
       substr(string, 1, instr(string, '|')-1),
       regexp_substr(string, '[^|]*'),
       substr(string, 1,
                         case
                           when instr(string, '|') = 0
                             then length(string)
                           else
                             instr(string, '|')-1
                         end
             )
from test


text:
Q: Which is more better between basic auth and token auth as security perspective I am currently developing a RESTful API server, and I am choosing between using ID and password or using a token to authenticate a user.
Let me, explain my situation first. I need to include static authentication information to my library to communicate between a client and my server or provide it to a partnership company to communicate between their server and my server. And when I was researching other services which are in a similar situation as us, they are using token now (for example, Bugfender is using a token to specify a user).
However, what I think is that using ID and PW and using the token are the same or using ID and PW is better because there are two factors to compare it is correct or incorrect.
Is there any reason why other services are using a token?
Which one is better as a security perspective or is there a better way to do this?

A: I think, if you are going go use on your client fixed username/password, or some fixed token, then the level of the security is the same.
Username and password is not considered as multi-factor authentication. Multi factor means that you are authenticating someone by more than one of the factors:

*

*What you know. This can be the combination of username and password, or some special token.

*What you have. Might be some hardware that generates an additional one time password - Google authenticator app on your telephone, or SMS with OTP received with some time expiration.

*What you are. This is for example your fingerprint or retina of the eye.

*Where you are. This can be the IP address of the origin if it is applicable for your setup.

*How you behave. What is your normal way of using the service.

etc.
Maybe not needed to mention that both - the token and the username/password combination have to be carried in an encrypted requests (I believe you are using HTTPS). Otherwise the client's identity can be stolen.
How are you going to provide the credentials to your client library? I thnk this is the most tricky part. If those credentials are saved as a configuration (or worse hard coded) on their server, is that storage secure enough? Who is going to have access to it. Can you avoid it?
What would happen if your partner company realize that the username/password is compromised? Can they change it easily themselves? Or how fast you can revoke the permissions of stolen credentials?
My advice is also to keep audit logs on your server, recording the activity of the client requests. Remember also the GDPR if you work with Europe servers, check for similar regulations in your country based on what you are going to audit log.

A: In case the credentials (ID and password) and the token are being transferred the same way (say: by a header in a REST request) over a TLS secured channel, the only difference lies in the entropy of the password VS entropy of the token. Since it is something for you to decide in both cases, there is no real difference from the security perspective.
NOTE: I don't count the ID as a secret, as it usually is something far easier to guess than a secret should be.
I'd go for a solution that is easier to implement and manage.
IMHO this would be HTTP basic authentication, as you usually get full support from your framework/web server with little danger of making security mistakes in authentication logic. You know, friends don't let friends write their own auth. ;)


text:
Q: Missing port when starting Rails with Foreman I am new to RoR and I am trying to install specific project. My OS is Ubuntu 14.04 and I trying to run the project from terminal. I have already installed all needed gems following project's specifications.
Issue
When I run this command which is trying to run the project
foreman start -f Procfile.dev

It gives me the following error
17:01:33 web.1    | started with pid 4538
17:01:33 worker.1 | started with pid 4540
17:01:34 web.1    | /home/user/.rvm/gems/ruby-2.1.3/gems/railties-4.0.9/lib/rails/commands/server.rb:33:in `parse!': missing argument: --port (OptionParser::MissingArgument)
17:01:34 web.1    |     from /home/user/.rvm/gems/ruby-2.1.3/gems/rack-1.5.2/lib/rack/server.rb:293:in `parse_options'
17:01:34 web.1    |     from /home/user/.rvm/gems/ruby-2.1.3/gems/rack-1.5.2/lib/rack/server.rb:184:in `options'
17:01:34 web.1    |     from /home/user/.rvm/gems/ruby-2.1.3/gems/railties-4.0.9/lib/rails/commands/server.rb:58:in `set_environment'
17:01:34 web.1    |     from /home/user/.rvm/gems/ruby-2.1.3/gems/railties-4.0.9/lib/rails/commands/server.rb:42:in `initialize'
17:01:34 web.1    |     from /home/user/.rvm/gems/ruby-2.1.3/gems/railties-4.0.9/lib/rails/commands.rb:71:in `new'
17:01:34 web.1    |     from /home/user/.rvm/gems/ruby-2.1.3/gems/railties-4.0.9/lib/rails/commands.rb:71:in `<top (required)>'
17:01:34 web.1    |     from bin/rails:4:in `require'
17:01:34 web.1    |     from bin/rails:4:in `<main>'
17:01:34 web.1    | exited with code 1
17:01:34 system   | sending SIGTERM to all processes
17:01:34 worker.1 | terminated by SIGTERM

This is what I have in Procfile.dev:
web: bundle exec rails s --port $DEV_PORT
worker: bundle exec rake jobs:work
# exec: lt --port $DEV_PORT --subdomain $SUBDOMAIN

Could you please tell me how to solve this problem?

A: Foreman sets up an environment variable called $PORT, not $DEV_PORT. Unless you've set up $DEV_PORT yourself (which won't work if you need to deploy somewhere like Heroku), you're explicitly starting your processes with an empty port. Change your Procfile to use $PORT and you should be good to go.


text:
Q: Connecting to resource on vpn, while normal traffic routes through normal connection I'm running Windows 7 and am trying to connect to a specific IP on a VPN network that I'm connected to.
Since I don't want all Internet traffic to go through the VPN connection and I want to be able to run a server on my normal IP, I have unchecked the "Use default gateway" option on the VPN connection.
However I am now unable to reach any IP on my VPN network. After searching Google I found that this could perhaps be solved with persistent routes, but my attempts at trying this didn't work.
Any ideas how I can achieve this?

A: Open up the Network Connections view via control panel/network and sharing centre, right click on the VPN connection, and select Properties. Then go to the Network tab, and select IPv4, and then Properties. Then click the Advanced button, and untick Automatic Metric. Enter in a fairly large number (I use 9000), and then OK your way out of all the dialogs (you may want to do the same with IPv6 if your VPN supports it).
Here's a screenshot from my desktop PC with VPN:

The Metric value determines the order in which Windows tries networks in order to access a resource. Normally on automatic, Windows tries to use the connection with the fastest connection speed, but this can sometimes be wrong (eg wireless N being used instead of 100Mbit lan, or VPNs getting prioritised when they shouldn't). Setting the higher value means the connection is less favoured, and Windows will only try and use it when you request resources (remote LAN IP addresses) that can't be resolved by other connections.


text:
Q: How to get timestamp in kwargs like run_id in Airflow? As we get run_id in Airflow, how to get timestamp(ts)?

A: First:
In your task set provide_context=True
bye_operator = PythonOperator(
  task_id='bye_task',
  python_callable=print_goodbye,
  provide_context=True,
  dag=dag
)

Second:
Ensure you are passing the known arguments into your callback function:
def print_goodbye(**kwargs):
    ts = kwargs.get('ts', None)
    print(ts)
    return 'Good bye world!'


text:
Q: XPointers in SVG I've been trying to get XPointer URIs working in an SVG file, but haven't had any luck so far. After trying something more complicated and failing, I simplified it down to just referencing an ID. However, this still fails.
The spec seems pretty clear about this implementation:
http://www.w3.org/TR/SVG/struct.html#URIReference
I found an example online of what should be a working XPointer reference within an svg document. Here is the Original. Here is the version I copied out:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="500" height="200" version="1.1"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink">

    <defs>
        <rect id="simpleRect" width="100px" height="75px"/>
    </defs>
    <use xlink:href="#simpleRect"
        x="50" y="50" style="fill:red"/>
    <use xlink:href="#xpointer(id('simpleRect'))"
        x="250" y="50" style="fill:yellow"/>
</svg>

This should display two rectangles... one red and one yellow. I tried rendering with Firefox 3.6 and Inkscape 0.47. No success. Only the Red rectangle shows.
What am I missing?
Thanks for any help you can offer

A: There is currently (as of 10 March 2016, SVG 1.1 Second Edition) no support for rendering XPointers in browsers. W3Schools writes about this as follows:

XPointer Browser Support
There is no browser support for XPointer. But XPointer is used in other XML languages.

It's kind of frustrating, because all the official documentation does not bother to distinguish between browser-supported (Internet ready) features of SVG and the technically-supported, purely XML-like features of SVG.

A: From the linking section of the spec:
<URI-reference> = [ <absoluteURI> | <relativeURI> ] [ "#" <elementID> ]    -or-
<URI-reference> = [ <absoluteURI> | <relativeURI> ] [ "#xpointer(id(" <elementID> "))" ]

So what is the benefit of using xpointer syntax? All svg implementions I've seen have supported the alternative (shorter) syntax shown above (#myId). The xpointer syntax seems to be less well supported.


text:
Q: $$LAST_EXTRACT_DATE not in parameter file in informatica mapping - when run through DAC I have created a new mapping in Informatica and I defined a mapping parameter $$LAST_EXTRACT_DATE (this is already defined in DAC(as it is working for out of box mappings)). However, When DAC is executing, this variable is not getting its values in parameter file of mapping. Other mappings are working fine. It's just this mapping which has an issue. I am trying to make this mapping to run in incremental.
Any suggestions please?

A: Yogesh,
I assumed that your mapping run with no issue and parameter $$LAST_EXTRACT_DATE are being replaced with a correct date through the DAC. You don't parameter file if you using DAC to run mapping. A parameter file is needed when you start the task from Informatica.

A: Make sure that the same file is used while running through DAC, as it's possible to run workflows in two ways:

*

*just starting a workflow will make it read parameter file specified in the properties

*starting workflow with indicated parameter file will make it read the given file INSTEAD OF the one specified in the properties.


text:
Q: Bootstrap popover element access I want to display placeholder in the input text box in IE9, the following code is working fine but it is not working in the Bootstrap popover text box.
<script>
 jQuery(function() {
    jQuery.support.placeholder = false;
    test = document.createElement('input');
    if('placeholder' in test) jQuery.support.placeholder = true;
    });

    // Placeholder for IE
    $(function() {
        if(!$.support.placeholder) {

            var active = document.activeElement;
            $(':text, textarea, input[type="password"]').focus(function () {
                if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
                    $(this).val('').removeClass('hasPlaceholder');
                }
            }).blur(function () {
                if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
                    $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
                }
            });
            $(':text, textarea, input[type="password"],input[type="password"]').blur();
            $(active).focus();
            $('form').submit(function () {
                $(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
            });
        }

    });
</script>


text:
Q: KivyMD- KivyCamera class is initializing without being called This is my first time asking a question here so please bear with me. I'm trying to make a Camera App using opencv and kivy. I managed to do it but my problem is that the camera is being called right away even if its not on the right screen. I suspect this is because of my init class in KivyCamera, but I dont know any other methods to do it. What I want is that the camera will only initialize after pressing a button.
here's my main app
from kivy.lang import Builder

from kivymd.app import MDApp
from kivymd.uix.list import OneLineIconListItem, IconLeftWidget
from kivymd.uix.list import OneLineListItem, MDList
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.scrollview import ScrollView
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2

import random
import string

class OneLine(OneLineListItem):
    pass

class Scr(ScrollView):
    pass

class list(MDList):
    pass

class MenuScreen(Screen):
    pass

class CamScreen(Screen):
    # def show_cam(self):
    #     self.capture = cv2.VideoCapture(0)

    def on_stop(self):
        self.capture.release()

class SecondScreen(Screen):
    # def mama(self):
    #     for i in range(20):
    #         self.parent.parent.ids.container.add_widget(
    #             OneLineListItem(text=f"Single-line item {i}")
    #         )
    def on_released(self):
        # items=
        # self.add_widget()

        for i in range(20):
            list = OneLine(text=f"dsafsd {i}", on_release= lambda list: print(list.text))
            list.text = f"dsafsd {i}"
            # list.bind(on_release=lambda btn: self.dropdown.select(list.text))
            self.ids['container'].add_widget(list)

    # pass
class KivyCamera(Image):
    def __init__(self, capture = cv2.VideoCapture(0), fps=30, **kwargs):
        super(KivyCamera, self).__init__(**kwargs)
        self.capture = capture
        Clock.schedule_interval(self.update, 1.0/fps)

    def update(self, dt):
        ret, frame = self.capture.read()
        if ret:
            buf1 = cv2.flip(frame, 0)
            buf = buf1.tostring()
            image_texture =Texture.create(
                size = (frame.shape[1], frame.shape[0]), colorfmt='bgr'
            )
            image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')

            self.texture = image_texture

sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SecondScreen(name='second'))
sm.add_widget(CamScreen(name='cam'))

class Test(MDApp):

    def on_start(self):
        size= 0.5,0.5
        # self.help.get_screen('cam').ids['cam'].add_widget(KivyCamera(size_hint = size, pos_hint = {"x":0.1,"top":1}))
        for i in range(20):
            self.help.get_screen('second').ids['container'].add_widget(
                OneLineListItem(text=f"Single-line item {i}")
            )

    letters = string.ascii_lowercase
    random = random.choice(letters)

    def build(self):
        screen = Screen()
        self.help = Builder.load_file('tes.kv')
        screen.add_widget(self.help)
        return screen

Test().run()

and here's the kv file
ScreenManager:
    MenuScreen:
    SecondScreen:
    CamScreen:

<MenuScreen>:
    name: 'menu'
    MDRectangleFlatButton:
        text: 'to second'
        pos_hint: {'center_x':0.1,'center_y':0.2}
        on_press:
            root.manager.current = 'second'

    MDRectangleFlatButton:
        text: 'to cam'
        pos_hint: {'center_x':0.1,'center_y':0.9}
        on_press:
            root.manager.current = 'cam'
    MDLabel:
        id:our_label
        text: " "
        pos_hint: {'center_x':0.5,'center_y':0.2}
        # on_parent:
        #     app.samie()

<SecondScreen>:
    name: 'second'
    MDBoxLayout:
        orientaion: 'vertical'
        MDRectangleFlatButton:
            text: 'to menu'
            pos_hint: {'center_x':0.1,'center_y':0.95}
            on_press:
                root.manager.current = 'menu'

            # on_press:
            #     app.please()
                # ScrollView:
                # root.on_released()
                # list.text = list.text + "bobo"
                # root.manager.current = 'menu'
                # for i in range(4): print(f"bobo {i}")

        ScrollView:
            MDList:
                id:container
                # on_parent:
                #     app.please()

<CamScreen>:
    name: 'cam'
    BoxLayout:
        orientation: 'vertical'

        KivyCamera:
            id: cam
            size_hint: 0.5,0.5
            pos_hint: {"x":0.1,"top":1}

        MDRectangleFlatButton:
            text: 'show camera'
            pos_hint: {'center_x':0.1,'center_y':0.9}
            # on_parent:
            #     app.show_cam()

Thanks! I really think I just need to get rid of init but I dont know any alternative way

A: You can trigger the camera update using the on_enter() method of Screen. Try changing the __init__() method of KivyCamera to:
class KivyCamera(Image):
    def __init__(self, capture=cv2.VideoCapture(0), fps=30, **kwargs):
        super(KivyCamera, self).__init__(**kwargs)
        self.capture = capture
        self.fps = fps
        # Clock.schedule_interval(self.update, 1.0 / fps)

And add on_enter() and on_leave() methods to CamScreen:
class CamScreen(Screen):
    # def show_cam(self):
    #     self.capture = cv2.VideoCapture(0)

    def on_stop(self):
        self.capture.release()

    def on_enter(self, *args):
        cam = self.ids.cam
        self.clock_event = Clock.schedule_interval(cam.update, 1.0 / cam.fps)

    def on_leave(self, *args):
        self.clock_event.cancel()

On an unrelated note, the lines:
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SecondScreen(name='second'))
sm.add_widget(CamScreen(name='cam'))

are building the root of your App, but it is never used. Those lines can be eliminated.
The line:
self.help = Builder.load_file('tes.kv')

is also building the same root, and unless there is some reason for creating another Screen to contain that root, you can simplify your build() method to:
def build(self):
    self.help = Builder.load_file('tes.kv')
    return self.help

A:     def __init__(self, capture = cv2.VideoCapture(0), fps=30, **kwargs):

That line causes the issue.
The VideoCapture object is constructed at the time of the definition of the class and its method.
You probably don't want that.
Use capture=None in the parameter list, and in the body of __init__ you should check if capture is None: capture = cv2.VideoCapture...


text:
Q: Hide bootstrap modal popup var webpage = require('webpage').create();
var filename = 'demo.png';
webpage.open('https://www.example.com/', function() {
webpage.render(filename);
phantom.exit();});

In the above code when the example web site loads it displays a bootstrap popup. now in phantom js i want to take a screenshot of the web page without the popup. please help me on how to hide this popup through phantomjs..

A: You need to hide/turn modal off before making a screenshot:
var page = require('webpage').create();
var filename = 'demo.png';
page.open('https://www.example.com/', function() {

    // Delay script by a second to give
    // javascript some time to load and execute modal
    setTimeout(function(){

        page.evaluate(function(){
            // You'll need to find the modal id to hide it programmatically
            $('#themodal').modal('hide');
        });

        page.render(filename);

        phantom.exit();
    },
    1000);

});

Another way is to just remove the modal window elements from DOM:
        page.evaluate(function(){
            // These classes are for Bootstrap 4
            $('.modal, modal-backdrop').remove();
        });


text:
Q: How can I inherit an inner class using an abstract base class? I'm trying to create a test class which organizes its test methods using inner classes.  I would like for this class to be abstract with the ability to set a static property so this property can be injected.  Here's an example of what I'm talking about:
[TestClass]
public abstract class BaseUnitTest
{
   public static string InjectedProperty;

   public static string GetInjectedString()
   {
      return InjectedProperty;
   }

   [TestClass]
   public class WhenFoo
   {
      [TestMethod]
      public void TestFoo()
      {
         string str = GetInjectedString();
      }
   }
}

[TestClass]
public class DeriverdUnitTest : BaseUnitTest
{
   [ClassInitialize]
   public void SetUp()
   {
      InjectedProperty = "Injected Property";
   }
}

However, I don't see a DerivedUnitTest+WhenFoo+TestFoo() class show up in my unit test view.  I'm using Visual Studio 2010.  I'm guessing when I override BaseUnitTest, I don't override its inner classes as well.  I suppose I could make its inner classes abstract and override them later, but as the complexity of my test class increases this will get really annoying.  Could somebody please explain why this is occuring and how I can fix it?
Thanks.
Edit:
I feel like I need to better explain my reasons for wanting to do this.  We'd like to implement a testing standard which is very verbose in its naming.  Therefore a test class would look something like this:
[TestClass]
public abstract class BaseUnitTest
{
   public static string InjectedProperty;

   public static string GetInjectedString()
   {
      return InjectedProperty;
   }

   [TestClass]
   public class WhenFooIsCalled
   {
      [TestClass]
      public class AndTheArgumentIsNull
      {
         [TestMethod]
         public void AnArgumentNullExceptionShouldBeThrown()
         {
            string str = GetInjectedString();
         }
      }
   }
}

The advantage of this is when you open up the test view in Visual Studio and display the method name and class name columns you get something that looks like this:
BaseUnitTest+WhenFooIsCalled+AndTheArgumentIsNull AnArgumentNullExceptionShouldBeThrown()

This makes it a lot easier to glance to tell what a failing test among a few hundred pass tests is supposed to do.
The main reason I want to be able to override the abstract BaseUnitTest is because when I do all of the tests which were contained in the BaseUnitTest are all added to the DerivedUnitTest and show up in the Test View in Visual Studio.
Thanks again.

A: In the C# language, nested classes have no special relationship with the class in which they are nested.  It is a completely different type.  There is only one good reason you'd ever do this: you can declare the class private.  Which helps you to create a little worker class to get a job done on behalf of the outer class, a class that is completely invisible from the outside.  Very useful, you cannot otherwise declare a private class at outer class scope, the best you can do is internal.
What follows is that it in no way plays a role in the inheritance of the outer class.  A class you derive from the outer has no visibility to the nested class inside the base class at all.  Which was the intention, declaring it private was the reason to nest it in the first place.
Punt: if you need that class in the derived one just declare it internal or public.

A: Nested types don't work that way. You can't "override" types.
It's not clear what you're trying to achieve here, but I don't think it's going to work.

A: You can accomplish the kind of rich, verbose, BDD-style test repriting with xUnit.NET and SubSpec. SubSpec is included in the xUnit.NET extras download these days. You can read more about SubSpec and BDD testing at the following article:
http://haacked.com/archive/2008/08/24/introducing-subspec.aspx

A: How about using a config file?  For Example
   [TestClass]
   public class WhenFoo
   {
      [TestMethod]
      public void TestFoo()
      {
         string str = ConfigurationManager.AppSettings["WhenFooTestFooString"];
      }
   }


text:
Q: Mongo DB converts '_' into a number while importing the CSV file in mongodb we have a value like 6910001_1001. When we import the CSV file it convert 6910001_1001 into 69100011001.0
How can I restrict auto datatype selection in Mongodb?


text:
Q: change stylesheet rule selector dynamically This is a simplified version of how to dynamically change a selector rule:
http://jsfiddle.net/vsync/SaQy6/
For a giver inline style:
<style type='text/css' id='myStyle'>
    ul > li{}
</style>

trying to change the selector
var styleTag = document.querySelector('#myStyle');
// the style sheet in the style tag
var sheet = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet,
    // the first rule in the style sheet
    rules = sheet.cssRules ? sheet.cssRules : sheet.rules;

rules[0].selectorText = 'ul > li:nth-child(2)';
rules[0].style.cssText = 'background:red';

Nor selectorText or cssText work to set the selector dynbamically.
Then I read on MDN that selectorText is readOnly, and I am lost as to how should I actually change the selector without having to remove the whole style element and creating a new one.
There is the option of removing the rule completely and inserting a new rule, but it's very non-standard. Any ideas?

A: Demo - http://jsfiddle.net/vsync/SaQy6/6/
cross-browser way:
var styleTag = document.querySelector('#myStyle');
// the style sheet in the style tag
var sheet = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet,
    rules = sheet.cssRules ? sheet.cssRules : sheet.rules;

if( sheet.cssRules ){
    sheet.deleteRule(0); // deletes a rule at index 0
    sheet.insertRule("ul > li:nth-child(2n){background:red}", 0);
}
else{
    sheet.removeRule(0); // deletes a rule at index 0
    sheet.addRule("ul > li:nth-child(2n)", 'background:red', 0);
}


text:
Q:  mapped incorrectly in macvim I was trying to navigate the jump list in MacVim and I noticed that <C-I> doesn't work, although it works fine in normal Vim.
In insert mode, pressing <C-V><C-I> gives <D-<89>>. <C-V><Tab> gives ^I. (In normal vim (not MacVim), doing the same yields ^[ and ^I, respectively.)
My first thought was to check if I had a mapping set.
output of :map
x  gx            <Plug>NetrwBrowseXVis
n  gx            <Plug>NetrwBrowseX
x  <Plug>NetrwBrowseXVis * :<C-U>call netrw#BrowseXVis()<CR>
n  <Plug>NetrwBrowseX * :call netrw#BrowseX(netrw#GX(),netrw#CheckIfRe
mote(netrw#GX()))<CR>

output of :map!
No mapping found.

I saw mentioned on this thread that <Tab> and <C-I> are mirrored. But I don't have a mapping for <Tab> anywhere as you can see above.
I'm stuck at this point. Help appreciated!

A: In theory, <C-v><C-i> should just produce a simple <Tab> (U+0009), definitely not <D-<89>> or <D-<anything>> for that matter.
In <D-<89>>,

*

*<D- is the notation for the Command key,

*and <89> is the notation for "Character Tabulation with Justification".

U+0089 seems vaguely related to U+0009 so that would be one thing to investigate, but the combination with the Command key is weird.
If I were you I would open an issue in MacVim's issue tracker.


text:
Q: Problem with spellchecker
Why I don't get any suggestion when I execute this query agains Solr:

q=%2B%28text%3A%28gasal%29%29&suggestField=contentOriginal&ontologySeed=gasal&spellcheck.build=true&spellcheck.q=gasal&spellcheck=true&spellcheck.collate=true&hl=true&hl.snippets=5&hl.fl=text&hl.fl=text&rows=12&start=0&qt=%2Fsuggestprobabilistic

I am searching gasal and it should suggest gasol.
Thanks in advance

A: By default, the spellchecker works by taking the indexed content of a source field (in Solr) and store into an external Lucene index. That external index is the dictionary. Each words of the source field are stored in the dictionary in a format that allows to match words that are closed to each other. When asking for suggestions, Solr will look into that dictionary, NOT into the Solr index.
So in order for the dictionary to be built, you have to specify the source field. It should be defined in your schema using an appropriate analyzer (usually no stemming). That field should contain enough words to built a good dictionary. A good practice is to populate it from your text fields using copyfield instructions.
Then, the dictionary have to be built. This is the operation where the content of the source field is taken to build the actual dictionary. It can be done automatically at each commit or manually using the "build" parameter.


text:
Q: How to administer, manage & update 40 to 50 Kubuntu laptops? I have a custom developed application presently running on about 40 Kubuntu laptops (& more planned). Every few months I have to update the application. I also have to run Ubuntu updates and a few other minor things. I've been doing it manually, one by one, using Team Viewer to log into each client. I would like to dramatically improve this process.
Can anyone suggest an approach (and tools)? This is not an enterprise, I am not a sysadmin, and I prefer a simple solution.
To update my application presently, I have to use command line tools (as root) and I have to have access to the GUI in order to run the application. Team Viewer allows me to do this.
My question is, "How can I automate the process of updating my custom application on 40+ laptops?"
I'm most familiar with bash scripts and SSH.
As far as what have I considered or investigated so far, I googled a bit and the names of Puppet & Chef came up. But I read this:

People have been advocating tools like Chef and Puppet for solving
  exactly those problems. Both of them are solid tools, but they can be
  quite daunting.

So those options are not for me.
I also heard about Sprinkle, but I'm not provisioning servers - I'm managing laptops.
I came across Cuisine next:
http://stackful-dev.com/cuisine-the-lightweight-chefpuppet-alternative.html
https://github.com/sebastien/cuisine#readme

Fabric is an incredible tool to automate administration of remote
  machines. As Fabric's functions are rather low-level, you'll probably
  quickly see a need for more high-level functions such as add/remove
  users and groups, install/upgrade packages, etc.
Cuisine is a small set of functions that sit on top of Fabric, to
  abstract common administration operations such as file/dir operations,
  user/group creation, package install/upgrade, making it easier to
  write portable administration and deployment scripts.

Still, it sounds like I would have to learn Python to use Cuisine. I'm willing to do that if it is the right solution.
But I would like to ask here if there is a simpler way.


text:
Q: Using a list view to filter another list view I have two lists; List A and List B. List B has a lookup column to List A.
I want to filter List B based on the value in the field that looks up A. This can of course be done using the default OOTB column filtering. However, I want to create a view/webpart that does this for me using URL filters. Since List A will change from time to time, I won't hardcode the URL's, I want to create a special filtering view of List A I can add to List B's view.
I've managed to do what I'm trying except for one issue. When I filter List B using URL filters (e.g. http://server/site/Lists/Links/AllItems.aspx?FilterField1=DocumentID&FilterValue1=650) it will filter both List A's and List B's views simultaneously. I only want the filtering to be applied to List B. The solution to this could be to add View as an URL attribute, e.g. ?View={GUID}&FilterField1=DocumentID&FilterValue1=650. This will work, but then I need a reference to the View ID of List B from my List A xslt (to apply to the URLs).
Frankly, I could even live with the GUIDs being hardcoded, e.g. that I set them in List B's CAML and in the XSLT of List A. However, they just don't "stick", they are overridden during deployment.
Another option could be to render List A as "unfilterable". if you have any suggestions I'm all ears.

A: Use a "Filters » Query String (URL) Filter" webpart on a custom page.


text:
Q: Set NOINDEX, NOFOLLOW on particular products My magento store has the following to allow google/search engines to crawl the entire site.
<meta name="robots" content="INDEX,FOLLOW" />

I am now in need for some particular products to have:
<meta name="robots" content="NOINDEX,NOFOLLOW" />

so that google doesn't crawl/index them. Is this possible? Products would be random (i.e not all from one category) so I need to be able to do this on a product by product basis if needed.
I know i could do it on a url basis like:
<?php
$currentUrl = Mage::helper('core/url')->getCurrentUrl();
if ($currentUrl == 'xxxxxxx')
{
    <meta name="robots" content="NOINDEX,NOFOLLOW" />
}
else
{
    <meta name="robots" content="INDEX,FOLLOW" />
}
?>

but there could end up over time to be hundreds/thousands of these.

A: You can do this manually on a product-by-product basis by using the Custom Layout Update. In admin Catalog > Manage Products select your product, navigate to the design tab and int the Custom Layout Update field, insert the following:
 <reference name="head">
    <action method="setRobots"><value>NOINDEX,NOFOLLOW</value></action>
 </reference>

If there are going to be hundreds you may need to look into doing this in your local.xml, maybe on a per-attribute basis..


text:
Q: Почему фиксированный DIV сдвигается при использовании fancybox? Как исправить ситуацию? При использовании для просмотра картинок скрипта FancyBox
фиксорованный ДИВ съезжает вправо на ширину полосы прокрутки.
ПРИМЕР здесь. Как можно решить эту проблему?
A: $(".fancybox").fancybox({
    // ваши другие параметры
    'scrolling' : 'yes'
});


text:
Q: What do unlimit and limit do in the context of csh? I'm running a csh script that calls unlimit and limit just before running a scientific model. The script looks something like so (truncated for brevity):
#!/bin/csh -f
# ...
unlimit
limit
/usr/bin/time $BLD/$EXEC # Where `$BLD/$EXEC` is the path to the model
date
exit

Running the script produces the following error:
unlimit
unlimit: memorylocked: Can't remove limit
unlimit: maxproc: Can't remove limit
unlimit: openfiles: Can't remove limit

Checking ulimit from Bash:
$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 63711
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 63711
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

Trying unlimit (without specifying any resources) from csh:
$ sudo csh
# unlimit
unlimit: memorylocked: Can't remove limit
unlimit: maxproc: Can't remove limit
unlimit: openfiles: Can't remove limit

The output of limit from csh, and trying unlimit with resources specified:
$ sudo csh
# whoami
root
# limit
cputime         unlimited
filesize        unlimited
datasize        unlimited
stacksize       8192 kbytes
coredumpsize    0 kbytes
memoryuse       unlimited
memorylocked    64 kbytes
maxproc         63711
openfiles       1024
# unlimit openfiles
unlimit: openfiles: Can't remove limit
# unlimit memorylocked
unlimit: memorylocked: Can't remove limit

I am running Ubuntu 14.04:
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.1 LTS
Release:        14.04
Codename:       trusty

I am guessing that running unlimit is supposed to remove all the resource limitations before running the model, and the output of limit is supposed to verify that. Why would the root user not be able to remove the limitations? Is unlimit only supposed to be run as root?

A: ulimit is trying to increase the the maximum usage of those resources above that configured for the entire system by sysctl. Furthermore it's not actually possible to configure Linux with an unlimited number of some resources, such as open files.
Note that unlimiting all resources is not a good idea -- do you really want a few gigabytes of core dump should a model fail? Increase only those resources which are presenting a bottleneck to running the model. Because you can run the model successfully, this suggests that the resources available on your modern machine may be significantly more than on the machine for which the code was originally written.

A: See the csh man page, which documents the limit and unlimit builtins. The unlimit is to remove all limit, and the limit is the print the current limits. I'm guessing whoever wrote this ran into some sort of resource limit issue at some point and put these in as a defensive means to ensure there were no limits and print what they were if there were any.


text:
Q: Build the feature matrix and label vector: I have a dataset "Digit" . The dataset includes 1797 small images (8x8 pixels), each one includes a hand-written digit (0-9). Each image is considered as a data sample with pixels as features. Thus, to build the feature table you have to convert each 8x8 image into a row of the feature matrix with 64 feature columns for 64 pixels. How to build a feature matrix and label vector for it ???

A: If you're using numpy and cv2 you can do the following:
import numpy as np
import cv2

fname = "image1.jpg"
image = cv2.imread(fname)                    #  (8, 8, 1)

feature = image.reshape(64)                #  (64,)

to read a bunch of images and load into a 'feature matrix' (a numpy array) you can do the following:
N = 10 # number of images
data = np.zeros((N, 64))

for index in range(N):

    # get the current image and convert to feature, as above

    data[index] = np.copy(feature)

Each row of your data matrix is now one example (a 64 dim list of features).
Does this help?
The label vector can just be a 1D numpy array, i.e. labels = np.zeros(N)
EDIT:
There are a number of ways to read images:
(1) img = cv2.imread(filename)
(2) using matplotlib:
import matplotlib.image as mpimg
img = mpimg.imread(filename)

(3) using PIL (or PILLOW):
from PIL import Image
img = Image.open(filename)

It pays to check the shape of the image after it has been read, so that you know it is in the correct channel, width, height order that is appropriate for your application.

A: You can follow the scikit-learn tutorial on supervised learning, where they are using the Digit dataset
http://scikit-learn.org/stable/tutorial/basic/tutorial.html#loading-an-example-dataset
with more detail here. If you load the dataset as in the example, you can simple reshape the images:
from sklearn import datasets
digits = datasets.load_digits()
# To apply a classifier on this data, we need to flatten the image, to
# turn the data in a (samples, feature) matrix:
n_samples = len(digits.images)
data = digits.images.reshape((n_samples, -1))

This makes data a 2D matrix, with n_samples rows and as many columns as needed to fit the flattened image.


text:
Q: Azure Api Management log user accessed api Is there any rest api that can be used to fetch api access detail for a user. To know how many times a user accessed a api and how many success or failure request were there. i am not able to use log-to-eventhub.

A: Thanks to @MayankBargali-MSFT's Q&A answer to similar kind of issue and posting here to help other community members!

Azure APIM will do monitor the APIs published but only listed details are logged as per the APIManagementGatewayLogs.

Based on your requirement, leveage the APIM reporting API and refer to Microsoft Doc for more information on reporting API.

To know who the user accessed particular API in APIM recently, You can call the List by Request API by adding the filter (For example, last 4 days from this day, apiID, etc.).

The above response will provide the details like apiID, timeStamp, userID that helps to find the details.
Still paraphrasing @MayankBargali-MSFT from the post linked above:
To know how many time that user accessed the API, use List by User API where it gives the overall result in which we need to filter with the apiID, then you can get the API Level count.
Point to note here is:
Filter might not work for every column. Therefore, you must modify the outcome at your client's end to perform more filtering and obtain the appropriate result. For further information, kindly consult the relevant API document. As long as you don't delete the APIM instance, the data will continue to be maintained permanently.


text:
Q: Client-side authentication with google+ for iOS on azure mobile service backend I'm trying to integrate server-side side Google+ sign-in into my iOS app.
This is what i did:
func application(application: UIApplication, openURL url: NSURL, sourceApplication: NSString?, annotation: AnyObject) -> Bool
{
   return GPPURLHandler.handleURL(url, sourceApplication: sourceApplication, annotation:annotation)
}

// In the view controller
    @IBOutlet weak var gpLoginView: GPPSignInButton!
    googlePlus = GPPSignIn.sharedInstance()
    googlePlus.shouldFetchGooglePlusUser = true
    googlePlus.clientID = "CLIENT-ID"
    googlePlus.homeServerClientID = "HOME-CLIENT-ID"
    googlePlus.scopes.append(kGTLAuthScopePlusLogin)
    googlePlus.delegate = self;

func finishedWithAuth(auth: GTMOAuth2Authentication!, error: NSError!)
{
    if error != nil
    {
        println("[GoogleAuthentication] Error: \(error)")
    }
    else
    {
        var serverCode = GPPSignIn.sharedInstance().homeServerAuthorizationCode
        if serverCode == nil
        {
            println("[GoogleAuthentication] homeServerAuthorizationCode is missing")
            googlePlus.disconnect()
        }
        else
        {
            client.loginWithProvider("google", token: ["access_token" : serverCode])
            {
                user, error in
                println("[Azure::loginWithToken] Result. User=\(user). Error=\(error).")
            }
        }
    }
}

My have two credentials in my google developer console. One for iOS application and another for web application. The ClientID from iOS application is specified in googlePlus.ClientID. The ClientID from web application is specified in homeServerClientID. Also, the same ClientID and Secret is specified in Azure Mobile Service Identities configuration.
Also the URL Schema is created with the name of my application bundle.
I get the client portion of the authentication passed successfully and was able to get the homeServerAuthorizationCode, but when i try to do the server side portion i get an error from azure mobile service. The error i get is: Error Domain=com.Microsoft.WindowsAzureMobileServices.ErrorDomain Code=-1301 "The server returned an error." UserInfo=0x170464c80 {NSLocalizedDescription=The server returned an error.}.
Please help to figure out what am I doing wrong?
Thanks,
Ruben


text:
Q: How to display the data from mySQL in listview in android? I can insert data into database but now face the problem that cannot retrieve data from the database and display in listview in android. Here is my coding part for retrieve data. Hope someone can help to solve this, thank you.
package com.example.iuum;

private ProgressDialog pDialog;

private static final String READ_COMMENTS_URL = "http://10.19.229.212/webservice/comments.php";

private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";

private JSONArray mComments = null;

private ArrayList<HashMap<String, String>> mCommentList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_forum1a);
}

@Override
protected void onResume() {

    super.onResume();

    new LoadComments().execute();
}

public void clickbtnWrite(View v) {
    Intent i = new Intent(Forum1a.this, AddForum.class);
    startActivity(i);
}

/**
 * Retrieves recent post data from the server.
 */
public void updateJSONdata() {

    mCommentList = new ArrayList<HashMap<String, String>>();

    JSONParser jParser = new JSONParser();

    JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);

    try {

        mComments = json.getJSONArray(TAG_POSTS);

        for (int i = 0; i < mComments.length(); i++) {
            JSONObject c = mComments.getJSONObject(i);

            // gets the content of each tag
            String title = c.getString(TAG_TITLE);
            String content = c.getString(TAG_MESSAGE);
            String username = c.getString(TAG_USERNAME);

            HashMap<String, String> map = new HashMap<String, String>();

            map.put(TAG_TITLE, title);
            map.put(TAG_MESSAGE, content);
            map.put(TAG_USERNAME, username);

            mCommentList.add(map);

        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

/**
 * Inserts the parsed data into the listview.
 */
private void updateList() {

    ListAdapter adapter = new SimpleAdapter(this, mCommentList,
            R.layout.singelpost, new String[] { TAG_TITLE, TAG_MESSAGE,
                    TAG_USERNAME }, new int[] { R.id.title, R.id.message,
                    R.id.username });

    setListAdapter(adapter);

    ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

        }
    });
}

public class LoadComments extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Forum1a.this);
        pDialog.setMessage("Loading Comments...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
        updateJSONdata();
        return null;

    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        pDialog.dismiss();
        updateList();
    }
}
}

A: Add ListView in activity_forum1a.xml
<ListView
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></ListView>

Take ListView reference
    private ListView mList;

Initialize it in onCreate
    mList = (ListView) findViewById(R.id.list_view);

Take ListAdapter class Refernce
private ListAdapter listAdapter;

Add setListAdapter method
public void setListAdapter(ListAdapter listAdapter) {
    this.listAdapter = listAdapter;
    mList.setAdapter(listAdapter);
}

Change updateList method to
    /**
     * Inserts the parsed data into the listview.
     */
    private void updateList() {

        ListAdapter adapter = new SimpleAdapter(this, mCommentList,
                R.layout.test, new String[] { TAG_TITLE, TAG_MESSAGE,
                TAG_USERNAME }, new int[] { R.id.title, R.id.message,
                R.id.username });

        setListAdapter(adapter);
}

and perform item click operation outside from the method, by implementing onItemClickListener


text:
Q: proxy not working and port still goes port 3000 in react.js I want to fetch my data from port 8000,but it still get error 404.
Because it uses port 3000 ,I set proxy in package.json.
I don't know the reason why it goes wrong.
Error below:
GET http://localhost:3000/hotels/countByCity?cities=berlin,madrid,lodon 404 (Not Found)
Here are my relative codes:
pacakge.json
{
  "name": "booking",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fortawesome/free-regular-svg-icons": "^6.2.0",
    "@fortawesome/free-solid-svg-icons": "^6.2.0",
    "@fortawesome/react-fontawesome": "^0.2.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.1.3",
    "date-fns": "^2.29.3",
    "react": "^18.2.0",
    "react-date-range": "^1.4.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.4.2",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy":"http://localhost:8000/api"
}

useFetch.js
import { useEffect, useState } from "react";
import axios from "axios";

const useFetch = (url) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const res = await axios.get(url);
        setData(res.data);
      } catch (err) {
        setError(err);
      }
      setLoading(false);
    };
    fetchData();
  }, [url]);

  const reFetch = async () => {
    setLoading(true);
    try {
      const res = await axios.get(url);
      setData(res.data);
    } catch (err) {
      setError(err);
    }
    setLoading(false);
  };

  return { data, loading, error, reFetch };
};

export default useFetch;

featured.jsx
import React from 'react'
import "./featured.css"
import useFetch from "../../hooks/useFetch"
const Featured = () => {
const{ data,loading,error}=useFetch("/hotels/countByCity?cities=berlin,madrid,lodon")
console.log(data);
    return (

Amazônia.

189 properties

Avignon's historic center.

259 properties

Naz City Hotel Taksim

345 properties

    )
}

export default Featured


text:
Q: java.time.format.DateTimeParseException - what's the correct pattern to parse this date time string? Example input string: Mon Feb 07 07:47:04 UTC 2022
I have tried various different patterns, and none work, mostly I get the error:
java.time.format.DateTimeParseException: Text 'Mon Feb 07 07:47:04 UTC 2022' could not be parsed at index 4

This is my code (it's spark/scala but using Java libraries as is allowed). I need to convert strings of the form above, into a numeric value in seconds since the Unix epoch. I don't have control over the input format (it's from an external API) - I could use string manipulation on it if I really had to, but ideally just need to find a pattern that the formatter accepts.
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
import java.time.ZoneOffset;
import java.time.LocalDateTime;

def df = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("EEE LLL d H:m:s 'UTC' uuuu").toFormatter(Locale.ENGLISH);

def dateTimeStringToEpoch(s: String): Long = LocalDateTime.parse(s, df).toEpochSecond(ZoneOffset.UTC)

println(dateTimeStringToEpoch("Mon Feb 07 07:47:04 UTC 2022"));

Thanks


text:
Q: Struts2 Bulk Data display using ModelDriven I know the basic Concept of Model Driven process.
How ever i would like to know whether the same ModelDriven Interface process can be used to display bulk data on the action tagged response page ?
To explain this with example
Request page is normal has an argument which is action controlled.
On validate of request page an Intermediate process returns with the Array List Object
Response success page has an  Array List of buckets 100
Each bucket of the Array List holds a JavaBean Object of 10 values.
Question : By ModelDriven Interface process need to display data by looping thru Array List buckets and casting of the Java Bean on the Response page to extract the original data ??
with regards
karthik

A: I am not able to understand your question properly.
Request page is normal has an argument which is action controlled.

not sure what the above line actually mean
ModelDriven Actions provide a model object to be pushed onto the ValueStack in addition to the Action itself.
It provides more convenient than object back java bean.When you have implemented the model driven interface all that mean that framework will place that object on the top of valuestack.
That means say i have an object person with properties name and age,in normal approach i have to use java bean type accessor to access name property like
 <s:textfield name="name" value="%{person.name}"/>

but when i have model driven interface all i need to do is
 <s:textfield name="name" value="%{name}"/>

since now person is already on top of value stack so i need not to go traverse inside the person object


text:
Q: Catch file_get_contents timeout Can you help me?
<?php

$url='http://www.amigosdoforum.com.br/wp-content/uploads/2015/02/vingas.jpg';
$contents=file_get_contents($url);
if (false == $contents) {
  echo "Error!!";
} else {
  file_put_contents($_SERVER["DOCUMENT_ROOT"]."/system/images/aaa.jpg",$contents);
  echo "Success";
}

?>

This code is not catching "Fatal error: Maximum execution time of 30 seconds exceeded".
I know that I'm able to change the limit, but I don't want it! I just want to catch this error and show to me if the code downloaded the image or not
What should I do?

A: You cannot catch it because it's not an exception. You can register the shutdown function to handle this:
<?php
register_shutdown_function('shutdown');

function shutdown()
{
      // Your code to handle when PHP is down

}


text:
Q: How set in value type int? I need set value int. how do this?
    var list = from Enum e in Enum.GetValues(enumValue.GetType())
           select new SelectListItem
           {
               Selected = e.Equals(enumValue),
               Text = e.ToDescription(),
               Value = e.ToString()// need int
           };

if I set Value = ((int)e).ToString()
I get error:

Cannot convert type 'System.Enum' to 'int'

A: AFAIK in C#, Enums can be convert to int:
 Value = ((int)e).ToString()

That is as long as the underlying type is an int or castable to an int.

A: Cast to an int and get a string from it:
Value = ((int)e).ToString()

All enumerations are based on integer types, so a cast is the simplest solution (though if the enum is based on a long, you may get an overflow).
Additionally, the type returned from Enum.GetValues is the values of the enumeration - your LINQ should be:
from e in Enum.GetValues(enumValue.GetType())

As e will not be of type Enum.

A: Value = Convert.ToInt32(e.ToString())

A: You can try with
(int)YourEnum.enumValue;

or
(int)e

A:     var list = from Enum e in Enum.GetValues(enumValue.GetType())
       select new SelectListItem
       {
           Selected = e.Equals(enumValue),
           Text = e.ToDescription(),
           Value = (int) e
       };

A: you can convert enum directly by casting it to int type.


text:
Q: 403 Error while accessing s3a using Spark ISSUE:
Able to successfully download the file using AWS CLI as well as boto 3.
However, while using the S3A connector of Hadoop/Spark , receiving the below error:
py4j.protocol.Py4JJavaError: An error occurred while calling o24.parquet.
: com.amazonaws.services.s3.model.AmazonS3Exception: Status Code: 403, AWS Service: Amazon S3, AWS Request ID: BCFFD14CB2939D68, AWS Error Code: null, AWS Error Message: Forbidden, S3 Extended Request ID: MfT8J6ZPlJccgHBXX+tX1fpX47V7dWCP3Dq+W9+IBUfUhsD4Nx+DcyqsbgbKsPn8NZzjc2U

Configuration:
Running this on my Local machine

*

*Spark Version 2.4.4

*Hadoop Version 2.7
Jars added:

*

*hadoop-aws-2.7.3.jar

*aws-java-sdk-1.7.4.jar
Hadoop Config:
hadoop_conf.set("fs.s3a.access.key", access_key)
hadoop_conf.set("fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")
hadoop_conf.set("fs.s3a.secret.key", secret_key)
hadoop_conf.set("fs.s3a.aws.credentials.provider","org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider")
hadoop_conf.set("fs.s3a.session.token", session_key)
hadoop_conf.set("fs.s3a.endpoint", "s3-us-west-2.amazonaws.com") # yes, I am using central eu server.
hadoop_conf.set("com.amazonaws.services.s3.enableV4", "true")

Code to Read the file:
from pyspark import SparkConf, SparkContext, SQLContext
sc = SparkContext.getOrCreate()
hadoop_conf=sc._jsc.hadoopConfiguration()
sqlContext = SQLContext(sc)
df = sqlContext.read.parquet(path)
print(df.head())

A: Set AWS credentials provider to profile credentials:
hadoopConf.set("fs.s3a.aws.credentials.provider", "com.amazonaws.auth.profile.ProfileCredentialsProvider")

A: I faced the same issue as above. It turns out that I needed to add in the session token into my configuration. See the documentation.
configuration.set("fs.s3a.session.token", System.getenv("AWS_SESSION_TOKEN"))


text:
Q: Finding the force of attraction between a neutral and charged object I have looked through similar questions on stack exchange but I cannot find an answer that is satisfying my curiosity. Before getting into the question, I will make it painfully clear that I only have a basic understanding of physics and mathematics. While I have dabbled in self study to calculus, pre-calculus, and more complex physics, my conventional education only reaches the level of intermediate algebra and high school level physics. Now, as for the question. It just came to my understanding after reviewing induction that a force of attraction or repulsion could occur between a neutral and charged object. I visualized it as a drawing of two objects displaying the polarization of the charges. So I came to the conclusion that it would be solvable with Coulombs law. To avoid going on a tangent I will simplify the question.
Imagine a simple diagram consisting of one object A distance x away from object B. Object A shall be positively charged and B neutral. Call A's charge y. Now, assume object B is highly or even perfectly conductive. (I believe this property should allow for the free movement of electrons) Now because of this, the electrons will move toward the side of object B closest to object A. Therefore causing a difference in charge of the two sides. There would be a force of attraction between the closer "negative" side of B, but also force of repulsion from the farther "positive" side of B. Now the problem that arises here is simple yet I do not know how to approach it. Say we make a set of equations to label this using Coulomb's law. Doing this we find that the Net force will be equal to the sum of the force of attraction and repulsion. Now the problem in finding this (assuming we have the charges of these sides) lies in the distance. There will be some finite distance difference between the "positive" and "negative" sides in B. This is what allows some force of attraction between charged and neutral objects. So the real question comes now. How do you find this finite distance that would allow you to calculate the force of attraction/repulsion. Finding the charge is a problem on its own but I am interested in seeing how you could find the distance in order to calculate the charge.
This image I found online summarizes the question well. [Electron Movement in Conductors]
If you view this image you will see the difference in distance I am talking about. How could you calculate this. I am on a time crunch writing this and will clarify anything if needed.

A: For simplicity let us assume that both objects are spheres. The electric field produced by Object A causes a reconfiguration in the distribution of the electrons in object B. The redistributed electron in object B produces another electric field. In equilibrium, the total electric field should be perpendicular to the source of a conducting object.
In the case of spheres, the free electrons on the conducting sphere are redistributed as if there were an electric dipole of a given magnitude somewhere inside the sphere. The force between the induced dipole and object A is the attraction force.


text:
Q: how can an eigenvector represent an eigenface? I'm using python and the Olivetti dataset (with a lot of 64x64 grayscale face images).
I'm creating a matrix 20x4096, where each line is a sample (I chose 20 samples to be the training set) and each column is a value between 0 and 255, representing all the 64x64 pixels.
After doing PCA in this matrix, I get something about 10 eigenvectors (with 4096 slots each).
The eigenvectors are all normalized (meaning their length is 1). How can an eigenvector represent an eigenface? All its values are something around 0.001 or so.

A: If your goal is to visualise which image features are represented by each eigenvector, you can just plot the weight loadings as a heatmap.
Assuming you used scikit-learn to perform PCA, you can do this with following:
import matplotlib.pyplot as plt

plt.imshow(pca.components_[i].reshape(64,64),cmap="gray")

Where pca is your fitted PCA() variable and i is the ith principal component from the eigenvector matrix.


text:
Q: How to fix Uncaught Error: Cannot use e "__Schema" from another module or realm I have a Rails application with GraphQL API which works fine when running in development. After I deployed the app to Heroku, visiting the GraphiQL interface at /graphiql I get this error below:

Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.

https://yarnpkg.com/en/docs/selective-version-resolutions

Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.
    at n.default (application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:597)
    at u (application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:807)
    at o (application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:807)
    at M (application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:807)
    at R (application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:807)
    at new P (application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:807)
    at P (application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:807)
    at Object.129.../jsutils/isInvalid (application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:815)
    at i (application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12)
    at application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
n.default @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:597
u @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:807
o @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:807
M @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:807
R @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:807
P @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:807
P @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:807
129.../jsutils/isInvalid @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:815
i @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
(anonymous) @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
132.../error/GraphQLError @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:831
i @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
(anonymous) @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
96../execution/execute @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:588
i @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
(anonymous) @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
97../error @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:588
i @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
(anonymous) @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
(anonymous) @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:84
12.../utility/CodeMirrorSizer @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:84
i @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
(anonymous) @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
22../components/GraphiQL @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:139
i @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
t @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
(anonymous) @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
(anonymous) @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12
(anonymous) @ application-d621ca4100ba6f2e72e972ecd2a7ddcd5d2ec26b6f1fcf2932d68e2e12c78794.js:12

Meanwhile, here's my routes file:
Rails.application.routes.draw do
  mount GraphiQL::Rails::Engine, at: '/graphiql', graphql_path: '/graphql'
  get 'home/index'
  post '/graphql', to: 'graphql#execute'
  root 'home#index'
end

And I am using these versions of graphql and graphiql-rails respectively:
graphql (1.10.8)
graphiql-rails (1.7.0)


text:
Q: Return initial value or most recent occurance with XPath then run operator I have the following XPath 1.0 expression in MS InfoPath (I will post accompanying XML):
//my:Value_Modifier_Group[1=count(following-sibling::my:Value_Modifier_Group)]//my:Modified_Start_Value[(text())] | //my:Start_Value[text() and not(//my:Value_Modifier_Group[1=count(following-sibling::my:Value_Modifier_Group)]//my:Modified_Start_Value[(text()])]
If there is an initial value and no "Modified Value" yet then the initial value is returned. If a modified value is present then it is returned.
I need to return that value and then perform the following operations on it:
number(//my:Value_Modifier_Group[1=count(following-sibling::my:Value_Modifier_Group)]//my:Modfied_Start_Value) + number(//my:Value_Modifier_Group[0=count(following-sibling::my:Value_Modifier_Group)]//my:Start_Value_Increase) - number(//my:Value_Modifier_Group[0=count(following-sibling::my:Value_Modifier_Group)]//my:Start_Value_Decrease)
This operation adds or subtracts an increase/decrease value. The problem is that this expression returns a NaN if no Modified_Start_Value is present. Works great otherwise.
I need to team both of these expressions together into a single XPath expression.

*

*If Modified_Start_Value has a preceding value, use that in operations

*If Modified_Start_Value does not have a preceding value then use Start_Value in operations instead

*It is important that I always use the "preceding" value because the preceding value is fixed. It acts as a reference point or starting point.

Here is a sample of the XML I am using:
<?xml version="1.0" encoding="UTF-8"?><?mso-infoPathSolution solutionVersion="1.0.0.2" productVersion="14.0.0" PIVersion="1.0.0.0" href="file:///C:\Documents%20and%20Settings\Chris\Local%20Settings\Application%20Data\Microsoft\InfoPath\Designer3\ef41a19775b4ce0\manifest.xsf" ?><?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.3"?>
<my:myFields xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-09-19T13:28:35" xml:lang="en-us">
<my:Start_Value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">6</my:Start_Value>
<my:Main_Group>
    <my:Value_Modifier_Group>
        <my:Modified_Start_Value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">6</my:Modified_Start_Value>
        <my:Start_Value_Increase>0</my:Start_Value_Increase>
        <my:Start_Value_Decrease>0</my:Start_Value_Decrease>
    </my:Value_Modifier_Group>
<my:Value_Modifier_Group>
    <my:Modified_Start_Value>6</my:Modified_Start_Value>
    <my:Start_Value_Increase>0</my:Start_Value_Increase>
    <my:Start_Value_Decrease>0</my:Start_Value_Decrease>
</my:Value_Modifier_Group></my:Main_Group>
</my:myFields>

I hope this question isn't too hastily put together! Busy day today...

A: Ok, I am going to self answer this question as I just figured it out.
The key is to combine the XPath expressions by placing the value from the first expression into a node and then referencing that node in the second expression.
It seems that the pipe command | does not play well with other operators.
The following expression returns values in the following way:

*

*//my:Value_Modifier_Group[1=count(following-sibling::my:Value_Modifier_Group)]//my:Modified_Start_Value[(text())] | //my:Start_Value[text() and not(//my:Value_Modifier_Group[1=count(following-sibling::my:Value_Modifier_Group)]//my:Modified_Start_Value[(text()])]

*If no preceding Modified_Start_Value is available before the first Modified_Start_Value node the expressions defaults to the initial value.

*In this way you are guaranteed the most recent valid Start_Value or Modified_Start_Value
This value of this expression is then put into a node titled StartVModStart. The XPath for this node is then put into the evaluating expression:
../../../my:StartVModStart + number(/descendant-or-self::node()/my:Value_Modifier_Group[0 = count(following-sibling::my:Value_Modifier_Group)]//my:Start_Value_Increase) - number(/descendant-or-self::node()/my:Value_Modifier_Group[0 = count(following-sibling::my:Value_Modifier_Group)]//my:Start_Value_Decrease)

*

*This expression uses "the most recent" value and then adds or subtracts the changes

In this way one can keep a "running sum" through the course of document, starting in an initial node and moving all the way through repeating nodes.
This question seems highly convoluted, so forgive me if both my question and answer do not seem clear. As I reach for more complex functionality the required XPath expressions become more and more complex.


text:
Q: Algorithm to add implied parentheses in boolean expression I have a string such as "A and B or not C and D". The atoms are all simple uppercase letters A,B,C... and the operators are only { and, or, not }.  I would like to devise an algorithm that can add parentheses that are implied by the usual rules of precedence.
Can anyone think of a very simple way to do this? perhaps using Regex?
The desired output is "(A and B) or ((not C) and D)".

A: It can be as simple as this (Python code ahead):
def popnext(stream, token):
    if stream[0:len(token)] == list(token):
        del stream[0:len(token)]
        return True
    return False

def parse_binary(stream, operator, nextfn):
    es = [nextfn(stream)]
    while popnext(stream, operator):
        es.append(nextfn(stream))
    return '(' + ' {} '.format(operator).join(es) + ')' if len(es) > 1 else es[0]

def parse_ors(stream):
    return parse_binary(stream, 'or', parse_ands)

def parse_ands(stream):
    return parse_binary(stream, 'and', parse_unary)

def parse_unary(stream):
    if popnext(stream, 'not'):
        return '(not {})'.format(parse_unary(stream))
    return parse_primary(stream)

def parse_primary(stream):
    if popnext(stream, '('):
        e = parse_ors(stream)
        popnext(stream, ')')
        return e
    return stream.pop(0)

def evaluate(expression):
    return parse_ors(list(expression.replace(' ', '')))[1:-1]

print evaluate('A and B or not C and D')
print evaluate('A and (B or not C) and D')

result:
(A and B) or ((not C) and D)
A and (B or (not C)) and D

A: A grammar for your these Strings might be defined by the following production rules:

*

*S → E

*E → EorE

*E → F

*F → FandF

*F → T

*F  → notT

*T → A

*T → B

*T → C

*T → D
(Make rule 6 "T → not T"), if strings like "not not D and not not not B" shall be allowed, too.)
While this grammar is context free, it isn't regular. I don't think a regular grammar for your strings exists, so regular expressions are not sufficient to match exactly these strings, and by extension also not to parse and transform (re-write) them correctly.


text:
Q: Create EmailMessage out of Aspose.Net Email MapiMessage? Is there a way to create an EWS EmailMessage class instance out of Aspose.Net Email MapiMessage class instance?
I'm trying to use some common logic for email processing.
1) I have a service processing emails coming to an Exchange folder, and everything works just perfectly.
2) Also, I have users able to upload email files (*.msg) into the web app. These emails are processed using Aspose.Net.Email and I have an instance of MapiMessage as an output.
What I can try to do is to use MapiMessage .ToMailMessage() method, which will create an instance of MailMessage from this MapiMessage. But even after that, I wasn't able to find a way to create an EmailMessage to be able to use the processing logic from 1).
Any suggestions?

A: I have observed your requirements and if I am correctly understanding you are looking for support for interface between Aspose.Email MapiMesaage class and EWS EmailMesage class. These two classes belong to two different APIs and have no interface between them. Aspose.Email for .NET does allow saving as MSG or EML file format and you may load them on your end using EmailMessage class.
I am working as Support developer/ Evangelist at Aspose.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.exchange.webservices.data.emailmessage?view=exchange-ews-api
https://apireference.aspose.com/net/email/aspose.email.mapi/mapimessage/constructors/1


text:
Q: How to control bounded source split? I have a Dataflow where the input is a large read from a database. I would like to split this query up and have it executed from multiple hosts when the job starts. As far as I can tell, the BoundedSource has no way of directly controlling the input split. The closest it has is splitIntoBundles which basically means I have to start a very expensive read and hope Dataflow cancels it and uses my defined bundle split instead. This seems pretty crazy, so I'm hoping there is a better way of predefining an input split that can be run on any remote workers.

A: After much research, there is no way to control the split parallelism of a single reader. My solution was to create multiple readers, have each reader read into its own PCollection, and then flatten the multiple PCollections into a single PCollection.


text:
Q: IGeoPositionWatcher.PositionChanged is not being fired, but GeoCoordinateWatcher.PositionChanged is I'm trying to write an application which monitors the location of the computer using the .net 4.0 System.Device.Location namespace.  However I'm finding that the GeoCoordinateWatcher.PositionChanged event is only fired when I register with the event on the class, and not when I use the interface it implements.
Here is a working version of the code:
using (GeoCoordinateWatcher geoCoordinateWatcher = new GeoCoordinateWatcher())
{
    geoCoordinateWatcher.PositionChanged += (sender, args) => Console.WriteLine(args.Position);
    geoCoordinateWatcher.Start();

    Thread.Sleep(2000);
}

This outputs the position object as I would expect.  When I change the code to this:
using (GeoCoordinateWatcher geoCoordinateWatcher = new GeoCoordinateWatcher())
{
    IGeoPositionWatcher<GeoCoordinate> positionWatcher = geoCoordinateWatcher;
    positionWatcher.PositionChanged += (sender, args) => Console.WriteLine(args.Position);
    positionWatcher.Start();

    Thread.Sleep(2000);
}

it doesn't output anything.  I want to use the interface so that it's easier to unit test the code.
What am I doing wrong?  Is there something subtle I'm misunderstanding about events on generic interfaces?
Thanks
Andy
EDIT:
I think this may be a bug in Microsoft's code.  I had a look at System.Device.dll in .net reflector and found that the GeoCoordinateWatcher has 2 implementations of PositionChanged event.  The first a direct implementation of its own PositionChanged Event, the second is a explicit implementation of the IGeoPositionWatcher.PositionChanged event.
The second one appear not to be used anywhere else in the code.
I also managed to find a quick workaround by deriving from GeoCoordinateWatcher, and implementing the interfaces PositionChanged event myself:
public class MyGeoCoordinateWatcher : GeoCoordinateWatcher, IGeoPositionWatcher<GeoCoordinate>
{
    event EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>> IGeoPositionWatcher<GeoCoordinate>.PositionChanged
    {
        add { base.PositionChanged += value; }
        remove { base.PositionChanged -= value; }
    }
}

Now if I create a MyGeoCoordinateWatcher instead both sets of the above code work.
Can anyone confirm this?
Thanks
EDIT:
Raised this on Microsoft Connect: https://connect.microsoft.com/VisualStudio/feedback/details/613235/igeopositionwatcher-geocoordinate-positionchanged-event-does-not-fire-on-geocoordinatewatcher-class

A: I completely agree with your diagnosis, nice sleuthing.  The explicit interface implementation is updating a field named m_positionChanged.  The PositionChanged event is updating a delegate field named PositionChanged.
Inspiring to see the big boys fumble this.  No simple workaround for this beyond hacking reflection to access the private fields directly.  You can report the bug at connect.microsoft.com.  Just a link to this thread should give them everything they need.

A: Apparently this behaviour is by design.  I've asked Microsoft to clarify this, as it seems very odd design to me.


text:
Q: Dynamically creating nested for loops I am creating a program to generate a list of numbers in lexicographical order and I need nested for loops based on the number of elements in the input. I'd like to dynamically allocate/create nested for loops based on the number of elements in the input.
def bounded_lists(upper_bounds):
    res = []
    for i in range(0,max(upper_bounds) + 1):
        for j in range(0,max(upper_bounds) + 1):
            for k in range(0,max(upper_bounds) + 1):
                if i<=upper_bounds[0] and j<=upper_bounds[1] and k<=upper_bounds[2]:
                    res.append([i,j,k])
    return res

This code gives me the right result and is straightforward if I know that the number of elements in the input is 3.

A: You are looking for itertools.product.
An example of this in action might be
from itertools import product

def bounded_lists(inlists):
    return list(product(*inlists))

arr = [[1, 2], [3, 4, 5], [6]]
print(bounded_lists(arr))
# This prints
# [(1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 3, 6), (2, 4, 6), (2, 5, 6)]
# This is in lexicographical order according to the orders of the lists in arr.


text:
Q: Robolectric's Shadow Object for Bluetooth Good day,
I made a android program which open bluetooth socket with another device, then exchange data with this device.
I am trying to make unit test for it, but I dont know how to make a shadow for the bluetoothDevice, how to test the connection, or the how to work virtualy with the another connected device.
I try to read the Robolectric documentaion, but it did not help me.
Anybody can please help me.
Thanks.

A: This is a pretty old question, but I'll go ahead and answer.  You should be able to get your ShadowBluetoothDevice with something like this:
ShadowBluetoothDevice bluetoothDevice = shadowOf(ShadowBluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:07:80:78:A4:69"));


text:
Q: Printing using Nodejs I am having a really hard time figuring out how I am going to handle printing in my Nodejs application. I have a website where there is a bunch of purchase numbers. I want the users to print this numbers in a click of a button. These numbers are dynamically generated after querying the database.
I started using this npm library to print the purchase number. When I am developing in my local computer this library is working fine. I made it so that each time the user presses a button in the front end, I make a post request to my Nodejs Server which prints to the printer that I configured locally.
The problem is that I want to eventually deploy my website to Heroku. Website will be used by a group of people sharing the same network and printer. I do not know of a way to set heroku to communicate with the printer using this package.
I also thought that printing directly from the front end might be a better idea, but I have to open google on kiosk mode and then do the same for all the users that are going to use this website. Also, most of the users will be using a tablet device so configuring printer in those devices will be difficult as well.
I did not find anything online that I can use as a reference. Any advice or suggestion will be greatly appreciated.

A: As for nodeJs printing I have no experience. It seems that you can use certain packages to print a pdf as given in the example answer here: Node.js : How to add print job to printer.
As for generating from html to PDF, that should be easy to find, less easy to style correctly though.
I would recommend doing it from HTML (you could still do the PDF conversion for more stable printing results)
From HTML
As stated, the API is rather limited, you can use window.print to request a print action.
Note though that you have some options to make your life better when calling window.print().
You can create the page in a separate window to get rid of bloat, like navigation etc, or you could actually hide that with css.
You might already be aware of css being included for certain targets e.g. for your website you probably want to use the screen target, but you can create a separate stylesheet for printing.
More info at mozilla
https://developer.mozilla.org/en-US/docs/Web/Guide/Printing


text:
Q: jQuery 'Whack-A-Mole'-type game issue I'm creating a Whack-A-Mole type of game for my Javascript class. I've been trying to figure out how to make it so that the user can only click the "mole" once. As it is right now, I can repeatedly click the "mole" as it fades out. The "moles" are added in dynamically so I couldn't seem to get .one() to work. Hopefully you guys can help me out. The game is almost finished, this is pretty much the last thing I need to change. I've uploaded the game to my website here: http://shawnnance.com/game/

A: As Alejandro Iván suggests, it's probably better to stick with a data property for this, though using a class would work as well.
Data Property
Use the .data() method to attach arbitary data to your img:
$("#gamespace").append('').data("clicked","false");

Then only track clicks to the unclicked imgs:
$('#gamespace img[data-clicked="false"]').on('click', "img", function() {
     incrementScore();
     $(this).data("clicked","true").fadeOut("fast");
     $('#blaster').html("<audio autoplay><source src='img/blaster.mp3' type='audio/mpeg'> Your browser does not support the audio element. </audio>");
});

Class
Add a class to the mole at the start, then only track clicks to that class. For instance:
$("#gamespace").append('').addClass("notClicked");

Then,
$('#gamespace img.notClicked').on('click', "img", function() {
     incrementScore();
     $(this).removeClass("notClicked").fadeOut("fast");
     $('#blaster').html("<audio autoplay><source src='img/blaster.mp3' type='audio/mpeg'> Your browser does not support the audio element. </audio>");
});

So you remove the class the moment it's been clicked on so it can't be clicked on again.


text:
Q: Does Kafka's producer.flush() verify that all the data is sent to topic? I'm sending about 12 million rows of data to Kafka topic, via Pythonic KafkaProducer on a daily basis.
The data needs to be JSON formatted, and each row as a 1 entry,
and does a producer.flush() every 1 million rows.
The code is provided below:
import json
count = 0
for key in json_df:
    x = json.dumps(key, default=str).encode('utf-8')
    producer.send('SOME_TOPIC_NAME', value=x)
    count+=1
    if (count % 1000000 == 0):
        producer.flush()
producer.flush()

But today I have faced a problem that 250~ rows were missing from the topic, and my question is: does the execution of producer.flush() more often guarantees that no data is missing?
I also have linger_ms = 500 in KafkaProducer object, does decreasing the frequency of linger makes sure that all the data is sent to topic?

A: I dont think the flush is the problem. There is nothing in your code that checks if the program itself dies with less than 1M records. When you restart the producers, the count restarts a zero, and you lose all intermediate batched records.
To answer the question - yes, flush is a blocking call that empties the data that is available in the batch... Keep in mind that Kafka does have a batch.size upper limit (in bytes).
If you already had a JSON-lines formatted file, you could just do
kafka-console-producer ... < file.jsonl


text:
Q: unable to pause my Repository execution using System.Threading.Thread.Sleep(10000); I am working on an asp.net MVC-4 web application. now inside my model repository class i want to pause the execution of it for testing purposes . so inside my repository model class , i define the following inside the repository model class:-
 public class Repository
{

        public TechnologyAudit IntiateTechnologyAudit(int actionId, int typeID, string username)
        {

                System.Threading.Thread.Sleep(10000);

and i am calling the repository method from my controller class as follow:-
repository.IntiateTechnologyAudit(actionid,typeid,"Test User");

but this did not pause the repository execution for the specified time.. so can anyone adivce on this please ?


text:
Q: Got a `TypeError` when calling `Article.objects.create()` I am working on Django React Project using the Django REST FRAMEWORK,I am trying to post some data tied to my model.
The list view and the detail view of the project works pretty fine,The only problem is when I try to make a POST request.
Whenever I Try post the data in the CreateAPIView I get an error :
Got a `TypeError` when calling `Article.objects.create()`.  This may be because
you have a writable field on the serializer class that is not a valid argument to
`Article.objects.create()`.  You may need to make the field read-only, or override
the ArticleSerializer.create() method to handle this correctly.

I have searched through various past problems but non of them seem to fix my problem.
Here is my serializers file:
from rest_framework import serializers
from articles.models import Article

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('id','title','content','star_count','like_count','comment_count','avatar')

Here is my views file
from rest_framework.generics import  ListAPIView,RetrieveAPIView,CreateAPIView,UpdateAPIView,DestroyAPIView
from .serializers import ArticleSerializer
from articles.models import Article
from rest_framework import viewsets

class ArticleViewSets(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

models file
    content = models.TextField()
    comment_count = models.IntegerField(default=0,null=True,blank=True)
    like_count = models.IntegerField(default=0,null=True,blank=True)
    star_count = models.IntegerField(default=0,null=True,blank=True)
    avatar = models.ImageField(null=True,blank=True)

    def  __str__(self):
        return self.title

    def save(self):
        if not self.slug:
            self.slug = slugify(self.title)
        super(Article,self).save()

Here is the error generated when I try to make a POST request based on the django rest framework createAPIVew
Got a `TypeError` when calling `Article.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Article.objects.create()`. You may need to make the field read-only, or override the ArticleSerializer.create() method to handle this correctly.