text:
Q: Passing $options to form builder in symfony2 I have this code in my form builder
->add('user', 'entity', array(
                'class' => 'Acme\Entity\User',
                'query_builder' => function(EntityRepository $er) use ($options) {
                        return $er->createQueryBuilder('u')
                        ->where('u.id = :id')
                        ->setParameter('id',$options['my'])
                        ->orderBy('u.name', 'ASC');},))

When I echo $options['my'] I get output as 1 inside the builder.
Now when I submit the form, I get NULL as the User object.
But if I use  ->setParameter('id',1) then it works fine.
Now if i use this
$options['test'] = 1 inside the build form and use
->setParameter('id',$options['test']) then it also work fine.
But ->setParameter('id',$options['my']) is not working directly. It is echoing fine as 1 in the form , so value is in that variable.
What should I do?

A: It is a common error of type. 1 is a string in the first case and a int in the second case. Try if this works:
->setParameter('id',intval($options['my']))

Your debug is really good though, but it is better to use var_dump rather than echo. You can also compare the types with gettype().
Compare var_dump($options['my']) with var_dump($options[test']).
Compare gettype($options['my']) with gettype($options['test']).


text:
Q: Why can't get the value stored in a variable of the controller here is my controller:
(function(){
  'use strict';

  angular
    .module('app')
    .controller('HomeController', ['Factory',
                                  HomeController]);

    function HomeController(Factory){

      var result = Factory.query();

      this.model = result[0];

    }
})();

in the view I get the value by doing so
div(ng-controller='HomeController as HomeCtrl')
  h3{{HomeCtrl.model}}

the problem is I don't get any value. I am totally sure the value is returned from the factory since I have already tested the Factory.query() and I got the results. In fact If I do in the following way and get the value in the view by doing HomeCtrl.result[0], I get the result.
(function(){
  'use strict';

  angular
    .module('app')
    .controller('HomeController', ['Factory',
                                  HomeController]);

    function HomeController(Factory){

      this.result = Factory.query();

    }
})();

A: You should use $scope to pass data to the view. That way, Angular will bind data and automatically update the view when your scope variable changes (your model variable is probably not available at the time the view renders due to an async call). Try something like this:
Controller
$scope.model = result[0];

View
h3{{model}}

A: Well, the factory's query method is most certainly an asynchronous method which immediately returns an empty array, but only populates it once the results of the asynchronous query are available (when it gets the response from an AJAX request, for example):
var query = function() {
    var result = [];
    $http.get('/somePath').success(function(data) {
        copyDataElementsTo(data, result); // 1 second later, the result is populated
    }
    return result; // returned immediately, empty
};

So, since your controller doesn't wait for the query result, it assigns result[0], which is undefined at this moment, to its model variable.
Your second way of doing works because, in that case, the view re-renders itself as soon as the response to the asynchronous request has been received, so it reevaluates result[0], which contains the elements received from the AJAX request.

A: Since you want to get the first element of the array once it is populated, you can do so in the callback:
Factory.query(function(result) {
    this.model = result[0];
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ask user to input desired mathematical operation I am trying to write a C program where user will input their desired mathematical operation.  I am able to do it but can't figure out how to execute the operation on two different numbers as the operation I stored in a char type variable called operation.

How I can solve this?

#include<stdio.h>
#include<conio.h>

int main(){

    char operation;
    int num1;
    int num2;

    printf("enter an expression \n");
    scanf("%c",&operation);
    printf("enter num1 \n");
    scanf("%d",&num1);
    printf("enter num2 \n");
    scanf("%d",&num2);

    printf("entered  expression is =");
    printf("%d%c%d \n",num1,operation,num2);

    printf("result is \n");

    // Here i had to put the - sign to ensure a subtraction, I want it to be automatic
    printf("%d%c%d = %d",num1,operation,num2,num1-num2);

}

A: What you need here, is a switch statement.
For every operation, you need to add a different case to perform that operation. Something like
switch(operation)
{
  case '+':
               //perform addition, num1+num2
  case '-':
               //perform subtraction, num1-num2
  case '*':
               //perform multiplication, num1*num2
  case '/':
               //perform division, num1/num2
}


text:
Q: Node - Database query callback not firing This may be a stupid question but I was not able to find an answer.
My db query (node -> PostgreSQL) is not firing the callback when the query function itself is called from another callback like this:
routes.js
router.post("/getsheet/", (req, res) => {

    googleAPI.getSheet(googleToken, req.body.sheetid).then((invoices) => {

        templateData.sheetData = invoices;
        templateData.sheetData.length = invoices.length;

        // When sheet is received, db query runs but it's callback won't
        // function takes an array and index
        db.query(invoices, 1).then((db_results) => {
            console.log(db_results);
            res.redirect("/");
        }).catch((db_error) => {
            console.error(db_error)
            res.redirect("/");
        });

    }).catch((error) => {
        console.error(error);
    });
});

db.js
const query = (data, index) => {
return new Promise((resolve, reject) => {
    // console log fires but not the callback function so it does not resolve or reject
    console.log("... querying index ... " + index + " customer: " + data[index].name);
    client.query(`SELECT * FROM customer WHERE customer_number=${data[index].customer_id};`, (err, res) => {
            // does not run this block
            if (!err) {
                resolve(res);
            } else {
                return reject(err);
            }
    });
});

}
Thanks! :)

A: Have you already established a connection?  You'd need to do that first before trying to run a query.  See an example here:
http://mherman.org/blog/2015/02/12/postgresql-and-nodejs/#.WeJpJWhSyUk
  pg.connect(connectionString, (err, client, done) => {
    // Handle connection errors
    if(err) {
      done();
      console.log(err);
      return res.status(500).json({success: false, data: err});
    }
    // SQL Query > Select Data
    const query = client.query('SELECT * FROM items ORDER BY id ASC;');
    // Stream results back one row at a time
    query.on('row', (row) => {
      results.push(row);
    });
    // After all data is returned, close connection and return results
    query.on('end', () => {
      done();
      return res.json(results);
    });
  });

Also, I'd highly recommend you use npm pg-promise.  Will simplify your life.
Lastly, you're also missing the point of promises.  I'd encourage you to use the newer async/await.  However if you don't want to and/or can't, at least see why you're just getting back into a callback hell... promises are in place to help reduce all the call back nesting.  Really you should reduce the nest level of your promises, like so:
router.post("/getsheet/", (req, res) => {

    googleAPI.getSheet(googleToken, req.body.sheetid).then((invoices) => {

        templateData.sheetData = invoices;
        templateData.sheetData.length = invoices.length;

        // When sheet is received, db query runs but it's callback won't
        // function takes an array and index
        return db.query(invoices, 1);
    }).then((db_results) => {
        console.log(db_results);
        res.redirect("/");
    }).catch((error) => {
        console.error(error);
        res.redirect("/");
    });
});


text:
Q: Sql - Filtering on certain category I am trying to write sql that would give me count of unique devices which appeared in category 'blue' and 'red' but not in any other category.
Below is my simple example. Answer for this question would be 3 devices (device 1, 2, 5).
If anyone could give me a tip, I would much appreciated. Thank you.
 device | category
--------+----------
      1 | blue
      2 | red
      3 | black
      4 | yellow
      4 | blue
      5 | red
      5 | blue

A: Use bool_and():
with my_table(device, category) as (
values
    (1, 'blue'),
    (2, 'red'),
    (3, 'black'),
    (4, 'yellow'),
    (4, 'blue'),
    (5, 'red'),
    (5, 'blue')
)

select device, bool_and(category in ('red', 'blue'))
from my_table
group by device
order by device;

 device | bool_and
--------+----------
      1 | t
      2 | t
      3 | f
      4 | f
      5 | t
(5 rows)

Your query may look like this:
select device
from my_table
group by device
having bool_and(category in ('red', 'blue'))
order by device;

A: One approach is to join your table to an aggregation query which identifies matching devices.
WITH cte AS (
    SELECT Device
    FROM yourTable
    GROUP BY Device
    HAVING SUM(CASE WHEN category NOT IN ('blue', 'red') THEN 1 ELSE 0 END) = 0
)

SELECT t1.Device, t1.Category
FROM yourTable t1
INNER JOIN cte t2
    ON t1.Device = t2.Device;

We can also use SUM as an analytic function:
SELECT Device, category
FROM
(
    SELECT Device, category,
        SUM(CASE WHEN category NOT IN ('blue', 'red') THEN 1 ELSE 0 END) OVER
            (PARTITION BY Device) color_sum
    FROM yourTable
) t
WHERE color_sum = 0;

Demo

A: select distinct device from Test
where category in ('blue','red')
except
select distinct device from Test
where category in (select distinct category from test
                     where category not in ('blue','red'))

or if you need count:
select count(*)
from
(select distinct device from Test
where category in ('blue','red')
except
select distinct device from Test
where category in (select distinct category from test
                     where category not in ('blue','red'))) a


text:
Q: Field Service Lightning to track location and to auto change the status of the schedule appointment to Done A user goes to a scheduled appointment. He changes the status to arrived. When the user leaves the location, track his location and when they leave the location - auto change the status of the schedule appointment to Done.
How can we do this...


text:
Q: How to represent classes with hierachical inheritance in a relationnal database I have an abstract class "Person" which is inherited by a (non-abstract) class "Candidate", the latter has several subclasses : retained candidate (for interview), admitted candidate ... How can I represent that in database please?
Thank you

A: This is an incorrect use of inheritance. A person might play the role of a candidate but has not always been and always will be a candidate. Use composition. A person plays many roles, one of which can be candidate. They could later become an employee. And their status should not be a subtype either. Use a "status" column for that.
Something like this:
create table people (
  person_id int primary key,
  name text,
  ...
);

create table person_roles (
  person_id int references people(person_id),
  type text check (type in ('Candidate', '...') ),
  candidate_status text check (candidate_status in ('Retained','Admitted') ),

  primary key (person_id, type)
);

A correct use of inheritance would be Person extends AbstractLegalParty. Organization or Company would also extend AbstractLegalParty.

A: If there are not a lot of data items, just make a single table with a type field. If there are lots of columns or variations, make tables for the variants and link them to a master table.


text:
Q: TigerGraph modeling: "composite" vertex possible? I am exploring TigerGraph and was wondering how to model the following construct. Suppose I have a Work that has 1 or more Authors. Each Author is a Person who is affiliated to an Organisation during a certain period. Instead of connecting a Work to a "Person" I want to connect the Work to the "Person being affiliated to an Organisation".
Maybe the following image helps.

The Work should be connected to the "composite" combination of person and organisation instead of just to the person.
One way to solve this is to create an "EmployedPerson" vertex class like this:

This is clearly not as "graph-like" as I would want it to be - it makes more sense to add a period attribute to the edge connecting Person and Organisation and connect Person to the edge (in the 1st image) than to create an additional class EmployedPerson (in the 2nd image).
As a beginner with TigerGraph, I could not find any examples of this pattern in the documentation & was wondering what is the most natural fit (e.g. for storing / querying purposes down the road).

A: If it is important to link the person's authorship of a work item with the person's employment (i.e. to highlight the fact that the work was authored during a given employment period), then yes, you need a vertex type linking these three things together.
Although I would call it employment rather than employedPerson, but it's a question of taste/preference.
This link vertex type should contain the start and end date/time of the employment, and you would probably need to generate a primary ID for this by concatenating a few things together (like person ID + a serial number, or person ID + company ID + start_date), rather than using a surrogate key (typically a number).


text:
Q: JAX-WS return empty lists I'm new in web services. I have faced some problem.
At the server side i'm using spring-ws. At the client side i'm using jax-ws.
With wsimport tool i have generated java classes according to my wsdl.
Everything works fine, but for some reason jax-ws does not parse arrays and list correctly, all lists are empty
I'm absolutely sure, that response is form correctly, tested it with soapui, also i'm using logging interceptor to log outcomming responses.
Below is the snippets of response
response looks like
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <SOAP-ENV:Body>
      <firstElementResponse>
         <name>hello world text</name>
         <name>hello world text</name>
         <name>hello world text</name>
      </firstElementResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

and the snippets of wsdl

<xs:complexType name="sayHelloResponseType">
  <xs:sequence>
    <xs:element maxOccurs="unbounded" minOccurs="0" name="name" type="xs:string"/>
  </xs:sequence>
</xs:complexType>

To generate client code i use wsimport.
SayHelloResponseType resp = serv.sayHello(r);
List<String> name = resp.getName();
System.out.println(name.size());

Thank you. Any help will be highly appreciated.

A: Seems it's just an invalid body of response, that does not math wsdl shema. Neither spring-ws neither jax-ws throws exception. It simply parse invalid data to empty list without any warrnings.
org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor saved my day
probably i have to tweak logging for jax-ws to avoid it next time

A: I just answered a similar question in How can I handle Castor unmarshaling of SOAP messages when the namespace is defined inside the operation tag? - if you're using Spring-WS, you're writing contract-first web services, so make sure you really nail that contract down. Put all your elements in a namespace, make sure your XSD schema expects elements to be qualified, and declare ns-uri and ns-prefixes in your Castor mappings. It's worth the effort.


text:
Q: Why isn't it possible to use fractional weights for Kruskal-Wallis test? When I try to run a Kruskal-Wallis test on a sample with fractional weights, SPSS throws the following warning:
Frequency weight data values must be positive integers.
Positive non-integer frequency weight data values are encountered.
These values are rounded to the nearest integers for the analysis.

When I try to run the same analysis in R, it simply doesn't run unless I round the weights myself.
What's the reason behind this? How come the same thing doesn't apply in other non-parametric tests, such as correlations (e.g. Kendall-Tau)?


text:
Q: how to translate c header file to delphi 2006 How to translate the following?
1)
#ifndef __LVR_NET_SDK_H__
#define __LVR_NET_SDK_H__

#ifdef __LVR_NET_EXPORT__
#define LVR_NET_API  extern "C" __declspec(dllexport)
#else
#define LVR_NET_API  extern "C" __declspec(dllimport)
#endif

2)
typedef struct {
 DWORD dwAlarmInput;
         DWORD dwVideoLoss;
         DWORD dwMotionDetect;
 DWORD dwVideoCover;
 DWORD dwReserve[16];
}LVR_NET_ALARM_INFO, *LPLVR_NET_ALARM_INFO;

3)
LVR_NET_API DWORD __stdcall LvrNetGetSdkVersion();

Thanks.

A: (1):
Depends on if you only want to use this header to interface to the C lib, in that case you can safely ignore it.
(If you are translating a whole package to Delphi, and want to generate a DLL based on it, you'll need to add
something like {$ifdef  LVR_NET_EXPORT} export; {$endif} to the function declarations, and in the main library file (the one that starts with "library") add the function to the "exports" clause (again {$ifdef LVR_NET_EXPORT})
)
In short: ignore
(2):
  Type LPLVR_NET_ALARM_INFO = ^LVR_NET_ALARM_INFO
       LVR_NET_ALARM_INFO  = Record
                               dwAlarmInput,
                               dwVideoLoss,
                               dwMotionDetect,
                               dwVideoCover    : DWORD;
                               dwReserve       : array[0..15] of DWord;
                             end;
       TLVR_NET_ALARM_INFO = LVR_NET_ALARM_INFO; // not needed but Delphi style convention

This isn't necessarily enough, since the way the record is packed is not defined this way. But the original fragment also lacks information about packing.
3)
  function LvrNetGetSdkVersion:DWord;

