text:
Q: function of pyqtSlot I just read a tutorial about pyqt5 button from here. And the code is as below. There is a question about button.clicked.connect(self.on_click) and @pyqtSlot(). If I delete @pyqtSlot() from the code, it still works. However, the button does not work if I delete button.clicked.connect(self.on_click) from the code. So what is the function of @pyqtSlot() in this code?
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 button - pythonspot.com'
        self.left = 10
        self.top = 10
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('PyQt5 button', self)
        button.setToolTip('This is an example button')
        button.move(100,70)
        button.clicked.connect(self.on_click)

        self.show()

    @pyqtSlot()
    def on_click(self):
        print('PyQt5 button click')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

A: button.clicked.connect(self.on_click) binds signal of a button (clicked) to a slot self.on_click. Without this binding click will result in no action.
@pyqtSlot, in turn, is a decorator which converts simple python method to Qt slot. Doc states:

Although PyQt5 allows any Python callable to be used as a slot when
  connecting signals, it is sometimes necessary to explicitly mark a
  Python method as being a Qt slot and to provide a C++ signature for
  it. PyQt5 provides the pyqtSlot() function decorator to do this.
...
Connecting a signal to a decorated Python method also has the advantage of reducing the amount of memory used and is slightly faster.

When is that decorating necessary?
The only case I know is when you want to call methods from a QML interface: you can pass an object derived from QObject to QML and call object's methods but only if these methods are decorated with @pyqtSlot decorator with defined signature.
For your case consider it as a good practice - denoting a method as a slot for some signal.


text:
Q: How to use a custom type from RIA services with lightswitch? I have a service class that is passed to lightswitch using RIA services. The service class uses a custom type instead of native lightswitch or SQL types.
public class MyService : DomainService
{
    [Query(IsDefault = true)]
    public IQueryable<MyRecord> GetMyRecordData()
    {
        return ...
    }
}

public class MyRecord
{
    [Key]
    public int Id {get; set;}

    public string Text {get;set;}

    public MyCustomType Custom {get;set;}
}

public struct MyCustomType
{
    public MyCustomType (int val1, int val2) : this ()
    {
       Val1 = val1;
       Val2 = val2;
    }

    public int Val1 {get; private set;}
    public int Val2 {get; private set;}
}

How to have lightswitch use this custom type for its display ?

A: Custom types are not supported as entity members unless they implement the IList interface. Even in the case of an IList implementation, you would not be allowed to provide a list of complex types, just simple .NET types. So there's no way to pass an instance of MyCustomType as a supported entity member.
Unfortunately Microsoft has taken the RIA spec offline, but you can still find a copy here. See section 4.11 for an explanation of this limitation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Image not uploading in storage laravel livewire, returning 404 not found I am using Laravel Jetstream livewire, Everything is working fine on localhost. But when I am uploading profile picture online, It's path is saving in database '/storage/profile-photos/pJis4kArzwPH059sisxUvVR95h81UI8EFXm1pRrV.jpg' but image is broken and returning 404 not found .
I tried everything ie:
    $exitCode = \Artisan::call('config:cache');
    $exitCode = \Artisan::call('config:clear');
    $exitCode = \Artisan::call('cache:clear');
    $exitCode = \Artisan::call('view:clear');
    $exitCode = \Artisan::call('route:clear');
    $exitCode = \Artisan::call('clear-compiled');
    $exitCode  = \Artisan::call('storage:link');

But nothing worked.
How can I solve this problem ?


text:
Q: Буквы и спецсимволы в строке регулярных выражений Есть подобная строка
/$s3..$8Hf

Написал регулярное выражение, но что-то оно не работает
/^[\$\/\.a-z0-9]{10}$/

Прошу подсказать, где ошибка?

A: У тебя там есть заглавная H, а в регулярке только строчные буквы. Попробуй ...a-zA-Z


text:
Q: get a char passed as parameter I would like to write a function in NASM System V ABI x86-64 (Intel Syntax) that I could use in a C program.
Here is the prototype of the function:
char *rindex(const char *s, int c);

I therefore retrieve the parameters in order (const char *s = rdi, int c = rsi)
First, I get the character stored in the register rsi and put it in ah:
segment .text

global rindex:function

rindex:
    mov ah, byte [rsi] ;; get the character
    [...]

Unfortunately, this line crashes my program:
rindex("hello world", 'o') // segfault

Why it is impossible to get the char and what would be the correct way?

A: I call "char" your first argument (const char *s = rdi), since it is a pointer to char. Your second argument (int c = rsi) is an int. To access elements of the string pointed by s you can use mov ah, byte ptr [rdi]. But your second argument is not a pointer, rsi contains the value of c. To read it you can read from esi, since the value of an int fits in the lower 32-bits of rsi.


text:
Q: Find parametrised method in unit test through reflection I have a Below sample code where I am trying to read the testid in after method , for method without parameters it works well , but My methods have Map as a parameter ..and it is failing.
I am not able to figure out how to read this testid in Aftermethod for parametrized method.-
Also In testng if say test1 failed then test2 will be skipped due to dependonMethod how can i still read this skipped method annotation value in aftermethod??
@Data(testId = 1623)
@Test(description = "test 1")
public void readTestAnnotation(Map<String,String> inputData) {
    logger.assertTrue(true, " test pass");
    logger.assertAll();
}

@Data(testId = 1645)
@Test(dependsOnMethods= {"readTestAnnotation"},  description = "test
2")
public void readTestAnnotation1(Map<String,String> inputData) {
    logger.assertTrue(true," test failed");
    logger.assertAll();
}

@Data(testId = 1646)
@Test(dependsOnMethods = {"readTestAnnotation1"}, description =
"test3")
public void readTestAnnotation2(Map<String,String> inputData) {
    logger.assertTrue(true," test failed");
    logger.assertAll();
}

 @AfterMethod(alwaysRun = true)
public void readtestId(ITestResult tr) throws NoSuchMethodException,
SecurityException {
String methodName = tr.getMethod().getMethodName();
UseAsTestId ta =
sampletest.class.getMethod(methodName).
   getAnnotation(UseAsTestRailId.class);

    System.out.println(ta.testRailId());

 }

A: You need to use getMethod with Parameters types:
sampletest.class.getMethod(methodName).
   getAnnotation(UseAsTestRailId.class, Map.class);

Quotation from javadoc:
public Method getMethod(String name,
                         Class<?>... parameterTypes)
                  throws NoSuchMethodException,
                         SecurityException

Returns a Method object that reflects the specified public member
  method of the class or interface

represented by this Class object. The name parameter is a String
    specifying the simple name of the desired method. The parameterTypes
    parameter is an array of Class objects that identify the method's
    formal parameter types, in declared order. If parameterTypes is null,
    it is treated as if it were an empty array.


text:
Q: Install Stylus manually in Node.js with Cygwin after a few tries I successfully install nodejs in windows with cygwin...
And when I find out that I can't install npm in windows, I wonder...
How can I install the Stylus manually??
I downloaded the files from the Stylus Github Site
Where do I copy them??
What commands should I use in the cgywin to install it??

A: Not sure if this is too late, but good news everyone! NPM runs on windows without cygwin now :-)
http://npmjs.org/doc/README.html


text: Q: VS2015 CSS menu items publish in a different color My environment is Windows10 and VS2015. I have a black page header in site master, and for contrast I use gold letters for menu item names, but when I publish, my menu items appear dark blue and are unreadable. I attach images of both set of letters and my CSS. I have not experienced this before and would appreciate a solution


text:
Q: Jenkins launch slave via execution of command on the master + The system cannot find the file specified Trying to start a slave on a remote machine from Master (local machine) using the Jenkins (launch slave via command line on Master)
ssh 10.1.18.135 java -jar D:/Jenkins/slave.jar

The slave.jar is present in the above path, It fails with this error:

[07/01/13 14:16:11] Launching slave agent $ ssh 10.1.18.135 java -jar
      D:/Jenkins/slave.jar The system cannot find the file specified ERROR:
      Unable to launch the slave agent for test123 : The system cannot find
      the file specified java.io.IOException: Cannot run program "ssh":
      CreateProcess error=2, The system cannot find the file specified    at
      java.lang.ProcessBuilder.start(Unknown Source)  at
      hudson.slaves.CommandLauncher.launch(CommandLauncher.java:115)  at
      hudson.slaves.SlaveComputer$1.call(SlaveComputer.java:230)  at
      java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)   at
      java.util.concurrent.FutureTask.run(Unknown Source)     at
      java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source) Caused by:
      java.io.IOException: CreateProcess error=2, The system cannot find the
      file specified  at java.lang.ProcessImpl.create(Native Method)  at
      java.lang.ProcessImpl.(Unknown Source)    at
      java.lang.ProcessImpl.start(Unknown Source)

Can someone help on this?

A: "The system cannot find the file specified" refers to ssh, not slave.jar. Ensure you have a Windows ssh implementation installed and that the folder it resides in is present in your PATH environment variable.


text:
Q: Need to Add Custom Button and Related action in System->Config->Custom section as field I am Adding Custom Section in System->Config Tab.
I need to add Button as Field and its related action which I need to perform. But I cannot find on google for button all example provide other field option but hard to get button example.
Other Section Working fine but I am not able to add button and related action (filepath) which call on click.
<fields>
  <goldprice translate="label">
    <label>GoldPrice</label>
    <frontend_type>text</frontend_type>
    <sort_order>0</sort_order>
    <show_in_default>1</show_in_default>
    <show_in_website>1</show_in_website>
    <show_in_store>1</show_in_store>
    <comment>Gold Price per 1gm</comment>
  </goldprice>
  <run translate="label">
    <frontend_type>button</frontend_type>
    <frontend_model>/adminhtml_system_config_customfield</frontend_model>
    <sort_order>30</sort_order>
    <show_in_default>1</show_in_default>
    <show_in_website>1</show_in_website>
    <show_in_store>1</show_in_store>
  </run>
</fields>