or
  function LvrNetGetSdkVersion:DWord; stdcall; external 'dllname.dll' name 'LvrNetGetSdkVersion';

to import from a dll. Note the "name" part where you can adjust the case of the imported identifier

A: You could translate the structure like this:
type
  TLVR_NET_ALARM_INFO = record
    dwAlarmInput : Cardinal;
    dwMotionDetect : Cardinal;
    dwVideoCover : Cardinal;
    dwReserve array [0..15] of Cardinal;
  end;

var
  LVR_NET_ALARM_INFO :  TLVR_NET_ALARM_INFO;

and the function declaration:
interface

    function LvrNetGetSDKVersion: Cardinal; stdcall;

implementation

    function LvrNetGetSDKVersion; external 'nameofthedll.dll';

Everything untested though. I hope it helps
Also check out DrBob. There you can find the tool HeadConv which can automatically convert C-Header files to Delphi. Its nice to start with, but not perfect.


text:
Q: Regex to pull 2nd-level domain out of text My splunk logs contain the following data:
TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT , URL: http://www.rexegg.com/regex-boundaries.html, TEXT TEXT TEXT TEXT

I want to pull out only the "rexegg.com" but I currently get "www.rexegg"
Closest I've got: (?i)(?:http:\/\/|https:\/\/)(?P<test>(?<!,)\w*\.\w*)

A: Change your regex to this:
(?i)https?:\/\/(?:[^. ]+\.)*(?P<test>[\w-]+\.[\w-]+)

RegEx Demo


text:
Q: Which X.509 certificate to use for NodeMCU SSL connections? Wow, SSL authentication is overwhelming!
I am using a NodeMCU device (ESP8266) device to connect to a Microsoft Azure IoT Hub securely using the MQTT protocol.
Microsoft offer the ability to authorise clients using self-signed X.509 certificates.
This is explained in detail here: Using X.509 Certificates with IoT Hub
I have followed the example that Microsoft Azure give, using OpenSSL to generate my self-signed X.509 certificates.
I try the example Python script to test the connection as a client, using my new certs and this works very well. So I know that the process has been a success, as it is tested and working and I am able to publish and subscribe to my IoT Hub.
In order to get the NodeMCU device connecting as a client to the IoT Hub, I need to load a certificate for authentication. NodeMCU provides the facility to load a single CA Certificate (in PEM format) into the operating system.
This is documented here: NodeMCU TLS Documentation
The question is, which certificate should I use?
I have tried a handful of combinations from the OpenSSL output, but none appear to result in a successful handshake. I am poking and hoping at this stage and could do with some input from someone who knows their stuff.
The encouraging news is that NodeMCU recognises the certificates as X.509 certs but fails on the verification. So this leads me to believe that I have the incorrect cert loaded...

-0x2700 MBEDTLS_ERR_X509_CERT_VERIFY_FAILED
Certificate verification failed, e.g. CRL, CA or signature check failed.

A: You need to use RSA Client Side Certificate & Private Key on NodeMCU end to authenticate client using X.509 authentication.
You can place PEM formatted certificate and private key in NodeMCU flash and load them in SRAM. It is a good idea to enclose the certificate and private key in "EOF(" ")EOF" tags.
Hopefully you are using Arduino core for ESP8266, you can them make use of BearSSL to format certificate files for transport layer and associate with WiFiClientSecure object as follows:
BearSSL::WiFiClientSecure espClient;

BearSSL::X509List serverCertList(getCertificate());
BearSSL::PrivateKey serverPrivKey(getPrivateKey());
espClient.setClientRSACert(&serverCertList, &serverPrivKey);

where, getCertificate() & getPrivateKey() methods you should define to read certificate from flash (or pass character array containing PEM formatted Certificate and Private Key here instead). After this, you will be able to authenticate the client with the server if your certificate and private key belongs to valid chain.


text:
Q: Run Logstash in Java Program I have created indexes and fields in ElasticSearch.
I could successfully run Logstash config file to add data from MySQL database table into ElasticSearch using the following command :
bin/logstash -f [PATH TO LOGSTASH CONFIG FILE] -v

I need to run this command from my Java source code. How do I run this logstash config file from Java code?

A: import java.io.*;
class UserTest{
        public static void main(String[] args)
        {
                try
                {
                        String s = "";
                        String[] cmd = new String[]{"/bin/sh", "./logstash","-f","loggingConfFile.conf"};
                        Process processes = Runtime.getRuntime().exec(cmd);
                        BufferedReader stdInput = new BufferedReader(new InputStreamReader(processes.getInputStream()));
                        while ((s = stdInput.readLine()) != null)
                        {
                                System.out.println(s);
                        }
                }
                catch(Exception ex)
                {
                        ex.printStackTrace();
                }
        }
}

A: Try this code. It works.
        try {
        ProcessBuilder b1 = new ProcessBuilder("cmd.exe", "/c", "cd \"C:\\elk\\logstash-5.1.2\\bin\" && logstash -f first-pipeline.conf --config.reload.automatic");
        b1.redirectErrorStream(true);
        Process p1 = b1.start();
        BufferedReader r1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
        String line1;
        while (true) {
            line1 = r1.readLine();
            if (line1 == null) { break; }
            System.out.println(line1);
        }

        }catch(Exception e) {

        }

A: Try this and this works fine with few changes to the above mentioned code:
try {
            ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "logstash -f --Your file Path-- ");
            builder.redirectErrorStream(true);
            Process p = builder.start();
            BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line1;
            while (true) {
                line1 = r.readLine();
                if (line1 == null) { break; }
                System.out.println(line1);
            }

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


text:
Q: How do you add OpenId session data to a Django test client POST? I'm trying to test that a UserProfile model is created as a new User is registered in django_authopenid.
I don't understand how to add the Openid session data to the POST.
class UserTestCAse(TestCase):
  def test_register_should_create_UserProfile(self):
    from django.test.client import Client
    c = Client()
    response = c.post('/account/register/', {u'username': [u'john'], u'email': [u'john@beatles.com'], u'bnewaccount': [u'Signup']},)

    self.assertEqual(response.status_code, 302)

    user = User.objects.get( username ='john')
    self.assertTrue(user.get_profile())

A: Apparently, adding session data to the django.test.client.Client without using Client.login() is not so easy.
The easiest solution was to create a new RequestFactory class so I could build a Request with the OpenID session object.
    class RequestFactory(Client):
    """
    Class that lets you create mock Request objects for use in testing.

    Usage:

    rf = RequestFactory()
    get_request = rf.get('/hello/')
    post_request = rf.post('/submit/', {'foo': 'bar'})

    This class re-uses the django.test.client.Client interface, docs here:
    http://www.djangoproject.com/documentation/testing/#the-test-client

    Once you have a request object you can pass it to any view function,
    just as if that view had been hooked up using a URLconf.

    """
    def request(self, **request):
        """
        Similar to parent class, but returns the request object as soon as it
        has created it.
        """
        environ = {
            'HTTP_COOKIE': self.cookies,
            'PATH_INFO': '/',
            'QUERY_STRING': '',
            'REQUEST_METHOD': 'GET',
            'SCRIPT_NAME': '',
            'SERVER_NAME': 'testserver',
            'SERVER_PORT': 80,
            'SERVER_PROTOCOL': 'HTTP/1.1',
        }
        environ.update(self.defaults)
        environ.update(request)
        request = WSGIRequest(environ)
        handler = BaseHandler()
        handler.load_middleware()
        for middleware_method in handler._request_middleware:
            if middleware_method(request):
                raise Exception("Couldn't create request mock object - "
                                 "request middleware returned a response")
        return request

I used the RequestFactory method like this:
class UserProfileCreation(TestCase):
    def test_register_should_create_UserProfile(self):
        count = User.objects.count()
        print 'Original Users' + str(count)

        from forum.tests.request_factory import RequestFactory
        rf = RequestFactory()
        post_request = rf.post('/register/', {u'username': [u'john'], u'email': [u'john@beatles.com'], u'bnewaccount': [u'Signup'] } )

        from django_authopenid.util import OpenID
        openid_instance = OpenID('https://www.google.com/accounts/o8/id?id=AItOxxxxxxxxxxxxxxxxxA',
                                 1267727884,
                                 [u'openid.op_endpoint', u'openid.claimed_id', u'openid.identity', u'openid.return_to', u'openid.response_nonce', u'openid.assoc_handle'],
                                 )

        post_request.session['openid'] = openid_instance

        from django_authopenid.views import register
        response = register(post_request)

        print "after POST User count: " + str(User.objects.count())
        self.assertEqual(response.status_code, 302)
        user = User.objects.get( username ='john')
        self.assertTrue(user.get_profile())


text:
Q: ERROR executing python script with nohup after a while: selenium.common.exceptions.TimeoutException: Message: I am trying to run a bot on my linuxserver that checks prices, I used selenium in my python script. I run it with nohup in the backgroun but after a while I encounter the folowing error:
File "selenium_amazon.py", line 68, in <module>
    isProduct()
  File "selenium_amazon.py", line 63, in isProduct()
  File "selenium_amazon.py", line 22, in Product_functie
    EC.presence_of_element_located((By.ID, "button"))
  File "/usr/local/lib/python3.7/dist-packages/selenium/webdriver/support/wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

Also i can't find the file /usr/local/lib/python3.7/dis_packages/selenium/webdriver/support/wait.py on my server.
Thank you in advance for your answers!

A: I had the same problem!
execute your command( nohup python3 -u main.py > out.out & )
normally , open a second terminal and execute the command screen -r ( this will attach in the process the screen that selenium needs) . After that close the both terminal and check the size file from your logs. ( I use snowflake to connect in my terminals )

A: An implicit wait tells WebDriver to poll the DOM for a certain amount of time when trying to find any element (or elements) not immediately available. The default setting is 0 (zero). Once set, the implicit wait is set for the life of the WebDriver object.
from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(10) # seconds
driver.get("http://somedomain/url_that_delays_loading")
myDynamicElement = driver.find_element_by_id("myDynamicElement")

Use this link for more details