My Config File Like Below
<?xml version="1.0"?>
<config>
  <modules>
    <LetsNurture_CustomGrid>
      <version>0.1.0</version>
    </LetsNurture_CustomGrid>
  </modules>
  <global>
    <blocks>
      <customgrid>
        <class>LetsNurture_CustomGrid_Block</class>
      </customgrid>
    </blocks>
    <models>
      <class>LetsNurture_CustomGrid_Model</class>
    </models>
    <helpers>
      <customgrid>
        <class>LetsNurture_CustomGrid_Helper</class>
      </customgrid>
    </helpers>
    <events>
      <admin_system_config_changed_section_gold> <!-- identifier of the event we want to catch -->
        <observers>
          <customgrid>
            <type>model</type>
            <class>LetsNurture_CustomGrid_Model_Observer</class>
            <method>UpdatePrice</method>
          </customgrid>
        </observers>
      </admin_system_config_changed_section_gold>
    </events>
  </global>
</config>

And Customfiled.php like below
class LetsNurture_CustomGrid_Block_Adminhtml_System_Config_Customfield extends Mage_Adminhtml_Block_System_Config_Form_Field
{
    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
    {
        $url = $this->getUrl('catalog/product'); //

        $html = $this->getLayout()->createBlock('adminhtml/widget_button')
                    ->setType('button')
                    ->setClass('scalable')
                    ->setLabel('Run Now !')
                    ->setOnClick("setLocation('$url')")
                    ->toHtml();

        return $html;
    }
}

But it gives me Warning like this "failed to open stream: No such file or directory"
Thanks,
Yogesh

A: <frontend_model> path goes to to Blocks (instead of Models).
Incidentally, even though it's named a model class but we have to create it as a Magento Block class since this is how the other built in front end model classes are implemented.
As well as, it is used for template output so it's appropriate to create a block class for this.
Example
<frontend_model>NAMESPACE_MODULENAME/adminhtml_system_config_customfield</frontend_model>

So
Create Customfield.php under .../NAMESPACE/MODULENAME/Block/Adminhtml/System/Config/ with the following content:
class NAMESPACE_MODULENAME_Block_Adminhtml_System_Config_Customfield extends Mage_Adminhtml_Block_System_Config_Form_Field
{

    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
    {
        $html = parent::_getElementHtml($element);
       //Write your custom html here
        return $html;
    }
}

Hope this help you


text:
Q: Falling to install Remi repo: RHEL 7.4 How to force subscription manager to accept REMI repo?
I'm not sure how to proceed. I've already spent 3 hours looking for a solution.
What I want in the end is to be able to install R (yum install -y R), but there're dependencies which require other repos, namely REMI so that I can install pcre2-devel
Really appreciate a solution. Thanks!
yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm

# yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm
Loaded plugins: enabled_repos_upload, langpacks, package_upload, product-id, search-disabled-repos, subscription-
              : manager
remi-release-7.rpm                                                                            |  17 kB  00:00:00
Examining /var/tmp/yum-root-efHRDy/remi-release-7.rpm: remi-release-7.7-1.el7.remi.noarch
/var/tmp/yum-root-efHRDy/remi-release-7.rpm: does not update installed package.
Error: Nothing to do
Uploading Enabled Repositories Report
Loaded plugins: langpacks, product-id, subscription-manager

A: Explanation is in the error message, remi-release is already installed.
But notice that RHEL 7.4 is outdated and unmaintained. Current version is 7.7.

A: I met the same error on Centos 7. and this is what I fixed.
Reinstall the epel-release  if you installed it
Check
yum install epel-release

Package matching epel-release-7-11.noarch already installed. Checking for update.
Next remove epel-release
yum remove epel-release -y
yum update

Next epel-release 7.13
yum install -y epel-release
yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm


text:
Q: Polymer get an attribute from an element I am using neon-animation-pages and I want to see if an attribute is set on one of its child elements.  From what I understand you can just add any attribute you want and if it is in the tag it will resolve to true if it doesn't have a value explicity set.  For instance:
<neon-animation-pages id="pages">

This one is awesome

This one is not

This one is not

</neon-animation-pages>

Above I created my own attribute called: awesome
In my code I use this:
_onIronSelect: function(){
    console.log(this.$.pages.selectedItem.getAttribute('awesome'));
}

The console only spits out 'null' or ' ' depending on whether it has my awesome attribute.  I can prob make it work, but I thought it was supposed to resolve to true or false, boolean?

Found this in the docs

Boolean properties are set based on the presence of the attribute: if
  the attribute exists at all, the property is set to true, regardless
  of the attribute value. If the attribute is absent, the property gets
  its default value.

at https://www.polymer-project.org/1.0/docs/devguide/properties.html
So I assume I should be trying to get the value of the selectedItem's property > awesome.  How can I do this?

A: There's an important difference between properties and attributes. Properties are JavaScript properties on the DOM object. Attributes basically provide a string valued key/value database that can be initialized from markup.
The Polymer docs you quoted are talking about properties. If a Polymer element has a property, awesome, listed in the properties object with a type of Boolean, it will deserialize to true or false as described.
This is a service Polymer provides because it's a common pattern for HTML elements. For example, if you set the id attribute on an HTML element, the browser automatically reflects that to the id property. But if you add a generic attribute that that element doesn't know about (like awesome), the attribute isn't reflected as a property.
If you want to test for the presence or absence of an attribute on any element (standard HTML or Polymer), use hasAttribute as @günter-zöchbauer said. According to MDN, getAttribute in all modern browsers returns null when the attribute is absent, but apparently this wasn't always true, so hasAttribute is probably safer, as well as clearer.
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

A: Maybe you want
this.$.pages.selectedItem.hasAttribute('awesome')


text:
Q: "__globals__" getting merged when using decorators? In the code below, func2 seems to have the __globals__ of func1 + also the symbols from contextlib. Can anyone elaborate how this globals merging works? IE, does it merge __dict__'s of all modules involved in defining the function? Also, what happens when there's a name conflict?
import contextlib

def func1():
    pass

@contextlib.contextmanager
def func2(args):
  pass

globals1 = set(func1.__globals__.keys())
globals2 = set(func2.__globals__.keys())

globals2.difference(globals1)

{'GeneratorContextManager',
 '__all__',
 '__file__',
 'closing',
 'contextmanager',
 'nested',
 'warn',
 'wraps'}

Using Python 2.7.10

A: Each function object will have __globals__ giving a reference to the global namespace of the module where the function was defined.
In your example, func1 is defined in your module and has the globals of that module.  You defined func2 in your module, but the contextmanager decorator wraps your function with another function.  That wrapper function is defined in contextlib, so when the decorator replaces func2 with the wrapped version, the resulting function has the globals of contextlib.  It does not have the globals of your module.
However, the wrapped function retains a reference to your original function, which still has the globals of your own module.  In your example this can be seen via func2.__closure__[0].cell_contents:
# func1 is not in func2's globals
>>> func2.__globals__['func1']
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    func2.__globals__['func1']
KeyError: u'func1'

# func1 is in the globals of the internally-stored wrapped version of func2
>>> func2.__closure__[0].cell_contents.__globals__['func1']
<function func1 at 0x0000000002B2B358>


text:
Q: Finding permutations for balanced distribution of values in lists Sorry for the bad title, but I don't know how to call this.
I have K lists, N elements in each, for example:

[8, 5, 6]
[4, 3, 2]
[6, 5, 0]

and I want to find such a permutation of the lists' elements, so that the sum of elements in first column, second column etc are as close to each other as possible (so the distribution is "fair").
In my example that would be (probably):

      [8,  5,  6]
      [4,  2,  3] -- the lists contain the same values
      [0,  6,  5]    just in different order
sums: 12, 13, 14

Is there some more elegant way than finding all the permutations for each list, and brute-force finding the "ideal" combination of them?
I'm not asking for code, just give me a hint how to do it, if you know.
Thanks!
ps. the lists can be quite large, and more of them - think ~20x~20 max.

A: If you can accept an approximation, I would do it iteratively :

*

*Sort matrix lines by descending weight (sum of line elements).
Edit : Sorting first by max element in line could be better.

*Each time you are going to add a new line to your result matrix, put smaller elements into higher columns.

*Order lines of your result matrix back to their initial state (if you have to).

It works with your example, but will obviously not be always perfect.
Here is an example (javascript)


text:
Q: How to Parse XML File in PHP The XML file is here.
How can I get the source content in this XML file?

A: PHP already includes XML parsers in the core or as extensions (i recommend SimpleXML).
Try to use it and then ask us if you have any specific problem.

A: Actually there are four relatively simple ways to read an XML file:

*

*DOM which uses the DOM API (and therefore has to load the whole document into memory)

*SimpleXML which provides a very simple and elegant way to parse XML documents (but lacks a lot of document manipulation methods), it also loads the whole document into memory

*XMLReader is a stream-based XML pull parser. It's usage is not as intuitive as the usage of both other options above, but it can be a life-saver when you have to parse large documents (as it does not need to load the whole document into memory and operates on the XML stream). The nice thing is that it allows you to inter-operate with the DOM via XMLReader::expand().

*XML Parser is a very low-level component which allows you to create SAX parsers, which means that you define handler functions which will be called when reading the XML file; essentially they have the same benefits as the XMLReader (operating on streams)

My personal favorites are:

*

*SimpleXML when parsing relatively small XML files without the need to modifiy them

*XMLReader when parsing large XML files


text:
Q: How to display PHP errors in code output? When executing a PHP page through browser , we will just get the output but not the errors in code.
how can i view the errors occurred by the code in the backend??
I am using the following in the code for error reporting..
error_reporting(E_ALL | E_ALL);

A: ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);

A: Try -1. From the documentation, "Passing in the value -1 will show every possible error, even when new levels and constants are added in future PHP versions."
// Report all PHP errors
error_reporting(-1);

If that doesn't work, try to do an ini_set:
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

A: Inside your php.ini, set the display_errors to On:
display_errors = On

Then restart your web server.


text:
Q: CDT : Parsing enumerations, enumerators and corresponding values I'm developing an extension of eclipse CDT plug-in which has to parse the c++ code and find all

*