text:
Q: Dynamic SQL to load images from a directory New to this and very stuck! I am trying to load images into a database from a directory using the following code.
When I execute the SP I get the following form the print statements I have included;
USE [store]
GO
DROP PROCEDURE [dbo].[insert2img]
/****** Object:  StoredProcedure [dbo].[insert2img]    Script Date: 07/08/2009 15:36:15 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROC [dbo].[insert2img]
as
Begin
   Declare @img1 as varbinary(max)
    Declare @dircmd as varchar(max)
             DECLARE @filename varchar(100)
  DECLARE @filepath varchar(100)
  DECLARE @maxRowID int
   DECLARE @count int
  DECLARE @tempXMLFileName table (RowId int identity(1,1), name varchar(100))
            Declare @sql as varchar(max)
        Set @count = 1
        Set @dircmd = 'MASTER..XP_CMDSHELL "dir/b '+ 'C:\Images\*.*"'

    INSERT
      @tempXMLFileName exec (@dircmd)
        SET @maxRowID = (SELECT max(RowId) FROM @tempXMLFileName)
WHILE @count <= @maxRowID
 BEGIN
          SET @filename = (SELECT name FROM  @tempXMLFileName WHERE [RowId] = @count)
          Print @filepath
          Set @filepath = 'C:\Images\'+@filename
                Set @sql = 'Insert into dbo.aaaimg (sno,imgdate,imgname,img)
                            Select '' @count'',getdate(),''Image'',
                            BulkColumn from Openrowset(Bulk ''' + @filepath + ''',Single_Blob) as tt  '
        print @sql
        Print @count

        Exec (@sql)

        Set @filepath=' '
        print @filepath
        Set @count = @count + 1

end
end

The output when I execute the SP with a few print statements is listed below;
Insert into dbo.aaaimg (sno,imgdate,imgname,img)
                            Select ' @count',getdate(),'Image',
                            BulkColumn from Openrowset(Bulk 'C:\Images\n0501.jpg', Single_Blob) as tt
1

(1 row(s) affected)

My issue is that I am trying to insert the value of @count into the db, but instead I end up with the actual word @count in the db and not the value. I assume it is to do with the delimiters, but I can't get the combination correct.
Thanks,
James.

A: You'd need to concatenate the @count variable into the @sql variable like this:
Set @sql = 'Insert into dbo.aaaimg (sno,imgdate,imgname,img)
Select ' + CAST(@count AS VARCHAR) + ',getdate(),''Image'',
BulkColumn from Openrowset(Bulk ''' + @filepath + ''',Single_Blob) as tt '

Having said that I'd raise the point that it's not recommended storing images in SQL Server itself. Better to store the path of the image rather than the image itself in the db.


text:
Q: Djangothumbnails app issue I an using this plugin to generate thumbnails. But somhow I couldn't make it work. The models work well, as images can be uploaded from the admin interface, even thumbnails get generated. I uploaded an image named "myphoto.jpg". The view I have is this.
def mainpage(request,slug):
    page = get_object_or_404(MainPage, slug=slug)
    image = get_object_or_404(Image)
    return direct_to_template(request, 'flatpage.html',
        extra_context={
            'page':page,
            'image':image,
        })

I have defined the class in models as "Image". I had this in the template:
<img src="{% image.photo.myphoto_125x125 %}"> But the template shows error.
This is my model:
class Image(models.Model):
    title = models.CharField(max_length=100)
    photo = ImageWithThumbsField(upload_to='images/', sizes=((125,125),(200,200)))
    # second_photo = ImageWithThumbsField(upload_to='site_media/images')

    def __unicode__(self):
        return self.title

The second field, "second_photo" I have commented out as it created duplicate copy of the main image. Even I am looking for a way to create entry for actual unsized image in the first field itself.

A: I havent tried this app, but I am using PIL to create thumbnail versions of uploaded images, and using a def in the model to retrieve the path to the thumbnail for display.   This may be more of a manual approach than you are looking for but it works ok for me.  You can override the save method on your model (which has your FileField) or send a post_save signal to a def to create the thumbnail.
But curious to know if this app you are using adds some useful functionality over this manual approach.

A: Somehow I got it working. Instead of creating a separate class, I used this line photo = ImageWithThumbsField(blank=True, upload_to='images/', sizes=((125,125),(200,200))) in my blog class. And I used the line {{% post.photo.url_125x124 %} in my index.html template.


text:
Q: how I can insert data from database into below array? how can I insert data from the database into the below array? I've tried several ways but I still fail.
I want to insert value data from the database into an array
class topsis {
public $alternatif = array();
public $kriteria = array();

public function __construct()
{

    // data kriteria
    array_push($this->kriteria, array('Nilai Akademik', 5, 'Benefit'));
    array_push($this->kriteria, array('Historis Project', 4, 'Benefit'));
    array_push($this->kriteria, array('Pelatihan', 3, 'Benefit'));
    array_push($this->kriteria, array('Minat', 4, 'Benefit'));
    // data alternatif
    array_push($this->alternatif, array('Sistem Pakar', 5, 1, 2, 5));
    array_push($this->alternatif, array('Data Mining', 5, 1, 3, 5));
    array_push($this->alternatif, array('SPK', 5, 1, 3, 4));
    array_push($this->alternatif, array('Citra', 4, 1, 3, 3));
    array_push($this->alternatif, array('Jaringan Komputer', 5, 4, 3, 4));
}

public function pembagi()
{
    $this->pembagi = array(0, 0, 0, 0);
    foreach ($this->alternatif as $a) {
        for ($i = 0; $i < count($this->kriteria); $i++) {
            $this->pembagi[$i] += pow($a[$i + 1], 2);
        }
    }
    for ($i = 0; $i < count($this->pembagi); $i++) {
        $this->pembagi[$i] = round(sqrt($this->pembagi[$i]), 9);
    }
}

A: first of all, you need to create a connection with the database. You can do this by choosing a procedural way, using libraries and modules specific to your database, or an object-like way, in which you use a standard interface to interact with it, the PDO (Php Data Object). Now, you can choose one option based on the db you use and how you'd like to interact with it.


text:
Q: Axiomatizable classes Are the statements below true or false:

*

*The class of finite sets is axiomatizable

*The class of infinite sets is axiomatizable

*The class of infinite sets is finitely-axiomatizable

*The class of fields of characteristic 0 is axiomatizable

*The class of fields of characteristic $\neq$ 0 is axiomatizable

*The class of fields of characteristic 0 is finitely-axiomatizable

I think I need to use the following criterion:
Let $\mathcal{F}$ be a non-trivial ultrafilter on $\mathcal{P}(\mathbb{N})$ and $\mathcal{K}$ a class of structures of the same (countable) signature. Then $\mathcal{K}$ axiomatizable iff $\mathcal{K}$ closed under elementary equivalence and closed under ultraproducts modulo $\mathcal{F}$.


text:
Q: Which port should I use for SQL Server on Docker with runner in bitbucket? I'm using a python-mssql image to restore a .bak file on Bitbucket. This is the yaml file that I create:
image: diegonachon/mssql_python_sqlcmd
env:
- ACCEPT_EULA = Y
- SA_PASSWORD = 5tr0ngP455
pipelines:
custom:
run:
- step:
name: restauration
runs-on:
- 'self.hosted'
size: 8x
script:
- pip install pysftp
- pip install pyodbc
- pip install psycopg2
- mkdir /bak_db/
- python dowload_bak_file.py
- python restore_file.py

In download_bak_file.py I download a .bak file that I'll restore. Then, in restore_db.py, I restore it with this code:
import os
os.system(''' sqlcmd -S localhost -U SA -Q'''
''' "Restore DATABASE data_base FROM DISK = '/bak_db/data_base.bak' \
WITH MOVE 'data_base' TO '/bak_db/data_base.mdf', \
MOVE 'data_base' TO '/bak_db/data_base.ldf' " \
-P 5tr0ngP455 ''')

But I get these errors:

Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : Login timeout expired.
Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : TCP Provider: Error code 0x2AF9.
Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.

What I've seen, is a port problem, so I assume that I should change "localhost" with something else. Is it or I'm missing something?

A: Never use localhost in docker configs. In dockers, localhost is inside the docker container itself. If you want to connect to a database, you should use its service name or machine IP.


text:
Q: nosetests 'cannot import name mkdir' im trying to use nose (NoseGAE) to test my GAE app but it fails with an import error.
cant really understand why because what it fails to import is python builtin stuff.
im actually testing a simple wsgi app with 1 handler which writes out 'hello world'.
does anyone understand whats going on? im on mac osx snow leopard
this is the traceback:
    Traceback (most recent call last):
  File "/Library/Python/2.6/site-packages/nose-0.11.4-py2.6.egg/nose/loader.py", line 382, in loadTestsFromName
    addr.filename, addr.module)
  File "/Library/Python/2.6/site-packages/nose-0.11.4-py2.6.egg/nose/importer.py", line 39, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/Library/Python/2.6/site-packages/nose-0.11.4-py2.6.egg/nose/importer.py", line 86, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/Users/pepe/DEV/nosetests/tornado/testing.py", line 21, in <module>
    from tornado.httpclient import AsyncHTTPClient
  File "build/bdist.macosx-10.6-universal/egg/nosegae.py", line 204, in load_module
    return super(HookMixin, self).load_module(fullname)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1289, in Decorate
    return func(self, *args, **kwargs)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1939, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1289, in Decorate
    return func(self, *args, **kwargs)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1841, in FindAndLoadModule
    description)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1289, in Decorate
    return func(self, *args, **kwargs)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1792, in LoadModuleRestricted
    description)
  File "/Users/pepe/DEV/nosetests/tornado/httpclient.py", line 28, in <module>
    import pycurl
  File "build/bdist.macosx-10.6-universal/egg/nosegae.py", line 204, in load_module
    return super(HookMixin, self).load_module(fullname)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1289, in Decorate
    return func(self, *args, **kwargs)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1939, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1289, in Decorate
    return func(self, *args, **kwargs)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1841, in FindAndLoadModule
    description)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1289, in Decorate
    return func(self, *args, **kwargs)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1785, in LoadModuleRestricted
    return source_file.load_module(submodule_fullname)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/dist/py_zipimport.py", line 213, in load_module
    exec code in mod.__dict__
  File "/Library/Python/2.6/site-packages/pycurl-7.19.0-py2.6-macosx-10.6-universal.egg/pycurl.py", line 7, in <module>
    __bootstrap__()
  File "/Library/Python/2.6/site-packages/pycurl-7.19.0-py2.6-macosx-10.6-universal.egg/pycurl.py", line 3, in __bootstrap__
    import sys, pkg_resources, imp
  File "build/bdist.macosx-10.6-universal/egg/nosegae.py", line 204, in load_module
    return super(HookMixin, self).load_module(fullname)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1289, in Decorate
    return func(self, *args, **kwargs)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1939, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1289, in Decorate
    return func(self, *args, **kwargs)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1841, in FindAndLoadModule
    description)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1289, in Decorate
    return func(self, *args, **kwargs)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1785, in LoadModuleRestricted
    return source_file.load_module(submodule_fullname)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/dist/py_zipimport.py", line 213, in load_module
    exec code in mod.__dict__
  File "/Library/Python/2.6/site-packages/setuptools-0.6c12dev_r85381-py2.6.egg/pkg_resources.py", line 24, in <module>
    from os import utime, rename, unlink, mkdir
ImportError: cannot import name mkdir

A: Google app engine doesn't provide mkdir, there's no writeable filesystem.
http://code.google.com/p/appengine-monkey/issues/detail?id=25 is someone else with the same problem.


text:
Q: Exchanged HDD in MacBook Pro - OS X installation disk shows prohibitory sign I exchanged the HDD in my 2007 MacBook Pro and removed the DVD drive because it was making a terrible noise every time I booted the MacBook.
The new HDD is a Corsair Force F120 SATA SSD. I formated it as HFS+.
Every time I try to launch an OS X Lion installation disk or USB stick I get the grey prohibitory sign and the machine shuts down after a while.
When I connect the old harddrive (with OSX still on it) I'm able to boot it up successfully.
Any ideas what is wrong?

A: it is greyed out because it is in the wrong file format => ntfs
you should use disk utility via the usb stick to format the drive to HFS+ and then you will be able to install on it

A: I found the problem myself when I copied the old system-partition to the new one via SuperDuper, then went to the AppStore to buy Lion.
The problem is that I own a very early MacBook Pro which only sports a Intel Core Duo. Since Apple dropped support for 32 Bit-only processors with OS X Lion it won't work.


text:
Q: Inaccurate Result from using QGIS contour function on pgr_driving distance I was wondering whether anybody else has experienced a similar problem when using the contour function in QGIS.
I've run PGRouting's pgr_drivingdistance function on some osm data, and applied the contour function to this, although this has produced an inaccurate output
I've used the clip function to clip the sections of highway that fall within this contour as shown below, however this is consequently inaccurate because of the the contouring.
Does anybody know of any solutions to this problem?

I'm using the contour plugin in QGIS, and these are my settings. I've played around with these settings but it doesn't seem to make any real difference to the outputs which I'm getting.


text:
Q: restricting input to certain numbers only in a textbox I need to allow input in a textbox only for certain numbers (200, 300, 400, 600, 1000 or 1200), anything else shouldn't be accepted.
How can I do that using asp:RegularExpressionValidator?


text:
Q: Plot window division with viewports in R I'm trying to achieve a simple division of the plot window with viewports, but something's not right.  The code below wants to achieve the first plot in the left hand 2/3rds of the window and the second in the right hand 1/3rd.  Grateful for an idea what I'm missing:
pushViewport(viewport())
pushViewport(viewport(x=0, y=0, width=.66, height=1, just=c("left","top")))
plot(rnorm(100))
popViewport(1)
pushViewport(viewport(x=.66, y=0, width=.33, height=1, just=c("left","top")))
plot(1:20, 1:20, add=T)
popViewport(2)

Alternatively I wonder if it's possible to replicate the following ggplot method with base plotting.  The code below is illustrative of method but does not work as is incomplete - but is demo'd at rstudio-pubs-static.  But is the method transferable?
a <- qplot(1:10, rnorm(10), main = "a")
b <- qplot(1:10, rnorm(10), main = "b")
c <- qplot(1:10, rnorm(10), main = "c")
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 2)))
vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
print(a, vp = vplayout(1, 1:2))  # key is to define vplayout
print(b, vp = vplayout(2, 1))
print(c, vp = vplayout(2, 2))

A: If you want to use base graphics, then layout is an easy option:
layout(matrix(c(1, 2), 1, 2, byrow=TRUE),
              widths=c(2/3, 1/3))
layout.show(n=2)
plot(rnorm(100))
plot(runif(100))


text:
Q: VBA Regex to remove comments from Teradata SQL text files I am trying to write a VBA Regex to remove comments from Teradata SQL text files.
There are two types of comments:

1   --
  The occurrence of two dashes, '--' denotes the remainder of the line
  as comments.
2./* xxx */
  Everything between '/*' and '*/' is comments. Comments of this type
  can be spread over 1+ lines.

The complication is with text in single quotes such as '--these dashes are in single quotes so do not denote forthcoming comments'.
I am new to Regex and trying to figure this out is proving to be beyond me. I've been thinking along the lines of negative lookahead.
Can anyone help please?
This is as far as I have got:

Type 1:
\-\-[\S \t]*$
Type 2:
/\*[\s\S]*?\*/

A: An algorithm based on recursive parser calls. There are several modes: comments of 3 subtypes parsing, quoted parsing and normal. Normal mode can be alternated by any other mode, that in turn become the only normal. Thus e. g. quote chars within comments and any comment chars within quoted text are ignored. Chars to be searched depend on the current mode. The source is parsed chunk by chunk, once target chars are found the mode is switched respectively, current chunk is finished and the next one begins with the next recursive call. Call stack stores transient results. After the source ends, backward process starts, and each called parser concatenates and returns it's chunk, so finally a complete code retrieved.
Here is the code:
Option Explicit

Sub RemoveComments()

    Dim strOriginal As String
    Dim strProcessed As String

    strOriginal = ReadTextFile("C:\Users\DELL\Desktop\tmp\source.sql", 0) ' -2 - System default, -1 - Unicode, 0 - ASCII
    Parse strOriginal, strProcessed, 0
    WriteTextFile strProcessed, "C:\Users\DELL\Desktop\tmp\result.sql", 0

End Sub

Sub Parse(strSrc As String, strRes As String, lngMode As Long)

    Static objRegExp As Object
    Dim strBeg As String
    Dim objMatches As Object
    Dim lngPos As Long
    Dim lngEscPos As Long
    Dim strRet As String

    If objRegExp Is Nothing Then ' initialize regexp once
        Set objRegExp = CreateObject("VBScript.RegExp")
        With objRegExp
            .Global = False
            .MultiLine = True
            .IgnoreCase = True
        End With
    End If
    strRes = ""
    If strSrc = "" Then Exit Sub ' source completed
    strBeg = "" ' preceding chunk is empty by default
    Select Case lngMode
        Case 0 ' processing normal
            With objRegExp
                .Pattern = "(\/\*)|(^[ \t]*--)|(--)|(\')"
                Set objMatches = .Execute(strSrc)
                If objMatches.Count = 0 Then
                    strRes = strSrc
                    Exit Sub ' source completed
                End If
                lngPos = objMatches(0).FirstIndex
                With objMatches(0)
                    Select Case True
                        Case .SubMatches(0) <> ""
                            lngMode = 1 ' start multiline comment
                        Case .SubMatches(1) <> ""
                            lngMode = 2 ' start whole line comment
                        Case .SubMatches(2) <> ""
                            lngMode = 3 ' start singleline comment
                        Case .SubMatches(3) <> ""
                            lngMode = 4 ' start text in quotes
                            lngPos = lngPos + 1 ' skip found quote char
                    End Select
                End With
            End With
            strBeg = Left(strSrc, lngPos)
            lngPos = lngPos + 1
        Case 1 ' processing multiline comment
            lngMode = 0 ' start normal
            lngPos = InStr(strSrc, "*/")
            If lngPos = 0 Then Exit Sub ' source completed, comment unclosed
            lngPos = lngPos + 2 ' skip comment closing char
        Case 2 ' processing whole line comment
            lngMode = 0 ' start normal
            lngPos = InStr(strSrc, vbCrLf)
            If lngPos = 0 Then Exit Sub ' source completed
            lngPos = lngPos + 2 ' skip new line char
        Case 3 ' processing singleline comment
            lngMode = 0 ' start normal
            lngPos = InStr(strSrc, vbCrLf)
            If lngPos = 0 Then Exit Sub ' source completed
        Case 4 ' processing text within quotes
            lngPos = InStr(strSrc, "'")
            If lngPos = 0 Then Exit Sub ' source completed
            If Mid(strSrc, lngPos, 2) = "''" Then ' escaped quote char ''
                strBeg = Left(strSrc, lngPos + 1) ' store preceding chunk with escaped quote char
                lngPos = lngPos + 2 ' shift next from escaped quote char
            Else
                lngMode = 0 ' start normal
                strBeg = Left(strSrc, lngPos) ' store preceding chunk with quote char
                lngPos = lngPos + 1 ' shift next from quote char
            End If
    End Select
    Parse Mid(strSrc, lngPos), strRet, lngMode ' recursive parser call
    strRes = strBeg & strRet ' concatenate preceding chunk with processed and return result