*enumerations (names)

*enumerators (names)

*enumerator values (numbers)

Suppose .cpp file contains following text
enum SomeEnum
{
   One            = 0,
   Two            = 1,
   Three          = 2,
   Four           = 3,
   maxNum
};

The pluging should output following :

*

*Enumeration - SomeEnum

*Enumerators - One, Two, Three, Four,    maxNum

*Values      - 0, 1, 2, 3,
The visitor method of ASTVisitor inherited class finds the enumerations this way
public int visit(IASTDeclaration declaration) {
    if (declaration instanceof IASTSimpleDeclaration) {

        IASTDeclSpecifier specifier = ((IASTSimpleDeclaration)declaration).getDeclSpecifier();

        if (specifier instanceof IASTEnumerationSpecifier) {

            IASTEnumerationSpecifier enumSpecifier = (IASTEnumerationSpecifier)specifier;
            IBinding binding = enumSpecifier.getName().resolveBinding();
            System.out.println(enumSpecifier.getName());
        }
    }
    return PROCESS_CONTINUE;
}

Question : How can I iterate over the enumerators and their corresponding values of found enumeration ?

A: Well figured out on my own
public int visit(IASTDeclaration declaration) {
    if (declaration instanceof IASTSimpleDeclaration) {
        IASTDeclSpecifier specifier = ((IASTSimpleDeclaration)declaration).getDeclSpecifier();
        if (specifier instanceof IASTEnumerationSpecifier) {
            IASTEnumerationSpecifier enumSpecifier = (IASTEnumerationSpecifier)specifier;
            // Get the current enumeration name
            String enumerationName = enumSpecifier.getName().toString();
            IASTEnumerator[] enumerators = enumSpecifier.getEnumerators();
            for (IASTEnumerator enumerator : enumerators)
            {
                System.out.println(enumerator.getName());
                if (enumerator.getValue() instanceof IASTLiteralExpression  ) {
                    System.out.println(enumerator.getValue());
                }
            }
        }
    }
    return PROCESS_CONTINUE;
}


text:
Q: as am not getting what is the functionality of below code Can someone explain me below function line by line
handleChange(e) {
          let fields = this.state.fields;
          fields[e.target.name] = e.target.value;
          this.setState({
            fields
          });

as my understanding

*

*we are creating a variable fields and storing the present state of fields in the variable because we cant mute the state.

*i don't have idea about  fields[e.target.name] = e.target.value;

*updating the fields

can someone explain me the above function line by line?

A: fields[e.target.name] this syntax is also used to access the Object Properties.
var obj = {name:'abc', color:'red'}
console.log(obj.name) // this print 'abc'
console.log(obj['name']) // also print 'abc'

with obj['xxx'] syntax you can dynamically read and set properties to the object.
reference https://www.w3schools.com/js/js_objects.asp
So in your problem fields variable take existing fields object from the local state. And in each event it create new property with that event target name and add that event target value as that new property value. if that property name already exist within the fields object then it only modified the value of that property.
So as in your list,

*

*is correct. With let fields = this.state.fields; it get previously stored values into the fields variable. without losing previous data

*this is what I explained above

*your answer is correct. update the state with old and new values

A: This code let's you dynamically change the value of a field in your component state by using object notation. object[]
By using fields[event.target.name] you're going to look for a field in your component state that matches the name of the element that's causing the event to occur. Then it looks like you're updating the value for that field with event.target.value
Why this is useful
Let's say you have a component where you want to retrieve multiple inputs from a user. Without object notation, you might end up writing very repetitive code like writing a different event handler for each input in order to determine what field to update in your component state:
BAD:
handleOnChange1 = (event) => (this.setState({userName: event.target.value}))
handleOnChange2 = (event) => (this.setState({lastName: event.target.value}))

However, by naming your elements and coordinating them with a matching field in your component state, you won't have to worry about writing additional event handlers as long as you use object notaton.
GOOD:
class UserForm extends React.Component{
   state = {
       firstName: "",
       lastName: ""
   }
   handleOnChange = (event) => {
      this.setState({
          [event.target.name]: event.target.value
      })
   }
   render(){
      return(
         <div>
             <input name="firstName" value={this.state.firstName} onChange={this.handleOnChange}/>
             <input name="lastName" value={this.state.lastName} onChange={this.handleOnChange}/>
         </div>
      )
   }

}


text:
Q: jQuery double event fire after post/get ok i've wracked my brain and others to figure out why this is happening in IE and latest version of FF.  It works in chrome.  i am but a novice developer and recently started using jquery.  so i dont even know if i'm going about this correctly.
its a basic form for the most part.  jquery ajax post() then get() to update the page.  once the page is loaded from get, the right hand nav/sidebar collapsible headings double fire and so do the action links in the action pane.  i've tried binding the click event with bind(), live(), and delegate().  it worked originally with bind but i had to rebind all my click events after the ajax call and i am trying to find a way around that.
i've set up a static version of the app that i'm building here:
http://ishiftdelete.com/pw_mkvi/ajax_wtf.htm
to test: click on the Edit Page link inside the actions page in the right-hand nav/sidebar.  this will open a model dialog with a form and submit button.

A: Ok so a friend of mine figured this out. Apparently scripts were being loaded twice.
BAD:
$.get(gurl, function (data) {
    var $response = $('
').html(data);
$('#mydiv').html($response.find('#mydiv').html()); //form
});

GOOD:
$.get(gurl, function (data) {
    var $response = $(data);
$('#mydiv').html($response.find('#mydiv').html()); //form
});

A: I know you've already solved this, but for future finders, you can add a wrapper around your
 like this:

Then you can simplify your situation with .load() and the element you're looking for, like this:
$("#myDivParent").load(gurl + " #myDiv");

That's it, if you pass the argument as url selector it'll get only that element from the response :)


text:
Q: How can I handle KeyError in python for my example Im making a telegram bot using Python and Firebase.
I get stucked at a KeyError:
2021-02-12 12:39:38,687 - telegram.ext.dispatcher - ERROR - No error handlers are registered, logging exception.
Traceback (most recent call last):
  File "C:\Users\Lil-Dredd\PycharmProjects\TelegramBot\venv\lib\site-packages\telegram\ext\dispatcher.py", line 442, in process_update
    handler.handle_update(update, self, check, context)
  File "C:\Users\Lil-Dredd\PycharmProjects\TelegramBot\venv\lib\site-packages\telegram\ext\conversationhandler.py", line 549, in handle_update
    new_state = handler.handle_update(update, dispatcher, check_result, context)
  File "C:\Users\Lil-Dredd\PycharmProjects\TelegramBot\venv\lib\site-packages\telegram\ext\handler.py", line 160, in handle_update
    return self.callback(update, context)
  File "C:\Users\Lil-Dredd\PycharmProjects\TelegramBot\bot.py", line 61, in start
    print(user.val()["chat_id"])
KeyError: 'chat_id'

Here is my code:
def start(update: Update, context: CallbackContext) -> int:
    global PauseKey, PauseStart, PauseState, PauseAllKey
    timenow = datetime.now()
    auth = firebase.auth()
    userx = auth.sign_in_with_email_and_password('drux@mail.com', '12345678')
    db = firebase.database()
    chat_user_client = update.message.from_user.username
    all_users = db.child("users").get()
    user_status = "none"

    for user in all_users.each():
        print(user.val()["chat_id"])
        if user.val()["chat_id"] == update.message.chat_id:
            user_status = "exist"
            userKey = user.key()
            break
    print(user_status)
    if user_status == "exist":
        text_back = "You was logged in, Welcome back "
    else:
        data = {"name": chat_user_client, "chat_id": update.message.chat_id}
        date = {"date": datetime.today().strftime('%Y-%m-%d-%H:%M:%S')}
        userKey= db.child("users").push(data)
        userKey = userKey.val()
        text_back = "User was create"

    update.message.reply_text(
    f'{text_back}{chat_user_client}',
    reply_markup=markup2
    )

    return CHOOSING

Error Block:
for user in all_users.each():
        print(user.val()["chat_id"])
        if user.val()["chat_id"] == update.message.chat_id:
            user_status = "exist"
            userKey = user.key()
            break

and this print  print(user.val()["chat_id"]) show 690953230 in console . Which is a correct chat id that is stocked in my firebase.
I tried to used await with asyncio library, for this line:
all_users = db.child("users").get()

async def start()
...
all_user = await db.child("users").get()
...

With async and await error was leaving but code didnt do expected stuff.
The code should do the following:
browse all users data and check if user_chat_id is already in database.
If chat_id is already in database then user exist and Im working with his table key. If user dosnt exist im creating his table and take his user key.
I get stucked for hours with this error and cant handle it on my own, please help.
Edit

Now I found that if my user exist the code is working fine.
I mean if my  chat_id is already in database i dont get any errors ,
if im deleting im data from database im getting keyError

A: I suggest you to use get while getting element from dictionary; because while dict["key"] gives error, dict.get("key") does not give error when the key doesn't exist. My suggestion is to update the error block as:
for user in all_users.each():
    chat_id = user.val().get("chat_id")
    if chat_id and  chat_id == update.message.chat_id:
        user_status = "exist"
        userKey = user.key()
        break

Furthermore, you should do some refactoring to enhance readability. For example in above block of code following assignment looks redundant:
userKey = user.key()

You can also extract user existance checking as another method:
def user_exists(all_users, msg_chat_id):
    for user in all_users.each():
        chat_id = user.val().get("chat_id")
        if chat_id and  chat_id == msg_chat_id:
            return true
    return false

Then use it in start method as:
def start(update: Update, context: CallbackContext) -> int:
    global PauseKey, PauseStart, PauseState, PauseAllKey
    timenow = datetime.now()
    auth = firebase.auth()
    userx = auth.sign_in_with_email_and_password('drux@mail.com', '12345678')
    db = firebase.database()
    chat_user_client = update.message.from_user.username
    all_users = db.child("users").get()

    if user_exists(all_users, update.message.chat_id):
        text_back = "You was logged in, Welcome back "
    else:
        data = {"name": chat_user_client, "chat_id": update.message.chat_id}
        date = {"date": datetime.today().strftime('%Y-%m-%d-%H:%M:%S')}
        userKey= db.child("users").push(data)
        userKey = userKey.val()
        text_back = "User was create"

    update.message.reply_text(
    f'{text_back}{chat_user_client}',
    reply_markup=markup2
    )

    return CHOOSING


text:
Q: How to loop though HTML and return id values I am using selenium to navigate to a webpage and store the page source in a variable.
from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get("http://google.com")

html1 = driver.page_source

html1 now contains the page source of http://google.com.
My question is How can I return html selectors such as id="id" or name="name".
EDIT:
For example:
The webpage I navigated to with selenium has a menu bar with 4 tabs. Each tab has an id element; id="tab1", id="tab2", and so on. I would like to return each id value. So I want tab1, tab2, so on.
Edit#2:
Another example:
The homepage on my webpage (http://chrisarroyo.me) have several clickable links with ids. I would like to be able to return/print those ids to my console.
So I would like to return the ids for the Learn More button and the ids for the links in the footer (facebookLnk, githubLnk, etc..)

A: If you are looking for a list of WebElements that have an ID use:
elements = driver.find_elements_by_xpath("//*[@id]")

You can then iterate over that list and use get_attribute_("id") to pull out each elements specific ID.
For name, its pretty much the same code. Except change id to name and you're set.

A: Thank you @stewartm you comment helped.
This ended up giving me the results I was looking for:
from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get("http://chrisarroyo.me")

id_elements = driver.find_elements_by_xpath("//*[@id]")

for eachElement in id_elements:
    individual_ids = eachElement.get_attribute("id")
    print(individual_ids)

After running the above ^^ the output listed each of the ids on the webpage specified.
output:
navbarNavAltMarkup
learnBtn
githubLnk
facebookLnk
linkedinLnk


text:
Q: Copy-pasted large folder but didn't have enough space. Cancelled the paste, but storage was taken up anyways I don't know if specifics of the folder are needed, but I had a large folder already downloaded on my C: drive. I copy and pasted it onto my desktop but there wasn't enough space for the download to finish so I cancelled the paste. After looking at my storage I saw that it was taken up even though I cancelled the paste. Is there a way I can find this partially downloaded folder, or undo this to get my storage back?

A: There are various Disk Space visualization tools, such as TreeSize or WizTree that can show you a visual representation of your disk and the folders and files using up the space on it.
You should start with Windows' own Disk Cleanup because it's there, and it's simple to use.
Next, you should check the destination folder. If the file was partially copied, the parts that copied before you canceled the copy will still be there.


text:
Q: Computing a moving maximum in BigQuery Given a BigQuery table with some ordering, and some numbers, I'd like to compute a "moving maximum" of the numbers -- similar to a moving average, but for a maximum instead.  From Trying to calculate EMA (exponential moving average) using BigQuery it seems like the best way to do this is by using LEAD() and then doing the aggregation myself.  (Bigquery moving average suggests essentially a CROSS JOIN, but that seems like it would be quite slow, given the size of the data.)
Ideally, I might be able to just return a single repeated field, rather than 20 individual fields, from the inner query, and then use normal aggregation over the repeated field, but I haven't figured out a way to do that, so I'm stuck with rolling my own aggregation.  While this is easy enough for a sum or average, computing the max inline is pretty tricky, and I haven't figured out a good way to do it.
(The examples below are of course somewhat contrived in order to use public datasets.  They also do the rolling max over 3 elements, whereas I'd like to do it for around 20.  I'm already generating the query programmatically, so making it short isn't a big issue.)
One approach is to do the following:
SELECT word,
  (CASE
    WHEN word_count >= word_count_1 AND word_count >= word_count_2 THEN word_count
    WHEN word_count_1 >= word_count AND word_count_1 >= word_count_2 THEN word_count_1
    ELSE word_count_2 END
    ) AS max_count
FROM (
  SELECT word, word_count,
    LEAD(word_count, 1) OVER (ORDER BY word) AS word_count_1,
    LEAD(word_count, 2) OVER (ORDER BY word) AS word_count_2,
  FROM [publicdata:samples.shakespeare]
  WHERE corpus = 'macbeth'
)

This is O(n^2), but it at least works.  I could also do a nested chain of IFs, like this:
SELECT word,
  IF(word_count >= word_count_1,
    IF(word_count >= word_count_2, word_count, word_count_2),
    IF(word_count_1 >= word_count_2, word_count_1, word_count_2)) AS max_count
FROM ...

This is O(n) to evaluate, but the query size is exponential in n, so I don't think it's a good option; certainly it would surpass the BigQuery query size limit for n=20.  I could also do n nested queries:
SELECT word,
  IF(word_count_2 >= max_count, word_count_2, max_count) AS max_count
FROM (
  SELECT word,
    IF(word_count_1 >= word_count, word_count_1, word_count) AS max_count
  FROM ...
)

It seems like doing 20 nested queries might not be a great idea performance-wise, though.
Is there a good way to do this kind of query?  If not, am I correct that for n around 20, the first is the least bad?

A: A trick I'm using for rolling windows: CROSS JOIN with a table of numbers. In this case, to have a moving window of 3 years, I cross join with the numbers 0,1,2. Then you can create an id for each group (ending_at_year==year-i) and group by that.
SELECT ending_at_year, MAX(mean_temp) max_temp, COUNT(DISTINCT year) c
FROM
(
 SELECT mean_temp, year-i ending_at_year, year
 FROM [publicdata:samples.gsod] a
 CROSS JOIN
  (SELECT i FROM [fh-bigquery:public_dump.numbers_255] WHERE i<3) b
 WHERE station_number=722860
)
GROUP BY ending_at_year
HAVING c=3
ORDER BY ending_at_year;

A: I have another way to do the thing you are trying to achieve. See query below
SELECT word, max(words)
FROM
  (SELECT word,
    word_count AS words
  FROM [publicdata:samples.shakespeare]
  WHERE corpus = 'macbeth'),
  (SELECT word,
    LEAD(word_count, 1) OVER (ORDER BY word) AS words
  FROM [publicdata:samples.shakespeare]
  WHERE corpus = 'macbeth'),
  (SELECT word,
    LEAD(word_count, 2) OVER (ORDER BY word) AS words
  FROM [publicdata:samples.shakespeare]
  WHERE corpus = 'macbeth')
group by word order by word

You can try it and compare performance with your approach (I didn't try that)

A: There's an example creating a moving using window function in the docs here.
Quoting:

The following example calculates a moving average of the values in the current row and the row preceding it. The window frame comprises two rows that move with the current row.

#legacySQL
SELECT
  name,
  value,
  AVG(value)
    OVER (ORDER BY value
          ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)
    AS MovingAverage
FROM
  (SELECT "a" AS name, 0 AS value),
  (SELECT "b" AS name, 1 AS value),
  (SELECT "c" AS name, 2 AS value),
  (SELECT "d" AS name, 3 AS value),
  (SELECT "e" AS name, 4 AS value);


text:
Q: Addition using next object's property value in List I want to make addition using next object's property value in list.
Here is the sample code.
public class MyClass
{
    public List<Model> modelList { get; set; }

    public MyClass()
    {
       modelList = GetModelList();
    }
    public List<Model> GetModelList()
    {
        return new List<Model>
        {
            new Model(){Number = 1, Total = 0},
            new Model(){Number = 2, Total = 0},
            new Model(){Number = 3, Total = 0},
            new Model(){Number = 4, Total = 0},
        };
    }
}
public class Model
{
    public int Number { get; set; }
    public int Total { get; set; }
}

In above case :
modelList[0].Total should be modelList[0].Number + modelList[1].Number
What could be the best way to achieve this ? Any help ?
Below is the code How I am achieving currently
for (int i = 0; i < modelList.Count - 1; i++)
{
    modelList[i].Total = modelList[i].Number + modelList[i + 1].Number;
}

A: I added a method ComputeTotal to show a solution
public MyClass()
{
    modelList = GetModelList();
    modelList = ComputeTotal(modelList);
}

private List<Model> ComputeTotal(List<Model> models)
{
    for (var i = 0; i < models.Count; i++)
    {
        var hasNext = (i + 1) < models.Count;

        // no computation if hasNext is false
        if (hasNext)
        {
            var currentNumber = models[i].Number;
            var nextNumber = models[i + 1].Number;
            models[i].Total = currentNumber + nextNumber;
        }

    }

    return models;
}

i know this is very explicit. But it clearly demonstrates the approach.

Update:
added the hasNext check to avoid System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.


text: Q: Discrete value - Normal distribution I have a data with discrete values and need to find if it is normally distributed. I plotted the graph and it looks normal and then I  performed  shapiro wilk test where the result were W = 0.78773, p-value < 2.2e-16, through which I concluded data is not normal. I just need guidance if I should be performing any more tests to find if the data is normally distributed, also I believe discrete values data can never be normal, is my understanding correct?


text:
Q: Find all interleavings of given strings that can be formed from all the characters of first and second string where order of characters is preserved I am trying to find all interleavings of given strings that can be formed from all the characters of first and second string where order of characters is preserved
I tried to use recursion.
// This code works[Snippet 1]
void func(string str1,string str2,string temp){

    if(!str1.length() && !str2.length()){
        cout << temp << endl;
        return;
    }

    if(str1.length()){
        func(str1.substr(1),str2,temp+str1[0]);
    }

    if(str2.length()){
        func(str1,str2.substr(1),temp+str2[0]);
    }
}

// This code does not work[Snippet 2]
void func(string str1,string str2,string temp){

    if(!str1.length() && !str2.length()){
        cout << temp << endl;
        return;
    }

    if(str1.length()){
        temp+=str1[0];
        func(str1.substr(1),str2,temp);
    }

    if(str2.length()){
        temp+=str2[0];
        func(str1,str2.substr(1),temp);
    }
}

The difference between snippet 1 and snippet 2 is that in snippet 2, I have appended the temp string with the character before passing it into the function. The second code gives result(string) whose size is greater than sum of length of both input strings.

A: Here's a version with plenty of cout and a way to track recursion depth.
#include <iostream>
#include <string>

using namespace std;

void func0(string str1, string str2, string temp, int depth) {

    if (!str1.length() && !str2.length()) {
        cout << temp << endl;
        depth--;
        return;
    }

    if (str1.length()) {
        cout << "depth: " << depth++ << "|temp: " << temp << '\n';
        func0(str1.substr(1), str2, temp + str1[0], depth);
    }

    if (str2.length()) {
        cout << "depth: " << depth++ << "|temp: " << temp << '\n';
        func0(str1, str2.substr(1), temp + str2[0], depth);
    }

    depth--;
}

void func1(string str1, string str2, string temp, int depth) {
    if (!str1.length() && !str2.length()) {
        cout << temp << endl;
        depth--;
        return;
    }

    if (str1.length()) {
        temp += str1[0]; //temp has
        cout << "depth: " << depth++ << "|temp: " << temp << '\n';
        func1(str1.substr(1), str2, temp, depth);
    }

    if (str2.length()) {
        temp += str2[0];
        cout << "depth: " << depth++ << "|temp: " << temp << '\n';
        func1(str1, str2.substr(1), temp, depth);
    }

    depth--;
}

int main(int argc, char* argv[]) {
    string a = "asd";
    string b = "qw";
    string c = "";

    cout << "func0\n";
    func0(a, b, c, 0);
    cout << "func1\n";
    func1(a, b, c, 0);

    return 0;
}

which yields this output for func0:
func0
depth: 0|temp:
depth: 1|temp: a
depth: 2|temp: as
depth: 3|temp: asd
depth: 4|temp: asdq
asdqw
depth: 3|temp: as
depth: 4|temp: asq
depth: 5|temp: asqd
asqdw
depth: 5|temp: asq
depth: 6|temp: asqw
asqwd
depth: 2|temp: a
depth: 3|temp: aq
depth: 4|temp: aqs
depth: 5|temp: aqsd
aqsdw
depth: 5|temp: aqs
depth: 6|temp: aqsw
aqswd
depth: 4|temp: aq
depth: 5|temp: aqw
depth: 6|temp: aqws
aqwsd
depth: 1|temp:
depth: 2|temp: q
depth: 3|temp: qa
depth: 4|temp: qas
depth: 5|temp: qasd
qasdw
depth: 5|temp: qas
depth: 6|temp: qasw
qaswd
depth: 4|temp: qa
depth: 5|temp: qaw
depth: 6|temp: qaws
qawsd
depth: 3|temp: q
depth: 4|temp: qw
depth: 5|temp: qwa
depth: 6|temp: qwas
qwasd

and this for func1:
func1
depth: 0|temp: a
depth: 1|temp: as
depth: 2|temp: asd
depth: 3|temp: asdq
depth: 4|temp: asdqw
asdqw
depth: 3|temp: asdq
depth: 4|temp: asdqd
depth: 5|temp: asdqdw
asdqdw
depth: 5|temp: asdqdw
depth: 6|temp: asdqdwd
asdqdwd
depth: 2|temp: asq
depth: 3|temp: asqs
depth: 4|temp: asqsd
depth: 5|temp: asqsdw
asqsdw
depth: 5|temp: asqsdw
depth: 6|temp: asqsdwd
asqsdwd
depth: 4|temp: asqsw
depth: 5|temp: asqsws
depth: 6|temp: asqswsd
asqswsd
depth: 1|temp: aq
depth: 2|temp: aqa
depth: 3|temp: aqas
depth: 4|temp: aqasd
depth: 5|temp: aqasdw
aqasdw
depth: 5|temp: aqasdw
depth: 6|temp: aqasdwd
aqasdwd
depth: 4|temp: aqasw
depth: 5|temp: aqasws
depth: 6|temp: aqaswsd
aqaswsd
depth: 3|temp: aqaw
depth: 4|temp: aqawa
depth: 5|temp: aqawas
depth: 6|temp: aqawasd
aqawasd

To help see the recursion look at the correct output when depth is 1 as the first level of a tree with 2 branches.  They should be just the first characters of each string.  Now each of those nodes get children for each remaining character. At the next lower level (depth 2), you add a character then each of those nodes gets children to create level/depth 3...etc.  It builds a trie when done correctly and temp only changes length once at each depth.
In both, you bottom out and print when you reach a leaf.
In the incorrect version, you'll see that length of temp is inconsistent in a given depth of the recursion. As already said but in a different way, appending to temp and storing it locally (which can also be thought of as appending while still in a row/level/depth of the trie) causes length of temp to grow both left to right and top to bottom.

A: I think you should use std::next_permutation(). For the first string, add for each character a 0 to a vector. Do the same for the second string with a 1. Now you have one vector to permutate. For each permutation, simply remap the indices back to the next character in first string if it is even and second when odd.
Example permutation : "cat", "bird" to (0 0 0 1 1 1 1), one permutation becomes (0 1 1 0 1 0 1 ) which you can remap to "cbiartd"


text:
Q: Conditionally display markup formatted text based on shiny input I'm trying to create an Rmarkdown that displays different amounts of text based on user input into a shiny application. I've made an basic example below. There are 2 text inputs and a checkbox. If the checkbox is false only the 1st text box value is printed to the markdown. If the checkbox is true then both values are printed. I want the output for both text boxes to appear like the 1st textbox output.
Ui:
library(shiny)
library(shinyjs)

ui <- fluidPage(

  titlePanel("Hello Shiny!"),

  sidebarLayout(

    sidebarPanel(

      textInput(inputId = "text1",
                label =  "1st text", value = "1st text"),

      checkboxInput(inputId = "checkBox", label = "Checkbox"),

      textInput(inputId = "input2",
                  label =  "2nd text", value = "2nd text"),

      downloadButton("download", "Download button")

    ),

    mainPanel(

      verbatimTextOutput("checkBoxValue")

    )
  )
)

Server:
library(shiny)
library(shinyjs)

server <- function(input, output) {

output$checkBoxValue <- renderText(input$checkBox)

Text1Value <- reactive({input$text1})
BoxValue<- reactive(input$checkBox)
Input2Value <- reactive({input$input2})

output$download <- downloadHandler(
  filename = "Test.docx",
  content = function(file) {
    tempReport <- file.path(tempdir(), "TestRMD.Rmd")
    file.copy("TestRMD.Rmd", tempReport, overwrite = TRUE)

    params = list(

      Text1Value = Text1Value(),
      BoxValue = BoxValue(),
      Input2Value = Input2Value()

    )

    rmarkdown::render(
      tempReport,
      output_file = file,
      params = params,
      envir = new.env(parent = globalenv()),
      quiet = FALSE
    )
  })
}

Rmarkdown:
---
title: "Test"
output: word_document
params:
    Text1Value: NA
    BoxValue: NA
    Input2Value: NA
---

```{r echo= FALSE, message = FALSE, include = FALSE}

library(shiny)
library(knitr)
library(latex2exp)

Text1Value<- params$Text1Value
BoxValue<- params$BoxValue
Input2Value<- params$Input2Value

```

# Value for text 1 is `r Text1Value`

```{r, echo=FALSE}
if(BoxValue == TRUE){
"Value for input 2 is `r Input2Value`"
}

```

Currently I can get the text from the second text output to appear conditionally, however it renders looking like R code. I want it to appear in the same format as the output for the 1st text input.
How would I accomplish this?

A: The the following in your Rmd file. You already are in a code block and don't need to have additional inline r formatting. You can use results = 'asis' in your block and also add the header (#) for identical formatting if you'd like:
```{r, echo=FALSE, results='asis'}
if(BoxValue == TRUE){
  cat("# Value for input 2 is", Input2Value)
}
```


text:
Q: net.proteanit.sql for gradle I'm trying to open same project in 3 build tools: Maven, Ant and Gradle.
It's simple project with sql database, I've already done this via Ant and Maven, unfortunately after adding rs2xml.jar to project module(as I added in Ant and Maven), and import (import net.proteanit.sql.DbUtils;) project doesn't compile. I don't receive any errors from Intellij (no code is red), during gradle task - compileJava the message appears:
"error: package net.proteanit.sql does not exist
import net.proteanit.sql.DbUtils;"
It points me to method: table.setModel(DbUtils.resultSetToTableModel(rs));
In build file I added dependecies like: open javafx, javafx graphics, java.swing, apche.ant.
{
public class ExaminationDetails extends JFrame implements ActionListener {
private JPanel contentPane;
private JTable table;
private JTextField search;
private JButton b1, b2, b3;

public void Book() {
    try {
        conn con = new conn();
        String sql = "select * from student";
        PreparedStatement st = con.c.prepareStatement(sql);
        ResultSet rs = st.executeQuery();

        ***table.setModel(DbUtils.resultSetToTableModel(rs));***
        rs.close();
        st.close();
        con.c.close();
    } catch (Exception e) {
    }

}

}
Any help will be appreciated.

A: if that jar file are in any online repo it would be better to use it but in case you want to use this file then modify your repo as follow
repositories {
    mavenCentral()
    flatDir {
        dirs 'lib'
    }

this will look for the jar inside that folder
and for your dependencies add this line to it
implementation name:'rs2xml'

notice name the file without the extension
Edit:
if there no certain rule that make you use gradle version 7.1 then it better to use the latest version 7.5
simply run this
 ./gradlew wrapper --gradle-version 7.5

from your project folder or even the ide terminal window
hope that help and have a nice day :)


text:
Q: VS 2017 error C2664 map insert attempt class   Thread
    {
    Sync::TYPE  sync;       // synchronous start/finish
    char        name[256];  // thread name
    thread      handle;     // thread handle
    HANDLE      abort,      // abort event handle
            start;      // start event handle

    public:
    Thread(const char *desc,Sync::TYPE ctrl,void (*fn)(void *),void *arg=NULL);
    Thread(Thread &th);
    Thread(void);
    ~Thread(void);
    HANDLE      AbortHandle(void) const     { return(abort); }
    HANDLE      StartHandle(void) const     { return(start); }
    thread::id  ID(void) const          { return(handle.get_id()); }
    void        Name(const char *value);
    const   char    *Name(void) const       { return(name); }
    void        Sync(Sync::TYPE value)      { sync=value; }
    Sync::TYPE  Sync(void) const        { return(sync); }
    thread      *ThreadHandle(void)     { return(&handle); }
    Thread      &operator=(Thread &th);
    };

class   ThreadList
    {
    map<thread::id,Thread>  TiL;

    public:
    ThreadList(void);
    ~ThreadList(void);
    HANDLE                  AbortHandle(void);
    void                    Clear(void);
    bool                    Close(thread::id id);
    void                    Close(map<thread::id,Thread>::iterator pos);
    map<thread::id,Thread>::iterator    Create(char *name,Sync::TYPE sync,void (*function)(void*),void *arg=NULL);
    map<thread::id,Thread>::iterator    Find(thread::id id)             { return(TiL.find(id)); }
    int                 Size(void) const                { return(TiL.size()); }
    void                    Start(map<thread::id,Thread>::iterator pos);
    HANDLE                  StartHandle(void);
    };

Now this code generates the error:
map<thread::id,Thread>::iterator    ThreadList::Create(char *name,Sync::TYPE sync,void (*function)(void*),void *arg)
{
pair<map<thread::id,Thread>::iterator,bool> result;
thread::id                  id;
Thread                      th(name,sync,function,arg);

id=th.ThreadHandle()->get_id();
**result=TiL.insert(make_pair(id,th));**
return(result.first);
}

The faulty line is in bold. The exact error message is this:
Error C2664:    'std::_Tree_iterator>> std::_Tree>::insert(std::_Tree_const_iterator>>,const std::pair &)': cannot convert argument 1 from 'std::pair' to 'std::pair &&'
What am I doing wrong here?
Kind regards, Vadim.
P.S.: Sorry, I should have clarified that moment. There are those definitions as well:
Thread::Thread(Thread &th)
{
sync=th.sync;
StrCopy(name,sizeof(name),th.name);
abort=th.abort;
start=th.start;
handle=move(th.handle);
}

Thread  &Thread::operator=(Thread &th)
{
sync=th.sync;
StrCopy(name,sizeof(name),th.name);
abort=th.abort;
start=th.start;
handle=move(th.handle);
return(*this);
}

A: Without a MCVE it is hard to say for sure, however looking at your example the most obvious thing I see is thread      handle in your Thread class. I am assuming that is a std::thread and if so the documentation for std::thread states

No two std::thread objects may represent the same thread of execution;
  std::thread is not CopyConstructible or CopyAssignable, although it is
  MoveConstructible and MoveAssignable.

To fix it you will have to implement move operators to ensure that your Thread class can be emplaced into containers.
You will then either be able to std::move(th) into the map container or directly construct it with map.emplace
I would suggest reading articles on when and how to implement copy/move as it is very easy to get these things wrong and the defaults may be good enough anyway.


text:
Q: More than one GPU on vast.ai Anyone with experience using vast.ai for cloud GPU computing knows if when renting more than one GPU do you need to do some setup to take advantage of the extra GPUs?
Because I can't notice any difference on speed when renting 6 or 8 GPUs instead of just one. I'm new at using vast.ai for cloud GPU computing.
I am using this default docker:
    Official docker images for deep learning framework TensorFlow   (http://www.tensorflow.org)

Successfully loaded tensorflow/tensorflow:nightly-gpu-py3

And just installing keras afterwards:
pip install keras

I have also checked the available GPUs using this and all the GPUs are detected correctly:
from keras import backend as K
K.tensorflow_backend._get_available_gpus()

cheers

A: Solution:
Finally I found the solution myself.  I just used another docker image with an older version of tensorflow (2.0.0), and the error disappeared.


text:
Q: GStreamer plugin to post progress to REST service For load balancing my GPU based GStreamer tasks I would like to send the percentage of work done on the GPU side to a remote task scheduler service.
I am not that deep into GStreamer, so my question is:
can this be done with already available plugins (e.g. progressreport ! tcpserversink), or do I have to create a special progressreport plugin, that outputs its messages to an http service?


text:
Q: How to limit the number of stomp clients in Spring, subscribing to a specific topic, based on a condition? I have been researching for a way to limit the number of clients who can subscribe to a specific stomp topic but have not yet understood, which could be the right approach according to my needs.
My use case is a game, which I am developing in Angular (ng2-stompjs stomp client) and Spring Boot Websockets (for the moment, the Spring in-memory message broker is in use).
The idea is that a user can be connected and subscribed to a "/lobby" stomp topic, and there he sees the opened game rooms, that could be in different statuses. for example, in-play or not started yet due to the low number of players joined.
I'd like to intercept and programmatically restrict a possible subscription of a client, to a specific "/room/{roomId}" topic, IF the MAX number of players has been reached, for example, 4. There could also be some simple client-side validation to restrict that, but I believe only client-side is not sufficient
So my main questions are:
How can a specific stomp topic subscription be intercepted in Spring?
Is it possible to return to the client-requestor some kind of error message that subscription could not be done?
I'd really appreciate your help, thank you in advance!

A: You could implement a StompEventListener which listens for subscriptions, in this we can have map mapping a destination(room number) versus the count of number of players in that particular room. if the count is already at max reject the subscription.
@Service
class StompEventListener() {
   private Map<String, int> roomIdVsPlayerCount = new HashMap<>();

   @EventListener
   public void handleSubscription(SessionSubscribe event) {
     StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
     String destination = accessor.getDestination();

     String roomId = destination.substring(...); //Parsed RoomID
     if(roomIdVsPlayerCount.get(roomId) == MAX_ALLOWED_PLAYERS) {
       //Throw exception which will terminate that client connection
         or, send an error message like so:
       simpMessagingTemplate.convertAndSend(<some_error_message>);
       return;
     }
     //So it is not at maximum do further logic to actually subscribe
       user and
     roomIdVsPlayerCount.get(roomId) += 1;
   }

   @EventListener
   public void handleUnsubscription(SessionUnsubscribe event) {
    ...
   }
}

Useful References:

*

*SessionSubscribeEvent (For handling the subscriptions)

*ConvertAndSend. (For sending the error messages to client.)

EDIT
Please try sending the exception from a channel Interceptor since the above did not send the exception , so that it gets propagated to the client. The map we defined earlier can be defined as a bean in a separate class accessible(with @Autowired) to both event handler(for incrementing and decrementing) and TopicSubscriptionInterceptor(for validation).
@Component
class TopicSubscriptionInterceptor implements ChannelInterceptor {
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel){
      StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
      String destination = accessor.getDestination();

      String roomId = destination.substring(...); //Parsed RoomID
      if(roomIdVsPlayerCount.get(roomId) == MAX_ALLOWED_PLAYERS) {
        //Throw exception which will terminate that client connection
      }

     //Since it is not at limit continue

    }
}

Useful reference for implementing a TopicSubscriptionInterceptor: TopicSubscriptionInterceptor


text:
Q: match and subtract chronologically Sample Data:
df <- structure(list(Customer.ID = structure(c(1L, 2L, 3L, 4L, 1L,
5L, 3L, 4L), .Label = c("A123", "B561", "C985", "D456", "Z893"
), class = "factor"), Month = c(1, 1, 1, 1, 2, 2, 2, 2), Score = c(12,
16, 8, 20, 16, 15, 6, 22), Increase = c(12, 16, 8, 20, 4, 16,
-2, 2)), .Names = c("Customer.ID", "Month", "Score", "Increase"
), row.names = c(NA, -8L), class = "data.frame")

Customer.ID Month Score Increase
     A123     1    12       12
     B561     1    16       16
     C985     1     8        8
     D456     1    20       20
     A123     2    16        4
     Z893     2    15       16
     C985     2     6       -2
     D456     2    22        2

What I need to do is get the value in column "Increase".  So essentially,match first column by their ID, and then chronologically by "Month" take the difference in the "Score" column to get the "Increase" value.  If there is no match, keep the value.
How do I accomplish this using any R package necessary?

A: An option is to use use dplyr package. First group data on Customer.ID and then arrange it on Customer.ID and Month. Now, all you have to perform is to subtract the previous value from the current Score. Since, OP has  mentioned that if no match found then same Score should be shown in Increase column hence use lag with default=0.
library(dplyr)

df %>% group_by(Customer.ID) %>%
  arrange(Customer.ID, Month) %>%
  mutate(NewIncrease = Score - lag(Score, default = 0))

# # A tibble: 8 x 5
# # Groups: Customer.ID [5]
#   Customer.ID Month Score Increase NewIncrease
#   <chr>       <int> <int>    <int>       <int>
# 1 A123            1    12       12          12
# 2 A123            2    16        4           4
# 3 B561            1    16       16          16
# 4 C985            1     8        8           8
# 5 C985            2     6      - 2         - 2
# 6 D456            1    20       20          20
# 7 D456            2    22        2           2
# 8 Z893            2    15       15          15

Data:
df <- read.table(text =
"Customer.ID | Month| Score| Increase
A123| 1| 12| 12
B561| 1| 16| 16
C985| 1| 8| 8
D456| 1| 20| 20
A123| 2| 16| 4
Z893| 2| 15| 15
C985| 2| 6| -2
D456| 2| 22| 2",
stringsAsFactors = FALSE, header = TRUE, sep = "|")


text:
Q: Android: Activity with Fragments (Fragments on Top) I am working on the last days of my Android project but I just have a problem. I have read many tutorials and every solution I read was a fail.
I would appreciate, if anyone can help me.
Problem: The Fragments are just on the top of the contentHome.xml. But I want, that the layout should chance to the fragment.
HomeActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
    this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) indViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.home, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.menu_search) {
        return true;
    }

    return id == R.id.location || super.onOptionsItemSelected(item);

}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_home) {

    } else if (id == R.id.nav_account) {
        AccountFragment accountFragment = new AccountFragment();
        FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction().replace(R.id.app_bar,accountFragment).commit();

    } else if (id == R.id.nav_favorite) {

    } else if (id == R.id.nav_inbox) {

    } else if (id == R.id.nav_help) {

    } else if (id == R.id.nav_settings) {

    } else if (id == R.id.nav_logout) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

}
contentHome.xml:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.test.john.test.HomeActivity">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.test.john.test.LoginActivity">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/test_logo"
        android:id="@+id/imageView2"
        android:layout_marginBottom="240dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:contentDescription="@string/testLogo"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/btn_login"
        android:textColor="@color/iconsText"
        android:text="@string/newMachineText"
        android:id="@+id/btn_NewMachine"
        android:gravity="center"
        android:clickable="true"
        android:layout_marginBottom="45dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/btn_login"
        android:textColor="@color/iconsText"
        android:text="@string/accountOverviewText"
        android:id="@+id/btn_AccountOverview"
        android:gravity="center"
        android:clickable="true"
        android:layout_marginBottom="20dp"
        android:layout_above="@+id/btn_NewMachine"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/btn_login"
        android:textColor="@color/iconsText"
        android:text="@string/searchMachineText"
        android:id="@+id/btn_SearchMachine"
        android:gravity="center"
        android:clickable="true"
        android:layout_marginBottom="18dp"
        android:layout_above="@+id/btn_AccountOverview"
        android:layout_alignParentStart="true" />