End Sub


text:
Q: Не могу решить проблему с индексами массивов в с# в проекте в юнити Имею следующий код. Он создает кнопки в определенном месте с данными из массива.
public void CreateItemShop()
{

    for (int i = 0; i < dataSkins.Length; i++)
    {

        GameObject skinItem = Instantiate(prefabItemShopUI, Content.transform);
        skinItem.transform.GetChild(3).GetComponent<Image>().sprite = dataSkins[i].icon;
        skinItem.transform.GetChild(2).GetComponent<TextMeshProUGUI>().text = "" + dataSkins[i].price;

        Button buyButton = skinItem.transform.GetChild(6).GetComponent<Button>();

        buyButton.onClick.AddListener(() => OnClickBuyButtonSkin(buyButton, i));

        print(dataSkins[i].name);
    }

 }

Строка print(dataSkins[i].name); выполняется нормально. Индексы выводятся в консоль правильно. Чего не могу сказать о строке buyButton.onClick.AddListener(() => OnClickBuyButtonSkin(buyButton, i));
Данный метод возвращает лишь ошибку IndexOutOfRangeException: Index was outside the bounds of the array.
   public void OnClickBuyButtonSkin(Button button, int i)
{

    Debug.Log(dataSkins[i].name);
    button.gameObject.SetActive(false);
}

Буду благодарен за любую помощь.

A: Классическая ошибка. Прочитайте про замыкания.
В Вашем случае нужно создать переменную, присвоить ей значение итератора и передать в лямбду.
    var buttonIndex = i;
    buyButton.onClick.AddListener(() => OnClickBuyButtonSkin(buyButton, buttonIndex));

Если коротко о причине, то лямбды будут выполнены после цикла. И в это время i везде будет одинаково и равно dataSkins.Length, что является не валидным значением для индекса.