</RelativeLayout>

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

AccountFragment:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.test.john.test.AccountFragment">

<!-- TODO: Update blank fragment layout -->

<CalendarView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/calendarView" />

A: Maybe using a layout as a container inside contentHome will do the trick. Try reading this, maybe it will help you https://developer.android.com/training/basics/fragments/fragment-ui.html


text:
Q: Best way to select and traverse records in database I have a class Tweets which has some corresponding records stored in the repository.  I'm trying to grab the 10 latest tweets in the repository for a specific user and then traverse through them to analyze the date.
This is what I have come up with so far except for I am running into a issue where its saying that tweets does not have a parameter-less constructor..  But I'm a little confused because I'm not trying to initialize anything just want to take some records and traverse through them.
IEnumerable<Tweets> tweets = repository.Tweets.Take(10).Where(t => t.TwitterName == user.ScreenName) as IEnumerable<Tweets>;

foreach (var item in tweets)
{
    var date = item.Date;
}

Am I on the right track?  Is there a better way to do this?

A: You are returning tweets from repository, so each tweet in result should be constructed. That's why parameterless constructor is required.
Constructing entities and mapping database fields to properties of created objects is what ORM does for you. Btw, you can avoid entities construction, if you will return only dates from database.


text:
Q: Is this WSDL missing the methods?  <wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex" xmlns:wsa10="http://www.w3.org/2005/08/addressing" xmlns:tns="http://tempuri.org/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy" xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" name="myWCF" targetNamespace="http://tempuri.org/">
<wsdl:import namespace="" location="http://ip_address/Test/myWCF.svc?wsdl=wsdl0"/>
<wsdl:types/>
<wsdl:service name="myWCF"/>
</wsdl:definitions>

It is generated from a WCF.
Is it missing something ? because when i generate its client from Java, I don't get the methods, and they doesn't seem to be i the wsdl.
Can someone please confirm me if this wsdl is missing the methods, or that there is something wrong from the server side.
Thank you.

A: It depends on what is contained in the WSDL document that is included.
See the WSDL in the second row:
<wsdl:import namespace="" location="http://ip_address/Test/myWCF.svc?wsdl=wsdl0"/>


text:
Q: Bound on the distance in cartesian products Suppose we have a finite set in  $S \subseteq \mathbb{R}$.
Let
\begin{align}
d=\min_{\substack{a,b \in S \\ a \neq b}} \| a-b\|
\end{align}
where $\| \cdot \|$ is the Eucleadian distance. In other words $d$ is the smallest distance between points of $S$.
Next let
\begin{align}
S_n= S \times \cdots \times S
\end{align}
that is $S_n$ is a Cartesian product of $n$ copies of $S$.
My question: can we give a bound on minimum distance of $S_n$ defined as
\begin{align}
d_n= \min_{\substack{a,b \in S_n \\ a \neq b}} \| a-b\|
\end{align}
in terms of $n$ and $d$.
I think in general we have that $d_n=d$ but I don't know how to show it formally.

A: Using
$$|x_i|^2\leq \sum_{i=1}^{n}|x_i|^2 \Rightarrow |x_i|\leq \|x\|_2 \Rightarrow\|x\|_\infty\leq\|x\|_2$$
for $a,b\in S_n$, $a\neq b$, you can get
$$\|a-b\|_2 \geq \|a-b\|_\infty = \max_{1\leq i \leq n} |a_i-b_i| \geq d,$$
since there is at least one $i$ where $a_i\neq b_i$. As the above inequality is true for all such pairs, you get $d_n\geq d$.
On the other hand choose $a,b\in S$ such that $|a-b|=d$. Then for $c_1,\ldots, c_{n-1}\in S$ you get
$$\|(c_1,\ldots,c_{n-1},a)-(c_1,\ldots,c_{n-1},b)\|_2 = |a-b|=d$$
which implies $d_n\leq d$.
Combining the inequalities finally yields $d_n=d$.