text:
Q: Getting error ActionView::Template::Error (undefined method `each' for nil:NilClass) I tried to pass some string from a Controllers method to view but it is giving error
ActionView::Template::Error (undefined method `each' for nil:NilClass):
These are my code's i tried:
ApplicationController.rb
class ApplicationController < ActionController::Base
private
    def baconipsum
        @baconipsum ||= Faraday.new("https://baconipsum.com/") do |f|
          f.response :json
        end
      end
end

ArticlesController.rb
def show_Data
    #@count = params[:count]
    @bacon = baconipsum.get("api/", type: 'all-meat',paras: 2).body
end

_show_data.html.erb
<% @bacon.each do |meat| %>

<%= meat %>

<%end%>

Here I tried to take user input that how many paragraph he wants  to generate and i will pass its value to controller show_data, so that Faraday will generate that number of paragraph for it
Here is my form view
_form_data.html.erb
<%= form_for:article do %>
    Value
    <%= text_field_tag :value %>
    <%= submit_tag "Submit" %>
<% end %>

A: # config/routes.rb
get "articles/show_data", to: "articles#show_data"

# app/controllers/articles_controller.rb
def show_data
  @bacon = baconipsum.get("api/", type: 'all-meat',paras: 2).body
  # NOTE: this action will `render "show_data"` by default
end                                        # |
                                           # |
# app/views/articles/show_data.html.erb <----'
<% @bacon.each do |meat| %>

<%= meat %>

<% end %>

To see the result, go to http://localhost:3000/articles/show_data
Update
# app/controllers/articles_controller.rb
def show_data
  @bacon = baconipsum.get("api/", type: 'all-meat',paras: 2).body
end

def show
  @article = Article.find(params[:id])
  show_data # this will set `@bacon` variable
end

<% bacon.each do |meat| %>

<%= meat %>

<% end %>

<%= render "articles/show_data", bacon: @bacon %>

Update 2
Submit form to ArticlesController#show action:
<%= form_for :api_options, url: "/articles/1", method: :get do |f| %>
  <%= f.label :paras %>
  <%= f.text_field :paras %>

  <%= f.submit %>
<% end %>

ArticlesController#show calls show_data method. Submitted form parameters are available through params method in the controller:
def show_data
  @bacon = baconipsum.get(
    "api/",
    type: 'all-meat',
    # NOTE: use `fetch` method and set some defaults when params are not present.
    paras: params.fetch(:api_options, {}).fetch(:paras, 1)
  ).body
end

https://guides.rubyonrails.org/action_controller_overview.html#methods-and-actions
https://guides.rubyonrails.org/layouts_and_rendering.html#rendering-by-default-convention-over-configuration-in-action


text:
Q: Verifying a subring of R? How do I verify that $\mathbb{Z}[\sqrt{2}] = \{ a +b\sqrt{2} \, | \,  a,b \in \mathbb{Z} \}$ is a subring of $\mathbb{R}$ ? I'm thinking that i have to show that it's a subgroup which is closed under multiplication, is that correct?

Also, I have to show that $\mathbb{Z}[\sqrt{2}]^*$ is infinite. It furthermore says I'm supposed to consider powers of $1+\sqrt{2}$ . I am, however, completely lost on this one. I thought $\mathbb{Z}^* = \{ -1,1 \}$, and therefore $\mathbb{Z}[\sqrt{2}]^*$ would be $={-\sqrt{2},-1,1,\sqrt{2}}$, but I'm obviously wrong.

A: Given a ring $R$, a subset $S\subseteq R$ is a subring if it contains the multiplicative identity of R and is closed under the "subtraction" and multiplication of $R$.
For the second question, recall that $\mathbb{Z}[\sqrt{2}]=\{a+b\sqrt{2}\,|\,a,b\in\mathbb{Z}\}$. So $\mathbb{Z}[\sqrt{2}]^*$ is the set of elements of the form $a+b\sqrt{2}$ ($a,b\in\mathbb{Z}$) that have multiplicative inverses. So think about the hint: does $x=1+\sqrt{2}$ have a multiplicative inverse? What about powers of $x$?

A: I'm going to try to answer your second question, since showing that it's a subring only needs you to verify the conditions in the definition of a subring.
It seems that you're having some trouble understanding what $\mathbb{Z}[\sqrt{2}]^*$ is. By definition $\mathbb{Z}[\sqrt{2}]^*$ is the group of units of the ring $\mathbb{Z}[\sqrt{2}]$. It consists of elements $\alpha = a + b \sqrt{2}$ with $a, b \in \mathbb{Z}$ such that $\alpha$ has a multiplicative inverse in $\mathbb{Z}[\sqrt{2}]$.
This just means that if $\alpha = a + b \sqrt{2}$ is in $\mathbb{Z}[\sqrt{2}]^*$, then there must exist another element $\beta = c + d\sqrt{2}$ in $\mathbb{Z}[\sqrt{2}]$ such that $\alpha \beta = 1$.
Another fact that might be useful is that since $\mathbb{Z}[\sqrt{2}]^*$ is a group, then given any two elements $\alpha_1, \alpha_2 \in \mathbb{Z}[\sqrt{2}]^*$, then their product $\alpha_1 \alpha_2 \in \mathbb{Z}[\sqrt{2}]^*$ also.
Certainly $\pm 1 \in \mathbb{Z}[\sqrt{2}]^*$, but $\pm \sqrt{2} \notin \mathbb{Z}[\sqrt{2}]^*$ because for $\pm \sqrt{2}$ to be in $\mathbb{Z}[\sqrt{2}]^*$, there must be an element $c + d\sqrt{2}$ with $c, d \in \mathbb{Z}$ such that $\pm \sqrt{2}(c + d\sqrt{2}) = 1$. But observe that
$$
\begin{align}
\pm \sqrt{2}(c + d\sqrt{2}) = 1 &\iff \pm c\sqrt{2} + \pm 2d = 1 \\
&\iff c = 0 \quad d = \pm\frac{1}{2}
\end{align}
$$
But then since $d = \pm \frac{1}{2} \notin \mathbb{Z}$, this shows that $\pm \sqrt{2} \notin \mathbb{Z}[\sqrt{2}]^*$.
On the other hand, since $(1 + \sqrt{2})(-1 + \sqrt{2}) = 1$, then $1 + \sqrt{2} \in \mathbb{Z}[\sqrt{2}]^*$.
Now, you have to show that $\mathbb{Z}[\sqrt{2}]^*$ has infinitely many elements, and for this you're provided with the hint to consider powers of $1 + \sqrt{2}$. Well, since we already know that $1 + \sqrt{2} \in \mathbb{Z}[\sqrt{2}]^*$ and that products of elements in $\mathbb{Z}[\sqrt{2}]^*$ also lie in $\mathbb{Z}[\sqrt{2}]^*$ then we can conclude that any power $(1 + \sqrt{2})^n \in \mathbb{Z}[\sqrt{2}]^*$. Finally, since $1 + \sqrt{2} > 1$ then each succesive positive power gets bigger, so that we have actually showed infinitely many different elements in $\mathbb{Z}[\sqrt{2}]^*$
$$
1 < 1 + \sqrt{2} < (1 + \sqrt{2})^2 < (1 + \sqrt{2})^3 < \cdots
$$


text:
Q: slime v.2014-04-27 sbcl v.1.2.0 lisp in-package does not change *package* after compilation and loading command C-c C-k This is the code:
(defpackage :morse
  (:use :common-lisp))

(in-package :morse)
...

When I use C-c C-k (Compile/Load file):
CL-USER> *package*
#<PACKAGE "COMMON-LISP-USER">
; compiling file "/home/frederik/Lisp/Code/mycode/marco_baringer.lisp" (written 16 JUN 2014 11:30:15 AM):

; /home/frederik/Lisp/Code/mycode/marco_baringer.fasl written
; compilation finished in 0:00:00.025
CL-USER> *package*
#<PACKAGE "COMMON-LISP-USER">
CL-USER>

I am still in package "COMMON-LISP-USER" when the command "(in-package :morse)" is given in the source code. I should be in "MORSE" I think because when I give the command in the REPL:
...
CL-USER> (in-package :morse)
#<PACKAGE "MORSE">
MORSE> *package*
#<PACKAGE "MORSE">
MORSE>
...

Any idea? Am I wrong?

A: From: Nick Levine  ravenbrook.com>
Subject: Re: SLIME compile and load file REPL stays at  "CL-USER"   with "(in-package :xyz)" in code and not "XYZ"
Newsgroups: gmane.lisp.slime.devel
Date: 2014-06-17 08:12:34 GMT (15 minutes ago)

From: Frederik Cheeseman  evonet.be>
  Date: Tue, 17 Jun 2014 07:54:20 +0000 (UTC)
When I do C-c C-k (SLIME compile/load file) the REPL stays at
  "CL-USER". Shouldn't it switch to "MORSE" because of the
  "(in-package :morse)" code line?

No (and this applies to CL in general, not just to SLIME). This is
because, according to the spec, "load binds readtable and package
to the values they held before loading the file." In effect:
(defun load (file &key ...)
  (let ((*package* *package*))
    (in-load file ...)))

*

*n


text:
Q: Rscript in PowerBI for combined boxplot with bar chart (separate y-axis) Total noob to both Stackoverflow and R so please be gentle!
I'm trying to create a single graph in PowerBI using R that combines a boxplot with a barchart on a time-series x-axis.  Something that looks like this:
Boxplot w Barchart (also below).

What I'm trying to achieve is an x-axis that is the week number (Weeknum) and y-axis for the barchart that is the count of 'LDS' and secondary y-axis that is a cost-per-mile range for 'CAD_CPM.'
I am able to create the boxplot using the below code but cannot seem to figure out how to add in the bar chart.
Any and all help greatly appreciated! Thanks!
boxplot (
CAD_CPM~Weeknum
,data=dataset
,main="Cost Per Mile (CAD)"
,outline = FALSE
,ylab = "CPM (CAD)"
,xlab = ""
,col=(c("pink" , "light blue"))
    )

PowerBI boxplot (also below)

A: Since, you've not provided a minimal reproducible example, I have used the mtcars dataset in R to illustrate my point.
Try the following code in R script editor of PowerBI
library(ggplot2)
library(dplyr)

data = mtcars

temp <- data %>%
  group_by(cyl = factor(cyl)) %>%
  summarise(mpg = mean(mpg))
ggplot(data, aes(factor(cyl), mpg)) +
  geom_bar(data = temp, aes(cyl, mpg), stat = "identity") +
  geom_boxplot()+
  theme_light()

Will result in a boxplot combined with barplot as given below

Now, suppose you want to add some spice to this plot, i.e., make a colorful plot, then try the following code;
library(ggplot2)
library(dplyr)

data = mtcars

temp <- data %>%
  group_by(cyl = factor(cyl)) %>%
  summarise(mpg = mean(mpg))
str(temp)

ggplot(data, aes(factor(cyl), mpg)) +
  geom_bar(data = temp, aes(cyl, mpg), stat = "identity",
           fill=temp$cyl) +
  geom_boxplot(aes(fill=factor(gear)))+
  theme_light()

Will result in following plot;

Adding a secondary y-axis can be achieved by using the sec_axis() function. See the official docs for more info.
library(ggplot2)
library(dplyr)

data = mtcars

temp <- data %>%
  group_by(cyl = factor(cyl)) %>%
  summarise(mpg = mean(mpg))
str(temp)

ggplot(data, aes(factor(cyl), mpg)) +
  geom_bar(data = temp, aes(cyl, mpg), stat = "identity",
           fill=temp$cyl) +
  geom_boxplot(aes(fill=factor(gear)))+
  scale_y_continuous("mpg (US)",
                     sec.axis = sec_axis(~ . * 1.20, name = "mpg (UK)"))+
  theme_light()


text:
Q: How to input many letters and stop after a certain one (q or Q)? I was assigned a homework to input as many letters as the user wants and stop after input q or Q. Then the programs should output how many vowels there were in such string. We're supposed to use _getche() function but I have MacBook so it doesn't work.
I've tried making conio.h.
I've tried also using cin.get() and getchar() but none work.

A: __getche() is not a standard function and conio.h is not a standard header. The usual way of doing this is:
int main() {
    int ch;
    int vowel_count = 0;
    while ((ch = getchar()) != 'q' && ch != 'Q' && ch != EOF) {
       vowl_count += is_vowel(ch);
    }
}

A: i think you need it:
#include <conio.h>
using namespace std;

int main()
{
    bool h = true;
    while(h){
        char ch;
        ch = getche();
        if(ch=='q' || ch == 'Q'){
           h = false;
        }
    }

    return 0;
}

A: #include <iostream> // getchar(), std::cout
#include <cctype> // tolower()

int main()
{
    int count = 0;
    for (;;) // infinite loop
    {
        char c = getchar(); // read a single char from stdin
        if (tolower(c) == 'q') // if input is 'q' or 'Q'
            break; // break out of the loop
        // check for vowel here
        {
            count++;
        }
    }
    std::cout << "You typed in " << count << " vowels!\n";
    return 0;
}


text:
Q: iTextSharp - Using PDFAction.GotoLocalPage in Merged PDF I have written some code that merges together multiple PDF's into a single PDF that I then display from the MemoryStream. This works great. What I need to do is add a table of contents to the end of the file with links to the start of each of the individual PDF's. I planned on doing this using the GotoLocalPage action which has an option for page numbers but it doesn't seem to work. If I change the action to the code below to one of the presset ones like PDFAction.FIRSTPAGE it works fine. Does this not work because I am using the PDFCopy object for the writer parameter of GotoLocalPage?
Document mergedDoc = new Document();
MemoryStream ms = new MemoryStream();
PdfCopy copy = new PdfCopy(mergedDoc, ms);
mergedDoc.Open();

MemoryStream tocMS = new MemoryStream();
Document tocDoc = null;
PdfWriter tocWriter = null;

for (int i = 0; i < filesToMerge.Length; i++)
{
     string filename = filesToMerge[i];

     PdfReader reader = new PdfReader(filename);
     copy.AddDocument(reader);

     // Initialise TOC document based off first file
     if (i == 0)
     {
          tocDoc = new Document(reader.GetPageSizeWithRotation(1));
          tocWriter = PdfWriter.GetInstance(tocDoc, tocMS);
          tocDoc.Open();
     }

     // Create link for TOC, added random number of 3 for now
     Chunk link = new Chunk(filename);
     PdfAction action = PdfAction.GotoLocalPage(3, new PdfDestination(PdfDestination.FIT), copy);
     link.SetAction(action);
     tocDoc.Add(new Paragraph(link));
}

// Add TOC to end of merged PDF
tocDoc.Close();
PdfReader tocReader = new PdfReader(tocMS.ToArray());
copy.AddDocument(tocReader);

copy.Close();

displayPDF(ms.ToArray());

I guess an alternative would be to link to a named element (instead of page number) but I can't see how to add an 'invisible' element to the start of each file before adding to the merged document?

A: I would just go with two passes. In your first pass, do the merge as you are but also record the filename and page number it should link to. In your second pass, use a PdfStamper which will give you access to a ColumnText that you can use general abstractions like Paragraph in. Below is a sample that shows this off:
Since I don't have your documents, the below code creates 10 documents with a random number of pages each just for testing purposes. (You obviously don't need to do this part.) It also creates a simple dictionary with a fake file name as the key and the raw bytes from the PDF as a value. You have a true file collection to work with but you should be able to adapt that part.
//Create a bunch of files, nothing special here
//files will be a dictionary of names and the raw PDF bytes
Dictionary<string, byte[]> Files = new Dictionary<string, byte[]>();
var r = new Random();
for (var i = 1; i <= 10; i++) {
    using (var ms = new MemoryStream()) {
        using (var doc = new Document()) {
            using (var writer = PdfWriter.GetInstance(doc, ms)) {
                doc.Open();

                //Create a random number of pages
                for (var j = 1; j <= r.Next(1, 5); j++) {
                    doc.NewPage();
                    doc.Add(new Paragraph(String.Format("Hello from document {0} page {1}", i, j)));
                }
                doc.Close();
            }
        }
        Files.Add("File " + i.ToString(), ms.ToArray());
    }
}

This next block merges the PDFs. This is mostly the same as your code except that instead of writing a TOC here I'm just keeping track of what I want to write in the future. Where I'm using file.value you'd use your full file path and where I'm using file.key you'd use your file's name instead.
//Dictionary of file names (for display purposes) and their page numbers
var pages = new Dictionary<string, int>();

//PDFs start at page 1
var lastPageNumber = 1;

//Will hold the final merged PDF bytes
byte[] mergedBytes;

//Most everything else below is standard
using (var ms = new MemoryStream()) {
    using (var document = new Document()) {
        using (var writer = new PdfCopy(document, ms)) {
            document.Open();

            foreach (var file in Files) {

                //Add the current page at the previous page number
                pages.Add(file.Key, lastPageNumber);

                using (var reader = new PdfReader(file.Value)) {
                    writer.AddDocument(reader);

                    //Increment our current page index
                    lastPageNumber += reader.NumberOfPages;
                }
            }
        }
    }
    mergedBytes = ms.ToArray();
}

This last block actually writes the TOC. If we use a PdfStamper we can create a ColumnText which allows us to use Paragraphs
//Will hold the final PDF
byte[] finalBytes;
using (var ms = new MemoryStream()) {
    using (var reader = new PdfReader(mergedBytes)) {
        using (var stamper = new PdfStamper(reader, ms)) {

            //The page number to insert our TOC into
            var tocPageNum = reader.NumberOfPages + 1;

            //Arbitrarily pick one page to use as the size of the PDF
            //Additional logic could be added or this could just be set to something like PageSize.LETTER
            var tocPageSize = reader.GetPageSize(1);

            //Arbitrary margin for the page
            var tocMargin = 20;

            //Create our new page
            stamper.InsertPage(tocPageNum, tocPageSize);

            //Create a ColumnText object so that we can use abstractions like Paragraph
            var ct = new ColumnText(stamper.GetOverContent(tocPageNum));

            //Set the working area
            ct.SetSimpleColumn(tocPageSize.GetLeft(tocMargin), tocPageSize.GetBottom(tocMargin), tocPageSize.GetRight(tocMargin), tocPageSize.GetTop(tocMargin));

            //Loop through each page
            foreach (var page in pages) {
                var link = new Chunk(page.Key);
                var action = PdfAction.GotoLocalPage(page.Value, new PdfDestination(PdfDestination.FIT), stamper.Writer);
                link.SetAction(action);
                ct.AddElement(new Paragraph(link));
            }

            ct.Go();
        }
    }
    finalBytes = ms.ToArray();
}


text:
Q: Difference between the MacBook CPUs I have an old 2011 13-inch MacBook Pro and I am thinking to buy a new one. I am wondering if the difference between the CPUs is different. I checked the benchmarks here.

MacBook Pro (13-inch Early 2011) Intel Core i5-2415M @ 2.3 GHz (2
  cores) Score: 486
MacBook Pro (13-inch Mid 2019) Intel Core i5-8279U @ 2.4 GHz (4 cores)
  Score: 961       MacBook Pro (13-inch Mid 2019) Intel Core i5-8257U
  @ 1.4 GHz (4 cores) Score: 940
MacBook Pro (15-inch Mid 2019) Intel Core i7-9750H @ 2.6 GHz (6 cores)
  Score: 1037

Does that means that the new CPUs are only around 2 times faster than the old 2011 CPUs? The difference between the 1.4GHz i5 CPU and the other ones seems very small. Do you think there is a significant overall difference? I will need the laptop mainly for programming (Xcode, react, Tensorflow).

A: You are looking at the single core results. When you click on the Multi-core it changes to:
i5-2415M 1060
i7-9750H 5442
So if what you are planning on doing is single-threaded you are correct, the new MacBook will be roughly twice as fast. Anything multi-threaded will be a lot faster, depending on the workload.
Keep in mind Geekbench is a general benchmark. You can read what the test includes in this pdf , I suggest the detailed test report and try to check what is relevant to your use case.
And a final remark: Tensorflow is a lot faster when it runs on the GPU so you might want to check the graphics card as well.

A:
I will need the laptop mainly for programming (Xcode, react, Tensorflow).

So keep your old one.
You can't judge only with these score: some benchmarks are targeting "single thread performances", others "multi-thread", others "floating point", etc...
You should select the benchmark that are the more related to you domain of usage.
For programming, i think you should better look at:

*

*Numbers of core (if your build process is able to use several processes).

*Storage: SSD or Magnetic ?

*Display: Full HD ?

Cause the "raw power" of CPU won't be a big issue if your main goal is programming.


text:
Q: RStudio, updating packages, restarting R, RStudio goes into endless loop My script gives me a message that I have version 0.2.5 of tidyselect and that version 1.1.0 is required.  I use RStudio to update tidyselect.  RStudio gives me the message that Restating prior to updating is strongly recommended and that RStudio can restart R and then automatically continue the installation.  When I click yes, RStudio goes into an endless loop, continually producing this same message abut updating Loaded Packages.
I don't see any other way to update this package, and this method using RStudio also does not work.
I have the latest (as of today 9/30/20) versions of RStudio and R.

A: There could be multiple problems at hand but I can think of some that might occur as they have done with me as well.
install.packages("remotes")
#would be aid to install the package into R, then fill in the code below.
remotes::install_github("r-lib/tidyselect")
Since tidyselect is connected to several other packages, R studio will request you to update the other packages as well.
If your packages are not updated, it might go into a loop.
Enter 1 after the request to update here to update all the connected packages.
I hope this helped. Otherwise rephrasing your question would help me give more clarity to the situation.