text:
Q: How to achieve # in URL after submiting form? I have to submit a form which opens next page, but URL in next page has to be #/indes/string.
I have a page with input box and button. I already have logic to open new page, transfer parameter via:
var inputStr = document.getElementById('input_box').value;
var w = window.open("indes.html", '_blank');
w.input = inputStr;

and show it on new page with
<script> document.write(input);</script>

But I have to input this "string" to URL so the URL looks like:
#/indes/string

My URL should look like this at the end: www.mydomain.com/#/indes/string
How can I do this? Is this URL-rewriting? Can I even use this on my WAMP?

A: Check out sammy
Seems just like the thing you are looking for.

A: I think you need to set the Location Hash Property by setting window.location.hash.

A: instead of open a new window use location.hash but make sure you prevent default behavior by return false or if you use jquery use preventdefault.
function() {
  [your logic]
  location.hash = "#/indes/string";
  return false
}


text:
Q: How do I use map[string]struct{} So I am busy using http://godoc.org/github.com/samalba/dockerclient
Using CreateContainer (http://godoc.org/github.com/samalba/dockerclient#DockerClient.CreateContainer)
To setup a new container
containerConfig := &dockerclient.ContainerConfig{
    Image:        imageName,
    AttachStdin:  true,
    AttachStdout: true,
    AttachStderr: true}

containerID, err = docker.CreateContainer(containerConfig, containerName)

works correctly and I get a container, however, there is no exposed ports. Looking at the docker API(https://docs.docker.com/reference/api/docker_remote_api_v1.15/), I need to set
"ExposedPorts - An object mapping ports to an empty object in the form of: "ExposedPorts": { "/: {}" }"
Looking at the godoc for the Go dockclient lib I am using, I see you can pass it as
ExposedPorts    map[string]struct{}

But I have no idea on what to do here, from the docker api example passing :
 "ExposedPorts":{
             "22/tcp": {}
     }

is enough, so how do I do the struct bit in the my containerConfig?

A: Put this in your containerConfig
ExposedPorts: map[string]struct{}{
    "22/tcp": {},
}

Eg
containerConfig := &dockerclient.ContainerConfig{
    Image:        imageName,
    AttachStdin:  true,
    AttachStdout: true,
    AttachStderr: true,
    ExposedPorts: map[string]struct{}{
        "22/tcp": {},
    },
}

Playground


text:
Q: Mysql-Proxy Doesn't Failover (?) This is the first time I am using mysql-proxy and I am experiencing the weird behavior I was wondering if the community has tackled it before.
I have mysql-proxy (0.8.2) running on amazon linux (in ec2) connected to 2 mysql servers. My java client can connect to the proxy and load balancing works fine.
My problem is this: I have a client that is connected (via the proxy) to a server A. It works great until i test the fail-over. When I close server A and the client tries to execute simple insert command (on an already established connection), I was expecting the proxy to redirect the request to server B. However I am getting this exception:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure.

The client in this case is a Java program using mysql-connector-java-5.1.17-bin.jar
Any ideas how to solve this or am I missing anything here?

A: Here's an update on this issue, in case some else has the same problem.
It seems that mysql-proxy checks the status on the back-end server when the client connects to it. It doesn't perform any keepalive\heartbeat with the DBs. I have tried to force such behavior using lua scripts but failed miserably.
A potential alternative might be to use HAProxy and include xinted mysqlchecks. I haven't tried it personally. We'll probably end up building a proxy connection client that will wrap java.sql.Connection and will interact with mysql-proxy appropriately.
Let me know if you found other ways to achieve the above.


text:
Q: What does it mean, "eyebrows deep in every vice"? Michael denies the truth that horse racing is the only vice for Lord George.

Michael: I've always taken vice to be the definition of any criminal
  activity or wicked behavior involving prostitution, pornography or
  drugs, so, no...racing is definitely not your only vice, your
  lordship. I'd say you're eyebrows deep in every vice known to man.

What does it mean, "eyebrows deep in every vice"?
I find these line in The Gentlemen 2019

A: "You're eyebrows deep in every vice known to man" means that he engages excessively in every vice that you can think of: gambling, prostitutes, alcohol, drugs, etc.
This is similar to the expression "up to your eyebrows" which means that you are very deep into something - so deep that you are (metaphorically) buried up to your eyebrows. For example:

*

*"I'm up to my eyebrows in alligators!" = (humorous) I have so many tasks to accomplish that I can't keep up.

*"He's up to his eyebrows in debt" = he has way too much debt; he is very deeply in debt.


text:
Q: Backup Linux from Acronis True Image Home? I have a a software "Acronis True Image Home"
Is it possible to backup CentOS Linux?
on Windows do I need to create a bootdisk from Acronis and then boot it up on linux server?
I wanted to copy all the files from Server to External USB Hard Drive or via FTP

A: We need a little detail about what this computer is used for.
If it's for "home use" I use VERY happily remastersys for debian systems:
http://studyhat.blogspot.com/2010/05/creating-custom-ubuntu-live-cd-with.html
You can get the same result on your distro with PUNGI:
http://magazine.redhat.com/2007/05/31/remixing-fedora-7/
You can obtain a live cd of your personal computer: wow (and, of course, restore it).

A: I'm not having luck with Acronis True Image 2011 to recover a Ubuntu 11.04 disk.  I had good success with TI 2009, but it didn't support ext4, so I had to keep the old server on ext3.
Luckily I did a recovery test with this new server before depending on TI 2011.  The backups went well, all the .tib files verified as good, but they won't recover.  TI 2011 keeps losing connection to the .tib disk (and external USB) after failing to restore the partition.  I'd say test TI 2011 thoroughly before relying on it to backup Linux and/or look somewhere else.

A: I suggest you using clonezilla  to do that, it is a free software that do the same, you can download it and install on a bootable pen drive or burn a cd disk too boot-up from it.


text:
Q: WCF SetCertificate: how is it used I hava a self-hosted wcf service which is configured for ssl.
The certifiacate is bound to the port of the service by commandline,
using the 'netsh' command, e.g.:
netsh http add sslcert ipport=0.0.0.0:8000 certhash=XYZ appid={"ABC"}
This is described here:
http://msdn.microsoft.com/de-de/library/ms733791(v=vs.110).aspx.
It works as expeced.
Now I just discovered that there is a SetCertificate-Method:
http://msdn.microsoft.com/de-de/library/system.servicemodel.description.servicecredentials.servicecertificate(v=vs.110).aspx
So, I thought I can make use of this method, and do not need the netsh comamnd
for binding the certifiacte anymore.
But it does not work? SetCertificate seems to have no effect?
So what else is it used for?
Am I missing something?

A: I think I can answer my own question. Found the answer here:
http://msdn.microsoft.com/de-de/library/ms789011(v=vs.110).aspx

*

*If the transport is HTTP (using the WSHttpBinding), SSL over HTTP provides the transport-level security. In that case, you must configure the computer hosting the service with an SSL certificate bound to a port, as shown later in this topic.

*If the transport is TCP (using the NetTcpBinding), by default the transport-level security provided is Windows security, or SSL over TCP. When using SSL over TCP, you must specify the certificate using the SetCertificate method, as shown later in this topic.

So the SetCertificate method is only used when Transport is TCP. In my case it is Http, so I have to bind the Certificate to the port manually as I did.


text:
Q: How to hide a single header file from gcc I am compiling a c++ project and trying to find all what all functions from ncurses.h are used throughout the project.
I was wondering if I can tell gcc to not include specifically ncurses.h?

A: I ended up passing -D__NCURSES_H=1 on command line. ♂


text:
Q: Identify the test device for Admob I use the code below:
let request : GADRequest = GADRequest ()
request.testDevices = ["xxxxxxx",kGADSimulatorID]
But I am getting the below warning:

'testDevices' is deprecated: Use GADMobileAds.sharedInstance.requestConfiguration.testDeviceIdentifiers.

Do I use a syntax to remove the warning?

A: Swift Solution
It turns out the AdMob/GoogleAdManager deviceId can be found by computing the MD5 of the advertisingIdentifier. This way you can retrieve and use the test deviceId in code without having to previously have got a device's identifier from the console log.
To avoid the faff of using an ObjC-Swift bridging header (getting MD5 via <CommonCrypto/CommonCrypto.h>), I'd suggest using a Swift wrapper around the CommonCrypto framework, e.g this one:

*

*SwiftCrypto
Using the above framework (which adds an extension property to String for computing the MD5 hash), it is a simple matter of querying against:
GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers ?? []).contains(ASIdentifierManager.shared().advertisingIdentifier.uuidString.md5)

A: This is a modification to 10623169's answer.
To get a valid ID, for the current device, that can be set in "testDevices", get the MD5 of this: UIDevice.current.identifierForVendor?.uuidString
The asIdentifier value can be completely invalid if the user hasn't given permission for tracking. But the UIDevice.current.identifierForVendor is a valid UUID for the app, that will persist across launches (but perhaps not if you delete the app and reinstall).

A: You should use this:
GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers = ["YOUR IDENTIFIER PRINTED ON DEBUGGER"]

Instead of:
request.testDevices = ["YOUR IDENTIFIER PRINTED ON DEBUGGER"]

A: Use the syntax to remove the warning:
GADMobileAds.sharedInstance.requestConfiguration.testDeviceIdentifiers

A: You don't have to set this at all. As the AdMob Developer Doc says:

iOS simulators are automatically configured as test devices.

Source: https://developers.google.com/admob/ios/test-ads#enable_test_devices


text:
Q: How execute a combination key on node-webkit like c# sendkeys I made a Webkit app that register small codes on txt like snippets to use later on other apps. I can find my "snippet" and set the content on clipboard.
But also , I would like run "Ctrl+v" keys combination on Node-Webkit like the SendKeys function on C#.
Now I need press manually keys combination "Ctrl+v" to paste in another app.
Also i was thinking how run another file like a small exe program that do it the SendKey function and close it. But I prefer a node-webkit function without call other script or exe program.
It ´s posible to do it , and How can i do it ? Thanks guys.

A: Well, I was looking for an answer on the Internet without results.
But the best solution i 've implemented is to use a VBScript help file .
And it works well !!
The app calls the Paste function to execute the " paste.vbs " file.

paste.vbs
set shell = CreateObject("WScript.Shell")
WScript.Sleep 300
shell.SendKeys "^V"

myapp.js
var gui = require('nw.gui');
var win = gui.Window.get();

function getCommandLine() {
   switch (process.platform) {
      case 'darwin' : return 'open';
      case 'win32' : return 'start';
      case 'win64' : return 'start';
      default : return 'xdg-open';
   }
}
function Paste(){
    var sys = require('util');
    var exec = require('child_process').exec;
    exec(getCommandLine() + ' ' + "paste.vbs");
}
function useSnippet(content){
    var clipboard = gui.Clipboard.get();
    clipboard.set(content, 'text');
    win.minimize();
    Paste();
}

Now you can get the file contents for pasting into other applications.
If you want compatibility with other operating systems, you must use another command file similar to VBS
I use a list of files and reading passages content of a search list .
I can create a project on GitHub to load the code so that other people can use it or help me improve the code.


text:
Q: send whatsapp messages to someone not on contact list from android app I'm developing an application that can send message through whatsapp. I have implemented it by following this answer but it only works for contacts that on my contact list. It keeps error when i try to send message to contacts that are not in my contact list although the user already registered on whatsapp using that number (contact). Here is the message from whatsapp:

here is my code:
    try {
        Uri uri = Uri.parse("smsto: " + smsNumber);
        //Timber.e("smsNumber %s", uri.toString());
        Intent i = new Intent(Intent.ACTION_SENDTO, uri);
        i.setPackage("com.whatsapp");
        startActivity(Intent.createChooser(i, ""));

    } catch (Exception e) {
        Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT).show();
    }