text:
Q: How do i make a warn command for my bot using DISCORDIA(LUA) How can i make a warn command in discordia?
i have tried this but the .json returns as null(no error) in cmd, ive been trying for ages i just cant figure out the problem:
elseif args[1]:lower():sub(3, #".warn") == ".warn" then
  local wopen = io.open("warns.json", "r")
    local wparse = json.parse(wopen:read("*a"))
    wopen:close()
    if args[2] then
        local mentioned_user = message.mentionedUsers.first
        local mentioned_member = message.guild:getMember(mentioned_user)
        local mentioned = message.guild:getMember(mentioned_member)

        if mentioned ~= nil then
            if args[3] then
                table.remove(args, 1) --// removes command and mention arguments
                local reason = table.concat(args) --// turns remaining contents of the table into one long string value
                if wparse[mentioned.id] then --// checks if the mentioned user exists in the database
                  wparse[mentioned.id] = wparse[mentioned.id] + 1 --// big brain math (if the user already exists, add 1 to their warnings)
                    message:reply(mentioned.username.." has been warned because: "..reason..". They now have "..wparse[mentioned.id].." warnings.")
                else --// if they mentioned user doesn't exist, we should add them to it
                    wparse[mentioned.id] = 1 --// if they don't exist, add them to the database and set their warnings to 1
                    message:reply(mentioned.username.." has been warned because: "..reason..". They now have 1 warning.")
                end
            end
        end
    else
        message:reply("Provide a member to warn.")
    end

    wopen = io.open("warns.json", "w")
    wopen:write(json.stringify(wparse))
    wopen:close()

A: guessing your :sub() command is wrong.
it begins at position three, but then ends at length of ".warn" which is 5
so :sub(3, 5) will never return anything that will never == ".warn"
at best, it might give you ".wa"
you need to add three to the second arg in your sub()
:sub(3, #".warn" +3) == ".warn"


text:
Q: Ping IP using C# issue I use this simple code to ping my ip address:
public static bool PingHost(string nameOrAddress)
{
    bool pingable = false;
    Ping pinger = new Ping();
    try
    {
        //nameOrAddress my ip, pingTImeout = 1 second
        PingReply reply = pinger.Send(nameOrAddress, pingTimeout);
        pingable = reply.Status == IPStatus.Success;
    }
    catch (PingException)
    {
        // Discard PingExceptions and return false;
    }
    return pingable;
}

I have a loop which executes this code every 3 seconds.
The strange point is that this loop fails one ping every 1 or 2 minutes, while, if I run the command
ping myIP -t

in the command prompt, all the ping are correct.
Why this different behavior? Maybe the code isn't the right one?


text: Q: Zoom and Fade Custom Segue in iOS I'm trying to create a custom iOS segue that will have an effect similar to the one seen when starting an app on iOS 7. Within my app, I want the use to tap a button and the segue be a zoom into that button that reveals the view. How can I do this?


text:
Q: What is the syntax to export a function from a module in Node.js? What is the syntax to export a function from a module in Node.js?
function foo() {}
function bar() {}

export foo; // I don't think this is valid?
export default bar;

A: to expose both foo and bar functions:
module.exports = {
   foo: function() {},
   bar: function() {}
}

A: You can also do this in a shorter form
// people.js
function Foo() {
  // ...
}

function Bar() {
  // ...
}

module.exports = { Foo, Bar}

Importing:
// index.js
const { Foo, Bar } = require('./people.js');

A: export function foo(){...};

Or, if the function has been declared earlier:
export {foo};

Reference: MDN export

A: In Node you export things with module.exports special object. For example:
This exports both functions:
module.exports = { foo, bar };

They can be used as:
const { foo, bar } = require('./module/path');

To export one of those functions as top-level object you can use:
module.exports = foo;
module.exports.bar = bar;

which can be used as:
const foo = require('./module/path');

and:
const { bar } = require('./module/path');

or:
const foo = require('./module/path');
const { bar } = foo;

or:
const foo = require('./module/path');
const bar = foo.bar;

etc.
This is "the syntax to export a function from a module in Node.js" as asked in the question - i.e. the syntax that is natively supported by Node. Node doesn't support import/export syntax (see this to know why). As slezica pointed put in the comments below you can use a transpiler like Babel to convert the import/export keywords to syntax understood by Node.
See those answers for more info:

*

*Is it ok to use Babel npm package for node.js server application

*javascript - Why is there a spec for sync and async modules?


text:
Q: implement bounded buffer (non-block between reader and writer, block among readers, block among writers) Implement a bounded queue
Read:
If queue is empty, wait till it can return a value with time out
If another thread is reading from the queue then wait till that thread is done
Remove the first element from the queue and return it
Do not block if a thread is writing into the queue
Write:
If queue is full, wait till one value is read with time out
If another thread is writing to the queue, wait till that thread is done
Write the element at the end of the queue
Do not block if a thread is reading from the queue
I'm not sure if my implementation is correct
using namespace std;

template <typename T, int N>
class BoundedBuffer {
private:
    std::array<T, N> buffer;
    int read_pos;
    int write_pos;

    std::mutex reader_mutex; //mutex for between readers
    std::mutex writer_mutex; //mutex for between writers

    std::mutex shared_mutex;
    std::condition_variable reader_queue;
    std::condition_variable writer_queue;
    int timeout; //timeout in millisecond

public:
    BoundedBuffer(const BoundedBuffer&) = delete;
    BoundedBuffer& operator=(const BoundedBuffer&) = delete;

    BoundedBuffer(int t) :
        read_pos(0),
        write_pos(0),
        timeout(t) {
    }

    inline bool empty() {
        return read_pos == write_pos;
    }

    inline bool full() {
        return write_pos >= read_pos + N;
    }

    bool put(const T& data) {
        unique_lock<mutex> writer_lock(writer_mutex);

        {
            unique_lock<mutex> shared_lock(shared_mutex);
            if (full()) { //buffer full
                if (writer_queue.wait_for(shared_lock, std::chrono::milliseconds(timeout)) ==
                    std::cv_status::timeout)
                    return false;
            }
        }

        buffer[write_pos%N] = data;
        write_pos++;
        reader_queue.notify_one();
        return true;
    }

    pair<T, bool> get() {
        unique_lock<mutex> reader_lock(reader_mutex);

        {
            unique_lock<mutex> shared_lock(shared_mutex);
            if (empty()) { //buffer empty
                if (reader_queue.wait_for(shared_lock, std::chrono::milliseconds(timeout)) ==
                    std::cv_status::timeout) {
                    T t;
                    return make_pair(t, false);
                }
            }
        }

        pair<T, bool> result = make_pair(buffer[read_pos%N], true);
        read_pos++;
        writer_queue.notify_one();
        return result;
    }
};

A: Found a bug in my code :
In put() and get() method, it calls wait_for() and checks return value.
If it's timeout, then return false, else it assumes the waiting condition is met and the code continues to put/get data.
If wait_for() returns because of spurious wakeup, and at the time the condition isn't met :
not full for put() and not empty for() get,
then it will overwrite existing data or read wrong data.
The fix is to use predicate in wait_for(). It will ignore the spurious wakeup.
    bool put(const T& data) {
            unique_lock<mutex> writer_lock(writer_mutex);

            {
                    unique_lock<mutex> shared_lock(shared_mutex);
                    if (full()) { //buffer full
                            if (writer_queue.wait_for(shared_lock, std::chrono::milliseconds(timeout),
                                    [this]() { return !full(); }) == false) {
                                    return false;
                            }
                    }
            }

            buffer[write_pos%N] = data;
            write_pos++;
            reader_queue.notify_one();
            return true;
    }

    pair<T, bool> get(int i) {
            unique_lock<mutex> reader_lock(reader_mutex);
            cout << "i : " << i << endl;

            {
                    unique_lock<mutex> shared_lock(shared_mutex);
                    if (empty()) { //buffer empty
                            if (reader_queue.wait_for(shared_lock, std::chrono::milliseconds(timeout),
                                    [this]() { return !empty(); })==false) {
                                    T t;
                                    return make_pair(t, false);
                            }
                    }
            }

            pair<T, bool> result = make_pair(buffer[read_pos%N], true);
            read_pos++;
            writer_queue.notify_one();
            return result;
    }


text:
Q: Ionic-Angular+capacitor+firebase. Help to migrate Google Sign-in codes with the new Capacitor 3 and Firebase 9 I hope someone can help me how to make this old codes for firebase google sign-in to work in the new capacitor 3 and firebase 9. The auth import doesn't work anymore.
here's my code in my auth.service.ts:
import {
  Injectable
} from '@angular/core';
import {
  AngularFireAuth
} from '@angular/fire/compat/auth';
import {
  AngularFirestore,
  AngularFirestoreDocument
} from '@angular/fire/compat/firestore';
import '@codetrix-studio/capacitor-google-auth';
import {
  Plugins
} from '@capacitor/core';
import {
  auth
} from 'firebase/app';
import 'firebase/auth';

export class AuthService {
  constructor(private afAuth: AngularFireAuth, private afs:
    AngularFirestore) {}

  async googleSignup() {
    const googleUser = await Plugins.GoogleAuth.signIn(null) as any;
    const credential = auth.GoogleAuthProvider.credential(
      googleUser.authentication.idToken);
    const afUser = await this.afAuth.signInWithCredential(credential);
    return this.updateUserData(
      afUser.user,
      googleUser.givenName,
      googleUser.imageUrl
    );
  }

and here my code for introduction.page.ts where auth.service.ts is called:
import {
  AuthService
} from '../../services/auth.service';
import {
  Router
} from '@angular/router';

export class IntroductionPage implements OnInit {
  constructor(
    private auth: AuthService,
    private router: Router
  ) {}

  openGoogleSignup() {
    this.auth.googleSignup().then((res) => {
      this.router.navigateByUrl('/app');
    }, err => {
      // Canceled the sign up
    });
  }
}

I've already tried the new import method below for GoogleAuth but I can't follow up with the credentials in my old codes. And I get the error "Unhandled Promise rejection: Cannot read properties of undefined (reading 'getAuthInstance')"
import { GoogleAuth } from '@codetrix-studio/capacitor-google-auth';

Thank you in taking the time to read this, I'm hoping that someone can guide me to this new methods. Goodday everyone.

A: for all who might have a similar problem in the future. i've managed to find solution thanks to mr.grimm.
the imports should go like this:

    import { GoogleAuth } from '@codetrix-studio/capacitor-google-auth';
    import firebase from 'firebase/compat/app';

and the method to call Google sign in is like this:

    async googleSignup() {
        await GoogleAuth.init();
        const googleUser = await GoogleAuth.signIn();
        const credential = firebase.auth.GoogleAuthProvider.credential();
    }


text:
Q: Find $z$ if $dz=\frac{y dx- x dy}{3x^2-2xy+3y^2}$ How can we find $z$ if $$dz=\frac{y dx- x dy}{3x^2-2xy+3y^2}$$
I have no idea how to start, appreciate your help :)

A: $$dz=\frac{y dx- x dy}{3x^2-2xy+3y^2}$$
$$
\begin{align}
 z &=\int \frac{y dx}{3x^2-2xy+3y^2} - \int\frac{x dy}{3x^2-2xy+3y^2}\\&=
\int \frac{y dx}{3 (x - y)^2 + 4 x y } - \int\frac{x dy}{3 (x - y)^2 + 4 x y }\\&=
%\frac{1}y\int \frac{ dx}{3 (x/y - 1)^2 + 4 x/y  } - \frac{1}x\int\frac{ dy}{3 %(1 - y/x)^2 + 4  y/x }\\&=
%\int \frac{ du}{3 (u - 1)^2 + 4 u  } - \int\frac{ du}{3 (1 - u)^2 + 4  u }\\&=
\frac{1}{2 \sqrt{2}}
\left( \arctan \left( \frac{3 x-y}{2 \sqrt{2} y} \right) -
{\arctan\left(\frac{3 y-x}{2 \sqrt{2} x}\right)}\right)=
\arctan\frac{2 \sqrt{2} \left(y^2-x^2\right)}{x^2-6 x y+y^2}
\end{align}
$$
using $\arctan x\pm \arctan y=\arctan\frac{x\pm y}{1\mp xy}$


text:
Q: Can I use an Uno Cross-Platform Library within a UWP app? I've created an Uno cross-platform library that includes a few different Uno controls.
Is it possible to use this library within a UWP project?

A: Assuming you've used cross-platform APIs (eg from Windows.UI.Xaml.* namespaces) and haven't used platform-specific APIs, then yes you can reference this library from a UWP project, as you would any other library.


text:
Q: viewModelScope is cancelled in viewPager there are  fragments in viewPager and each fragment has a viewModel.
when viewpager's current item changes ,fragment is destroyed ,viewModel onCleared is called and viewModelScope is cancelled
there are 2 problems , first after returning back to same fragment, viewModelScope is cancelled and can't launch any coroutines. second when viewPager's current item is changing , the launched coroutine is cancelled.
how can i solve this issues?
i use FragmentStatePagerAdapter with BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT and OffscreenPageLimit is the default value.

A: If you want to do something during the application run lifecycle. You could use ProcessLifecycleOwner. like below.
ProcessLifecycleOwner.get().launch {
 // Do what you want.
}

Or even you can use shared ViewModel for each framents of viewpage.
============================== Deprecated ==================
use GlobeScope.launch{}


text:
Q: Styled components cause react-dom.production.min.js:4482 Error: Minified React error #31; Styled components cause build crash
Guys, I have a problem with styled components ;/.
I'm using create-react-app and everything works fine until I "npm run build" and deploy the app on my FTP.
I keep getting this weird error and have not found any solution online. My code is attached below. Should be plain and simple.
Any ideas?
import styled from 'styled-components';
import countriesJSON from './countries.json';

const Container = styled.div`
     max-width: 1200px;
     margin: 0 auto;
    `;

const Wrapper = styled.div`
        display: flex;
        flex-direction: column;
     height: 100vh;
         justify-content: center;
     align-items: center;

     `;

const Button = styled.button`
  background: whitesmoke;
  border-radius: 3px;
  height: 5vh;
  width: 20vw;
  border: 2px solid orange;
  color: 'slategrey';
  margin: 0 1em;
  padding: 0.25em 1em;

  &:hover {
    background: whitesmoke;
    transform: scale(1.2);
`;

const Text = styled.h1`
  font-size: calc(2vw + 10px);
  font-weight: bold;
  text-align: center;
  color: whitesmoke;

`;

const Paragraph = styled.p`
  color: whitesmoke;
  font-size: calc(1vw + 10px);
`;

const CountryWrapper = styled.div`
    display: flex;
    flex-direction: column;
    align-items: center;

    @media (min-width: 600px) {
     flex-direction: row;
     }
`;

const CountryDetailsWrapper = styled.div`
    margin: 10px;
    text-align: center;
`;

const CountryImgWrapper = styled.div`

    img {
    height: 40vh;
    margin: 0 auto;
     width: 90vw;
     padding: 10px;
     }

     @media (min-width: 596px) {
    img {
     width: 30vw;
    height: 30vh;
    }
    }
`;

class Homepage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            randomCountry: '',

            isCountryWrapperVisible: false,
            countryFlag: '',
            countryRegion: '',
            countryCurrency: '',
            countryCapital: '',
            countryPopulation: '',
            countryTimezone: ''

        }};

    generateRandomCity = () => {

        let num = Math.floor(Math.random() * countriesJSON.length);
        this.setState({
            randomCountry: countriesJSON[num].name
        });
    };

    componentDidUpdate() {
        this.fetchCountryInfo();
    }

    fetchCountryInfo = () => {

        fetch(`https://restcountries.eu/rest/v2/name/${this.state.randomCountry}`)
            .then(res => res.json())
            .then(response =>
                this.setState({
                    countryFlag: response[0].flag,
                    countryCapital: response[0].capital,
                    countryRegion: response[0].region,
                    countryCurrency: response[0].currency,
                    countryPopulation: response[0].population,
                    isCountryWrapperVisible: true
                })
            );

    };

    render() {
        return (

            <Container>
                <Wrapper>
                    <Text> Test Your Knowledge of Flags </Text>
                    <Button onClick={this.generateRandomCity}> HIT ME! </Button>

                    {this.state.isCountryWrapperVisible && (
                        <CountryWrapper>

                            <CountryImgWrapper>
                                <img src={this.state.countryFlag} alt='flag' className='img-fluid'/>
                            </CountryImgWrapper>

                            <CountryDetailsWrapper>
                                <Paragraph>  Name: {this.state.randomCountry} </Paragraph>
                                <Paragraph>  Capital: {this.state.countryCapital} </Paragraph>
                                <Paragraph>  Region: {this.state.countryRegion} </Paragraph>
                                <Paragraph>  Population: {this.state.countryPopulation} </Paragraph>

                          </CountryDetailsWrapper>

                        </CountryWrapper>
                    ) }

                </Wrapper>
            </Container>
        )
    }
}

export default Homepage;```

A: It turns out the problem lied in global-style object within parent component I had to recode.


text:
Q: how to fix localStorage is not defined in react js and how to set and get Item back why localStorage is not defined

  const [bookmark, setBookmark] = useState([]);
  const { showBookmark, setShowBookmark } = useContext(Context);

  const addToBookmark = (id) => {
    if (!bookmark.includes(id)) setBookmark(bookmark.concat(id));
  };

  const removeBookmark = (id) => {
    let index = bookmark.indexOf(id);
    let temp = [...bookmark.slice(0, index), ...bookmark.slice(index + 1)];
    setBookmark(temp);
  };
  let findBookmark = data1.ayat.filter((e) => bookmark.includes(e.nomor));

  useEffect(() => {
    localStorage.setItem('list', JSON.stringify(findBookmark));
  }, [findBookmark]);

  findBookmark = JSON.parse(localStorage.getItem('list')) || '[]';

So, I want to make bookmark feature in my project where I get the data from data1. When I click addBookmark it will save data as per id to localStorage and it works, but when I use getItem from localStorage errors appear:
ReferenceError: localStorage is not defined

and then findBookmark.map()

A: The issue you are seeing is because localStorage, which is an alias for window.localStorage, is not defined on the server side. A server renders your components, so when that happens, and it tries to access localStorage it can't find it. You'll have to wait until the browser renders it in order to use localStorage.
localStorage will have the value (window object) after the useEffect() runs. You can test it using the code snippet below inside the useEffect() hook.
if (typeof window !== 'undefined') {
  console.log('You are on the browser')
  //  can use localStorage here
} else {
  console.log('You are on the server')
  //  can't use localStorage
}

For further clarifications you can visit this link:
https://github.com/vercel/next.js/discussions/19911

A: Please use window.localStorage or globalThis.localStorage