is there any solutions ?

A: you can send via WhatsApp API even if he is not in your contact
String whatsappUrl = String.format("https://api.whatsapp.com/send?phone=%s&text%s",PhoneNumber,msg);
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(whatsappUrl));
            browserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            p_context.startActivity(browserIntent);


text:
Q: Ribbon instances per Document I am using  VSTO 3.0 and the ribbon designer gives me a ribbon that is apparently shared across documents.
So if I have Document specific state( number of XML marked up tags say) that needs to show up in the ribbon( or a toggle button ) then all documents seem to share the ribbon instance
How can I fix this
TIA

A: You can use Application.DocumentChange event or Application.WindowActivate event.
The first is fired then you change the current active document, but in the arguments there's no information about that document, so it's difficult to work with because you'll have to figure that out.
The latter is similar and it's fired every time you change of window but in this case it passes the current active document as an argument, so it's easier to change the ribbon if you need to check the value of any document property. That worked for me.

A: Hook into an appropriate event (such as when the active document is changed) within the document model, and in that event invalidate the appropriate ribbon button (you'll need the id of the element from the original Ribbon xml you load).
Then, when the refresh state callback for that button occurs, you can update the caption/image/enabled as required.


text:
Q: How can I show $\sqrt{2-\sqrt{2}} \in \mathbb Q\Big(\sqrt{2+\sqrt{2}}\Big)$?
How can I show $\sqrt{2-\sqrt{2}} \in \mathbb Q\Big(\sqrt{2+\sqrt{2}}\Big)$?

I know $2+\sqrt{2} \in \mathbb Q\Big(\sqrt{2+\sqrt{2}}\Big)$ and so I know $\sqrt{2} \in \mathbb Q\Big(\sqrt{2+\sqrt{2}}\Big)$. Thus, I know $2-\sqrt{2}\in \mathbb Q\Big(\sqrt{2+\sqrt{2}}\Big)$.
If $\alpha=\sqrt{2+\sqrt{2}}$, a basis for $\mathbb Q\Big(\sqrt{2+\sqrt{2}}\Big)$ over $\mathbb Q$ is $1, \alpha, \alpha^2, \alpha^3$. But I am not sure if/how I should use this.

A: Note that $\sqrt{2-\sqrt{2}}=\dfrac{\sqrt{2}}{\sqrt{2+\sqrt{2}}}$ and $\dfrac{1}{\sqrt{2+\sqrt{2}}}\in{\bf{Q}}(\sqrt{2+\sqrt{2}})$.


text:
Q: Socket hangup error in VercelCLI Nextjs deploy I am trying to deploy my next.js frontend using Vercel CLI but I'm getting an error
enter image description here
How to fix this?
version Vercel CLI 27.1.2

A: This is a common problem documented also on their github issue page, you can deploy ur project on vercel by uploading ur project on github (also in a private repository) and then going on https://vercel.com/ and linking it to your github repository, as there is not a good solution to the issue, people stated that after a few days it started working again. You may want to try go on this link and see if it gives you any response, if it doesen't you might be rate limited or your ip is blocked for some reason.