text:
Q: How to add OpenCV library in spring web application I have developed a desktop application. It has to upload an image, processing it, and give some out put.(braille image to text). That portion - the desktop application - is working fine. However, now I want to develop it as a web Application. I am currently designing that level.
using SpringMVC and maven.
In here I have added OpenCV as a user library,
but when it run give bellow
error
HTTP Status 500 - Handler processing failed; nested exception is java.lang.UnsatisfiedLinkError:      no opencv_java248 in java.library.path

Help would be appreciated; how to fix this Error?
Thanks,

A: is this what you're looking for ?
<dependency>
    <groupId>nu.pattern</groupId>
    <artifactId>opencv</artifactId>
    <version>2.4.9-4</version>
</dependency>

Cause your question seems a bit odd.

A: i solved adding  opencv_java248.dll file to Windows/Sun/java/bin

A: added the  opencv_java248.dll file to Windows/Sun/java/bin
it is in C:\opencv\build\java\x64  (in my case windows64 bit)


text:
Q: How to export DAG in .gml format from Dagitty and input into dowhy? I have just started exploring dowhy library for causal inference. In the user guide section there is a basic example to calculate the causal effect. A section here says that it is recommended to input the causal graph in GML graph format. The causal graph can be generated in Dagitty.
How can I export the graph in GML format from Dagitty and input into dowhy? If someone can show me the steps to export the GML format from Dagitty and visualize the graph in dowhy, that would be enough.
Note: I am new to GML as well. Am including networkx as a tag as dowhy uses networkx and getting the graph in GML format from Dagitty and visualizing it in networkx would help as well.

A: According to this pull request (and issue), you can basically just pass the string defining a Dagitty dag().
On Dagitty's website there is a Model code box on the right, which is the graph definitions you would use if you were coding it in R (and not building it interactively).
For example, the default M-bias graph is defined as
dag {
A [pos="-2.200,-1.520"]
B [pos="1.400,-1.460"]
D [outcome,pos="1.400,1.621"]
E [exposure,pos="-2.200,1.597"]
Z [pos="-0.300,-0.082"]
A -> E
A -> Z [pos="-0.791,-1.045"]
B -> D
B -> Z [pos="0.680,-0.496"]
E -> D
}

If you were to take this text as a multi-line string in Python, you could pass it as a CausalModel graph parameter and DoWhy should be able to take it from there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can you pull a timestamp from a preceding record and check a condition? I have a sample table below that shows a list of calls of each employee. Example: On Jan 1 Emp A took 4 calls, B took 4, etc. I am trying to find some anomalies within the start and end times for some calls. The end time for the Previous call cannot be more then the start time of the next call. Example: Call ID: 2 has a discrepancy. The call "ended" at 12:30 AM, but Emp A was on another call at 12:20 AM contradicting the call end time for call id 2. I am trying to write a script to flag these calls. The script will have to partition by Date first then partition by Emp then order by Time. Can this be done?
Call ID  Date    Emp   StartTime   EndTime
1        Jan 1   A     12:00 AM    12:10 AM
2        Jan 1   A     12:15 AM    12:30 AM
3        Jan 1   A     12:20 AM    12:45 AM
4        Jan 1   A     12:50 AM    1:00  AM
5        Jan 1   B     2:00  AM    2:30  AM
6        Jan 1   B     2:25  AM    2:50  AM
7        Jan 1   B     3:00  AM    3:50  AM
8        Jan 1   B     3:45  AM    4:00  AM
9        Jan 1   C     12:30 AM    12:45 AM
10       Jan 1   C     1:00  AM    1:30  AM
11       Jan 1   C     1:45  AM    1:50  AM
12       Jan 1   C     2:00  AM    2:10  AM
13       Jan 2   A     ...         ...
14       Jan 2   A     ...         ...
15       Jan 2   B     ...         ...

Result
Call ID   Incorrect EndTime
2         12:30 AM
5         2:30  AM
7         3:50  AM

A: You can use exists to get overlaps:
select t.*
from t
where exists (select 1
              from t t2
              where t2.emp = t.emp and
                    t2.date = t.date and
                    t2.starttime < t.endtime and
                    t2.endtime > t.starttime
             );

Note:  This assume that no calls span midnight.

A: It seems you're looking to determine incorrect overlap based on LEAD(StartTime) versus EndTime.  The PARTITION BY and ORDER BY for the LEAD function correspond to what's in the question.
with lead_cte as (
    select *, lead(StartTime) over (partition by [Date], Emp
                                    order by StartTime) lead_start
    from calls)
select CallID, EndTime as [Incorrect EndTime]
from lead_cte
where EndTime>lead_start;

A: Use LEAD function.
SELECT
    CallID,
    Date,
    Emp,
    StartTime,
    EndTime,
    LEAD (StartTime) OVER (PARTITION BY Emp, Date ORDER BY StartTime) AS StartTimeNextCall, --this is for information
    CASE
        WHEN (LEAD (StartTime) OVER (PARTITION BY Emp, Date ORDER BY StartTime)) > EndTime
        THEN 'discrepancy'
        ELSE 'ok'
    END AS Flag
FROM tab;

Obs.: I assume that column Date contains only the day, and not the time, otherwise the PARTITION BY clause must be different


text:
Q: a(*{'q':'qqq'}),why only print key def a(*x):
    print x

a({'q':'qqq'})
a(*{'q':'qqq'})#why only print key.

traceback:
({'q': 'qqq'},)
('q',)

A: That's how dictionaries get converted to sequences.
tuple(dictionary) = tuple(dictionary.keys())
for a similar reason
for x in dictionary:

assigns keys, not pairs, to x

A: When you're calling a function, using an asterisk before a list or dict will pass it in as positional parameters.
For example:
>>> a(*('test', 'testing'))
('test', 'testing')

>>> a(*{'a': 'b', 'c': 'd'})
('a', 'c')

A: Using * in front of an expression in a function call iterates over the value of the expression (your dict, in this case) and makes each item in the iteration another parameter to the function invocation. Iterating over a dict in Python yields the keys (for better or worse).

A: a(*{'q' : 'qqq'})

will try to expand your dict ({'q':'qqq'}) into an itemized list of arguments for the function.
Note that:
tuple({'q' : 'qqq'})

returns ('q',), which is exactly what you're seeing. When you coerce a dictionary to a list/tuple, you only get the list of keys.

A: Iterating a dictionary will yield its keys.
d = {'a': 1, 'b': 2, 'c': 3 }

for x in d:
    print x  # prints a, b, c but not necessarily in that order

sorted(d): # Gives a, b, c in that order. No 1/2/3.

If you want to get both keys and values from a dictionary, you can use .items() or .iteritems()
sorted(d.items()) # [('a,' 1), ('b', 2), ('c', 3)]

A: You are asking for a list of arguments, and then telling python to send a dict as a sequence of arguments. When a dict is converted to a sequence, it uses the keys.
I guess you are really looking for **, not *.

A: Probably because that's what a dictionary returns when you do a standard iteration over it. It gets converted to a sequence containing it's keys. This example exhibits the same behaviour:
>>> for i in {"a": "1", "b": "2"}:
...     print i
...
a
b

To get what I assume you expect you would pass it as variable keyword arguments instead, like this:
>>> def a(**kwargs):
...     print kwargs
...
>>> a(**{"a": "1", "b": "2"})
{'a': '1', 'b': '2'}

Note that you are now basically back where you began and have gained nothing.


text:
Q: Do Batch files support multiline variables If so How?
Yes, batch files are lame, but I cannot use powershell, and I don't feel like writing a real app to do this simple task....
edit
What i want is somthing along the lines of
set var="this is a
multi
line
string "

A: SET myFlags= ^
    a ^
    b ^
    c

A: Or you can create a "real" newline character.
setlocal enableDelayedExpansion
set NL=^

rem two empty line required
echo first line !NL! second line
set multi=Line1!NL!Line2
set multi=!multi!!NL!Line3
echo !Multi!

With this variant the newline is a "normal" character in the string, so the variables act normally and you can assign them to another variable, this is not possible with the &echo. trick (which is useful for simple tasks).

A: This is a pretty old question, but I put together a hybrid of the solutions from  @Fabricio and @jeb that both worked correctly and added some readability:
setlocal enableDelayedExpansion
set NL=^

rem two empty line required
set var=this is a !NL! ^
multi !NL! ^
line !NL! ^
string !NL!

echo !var!

A: If you just wanted to use it for outputting the lines of variables, I hope this would be useful to you.

Inspired by something, I found this working.

For codes in normal Command Prompt:
set this=echo hi ^& echo bye
%this%

It gives out the two following two lines:
hi
bye

in the Command Prompt window.

The reason for using the ^ character:
Command Prompt would identify that you wanted to run two commands so that you need to add this character, that tells Command Prompt to recognize the next character as a symbol and not to do any special thing for it.

A: I think I figured it out. I had to add ^ to the %NL% var when putting it in the string, otherwise it hides the text after the first %NL% because its executing when being set, instead of when its being echoed later
set NL=^& echo

set str=text on line 1 ^%NL% text on line 2

echo %str%
text on line 1
text on line 2

A: Is that ok?
@echo off
set var=kur
set var2=kur2
echo var is = "%var%" and var2 is = %var2%

edit
is that what you mean ?
@echo off
set nl=^& echo.
echo this%nl%is%nl%multiline%nl%string

A: And now - without auxiliary SET commands:
echo this is a & echo multi & echo line & echo string

A: If you wanted to build something instead, not just outputting, hope this would be useful to you too.

Firstly, you should make a file. Such as .txt. I'm going to use var.txt as an example.
Secondly, type in the multi-lines of variables.

Thirdly, here are the codes, but only works for batch:
@echo off
set num=0
set /p this%num%=<"var.txt"
goto there

:there
set /a num=num+1
for /f "skip=%num%" %%a in (var.txt) do (set this%num% =%%a
goto there)
set num=0
goto build

:build
rem Example of using multi-lines of variable.
call echo %%this%num% %%
set /a num=num+1
for /f "skip=%num% delims=" %%a in (var.txt) do (call echo %%this%num% %%
goto build)
rem Just replace the commands with `echo` part into something else which suits your situation.
pause >nul
exit

I admit that strictly speaking, this is not a variable of multi-line, but in my opinion, this is better than nothing.
You may ask why not just use the setlocal EnableDelayedExpansion command. The reason is simply, that command does work for me (IDK why). Therefore, I thought and made these codes that make the same effect.

A: I prefer this method
@ECHO OFF
SETLOCAL EnableDelayedExpansion

REM (define NewLine character)
(SET _NL=^
%=this line is empty=%
)

A: I just came to this kind of a specification; the NLM and NL are from https://stackoverflow.com/a/269819/6197439 - and then the trick is basically to write line by line, escaping the line ending with caret (^), and right before the caret, add a unique character (here +), which at the end will be replaced with actual newline via delayed expansion:
REM Creating a Newline variable (the two blank lines are required!)
set NLM=^

set NL=^^^%NLM%%NLM%^%NLM%%NLM%
REM use a unique character (here +) to indicate a newline, then replace it later
SET banner=Line 1 +^
Line 2 +^
Line 3

setlocal enabledelayedexpansion
SET banner=%banner:+=!NL!%
setlocal disabledelayedexpansion
echo %banner%

This prints in terminal:
Line 1
Line 2
Line 3


text:
Q: Serial communication between RPi and Arduino using C++ I've written two pieces of code, to create a serial communication between Arduino and a Raspberry Pi using C++. The codes are:
void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 baud
}

void loop() {
 Serial.println("Hello from arduino");
 delay(500);
}

And the C++ code in Raspberry is :
#include <iostream>
#include <wiringPi.h>
#include <wiringSerial.h>

using namespace std ;
int serialDeviceId=0;
int main(void)

{
    int pin=7;
    serialDeviceId= serialOpen("/dev/ttyACM1",9600);
    if(serialDeviceId==-1)
     {
     cout<<"Unable to open serial device"<<endl;
     return 1;
     }
    if(wiringPiSetup()==-1)
    {
        return 0 ;
    }
    pinMode(pin,OUTPUT); // designing pin as an output
    while(1)
    {
        digitalWrite(pin,0);
        delay(500);
        digitalWrite(pin,1);
        delay(500);
    }
    return 0;
}

So now I would like to read the data from the serial port using always that wiringpi and I've found that I can use SerialGetchar, but I don't know exactly how to use it. I just need to need this part in my code so that I can receive that "Hello from from arduino" written in the serial, from my Arduino code.

A: This code should work for you on the Raspberry Pi. It is extremely simple! Make sure you get the correct device special file by running:
dmesg

and looking for line like this:
[610106.464745] usb 1-1.4: new full-speed USB device number 4 using dwc_otg
[610106.608642] usb 1-1.4: New USB device found, idVendor=2341, idProduct=0043
[610106.608655] usb 1-1.4: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[610106.608663] usb 1-1.4: Manufacturer: Arduino (www.arduino.cc)
[610106.608671] usb 1-1.4: SerialNumber: 55731323536351E002E1
[610106.686193] cdc_acm 1-1.4:1.0: ttyACM0: USB ACM device

#include <stdio.h>
#include <string.h>
#include <errno.h>

#include <wiringSerial.h>

int main ()
{
  int fd ;

  if((fd=serialOpen("/dev/ttyACM0",9600))<0){
    fprintf(stderr,"Unable to open serial device: %s\n",strerror(errno));
    return 1;
  }

  for (;;){
    putchar(serialGetchar(fd));
    fflush(stdout);
  }
}

I assume you have a USB cable connecting one of the RaspberryPi USB ports to the USB port on the Arduino.


text:
Q: Could overriding Python destructor (__del__) cause memory leaks? I have a script where I create an object over a cloud using API and want to delete it over some occasions, at the end of the script.
class ObjCreator():
   def __init__(self, keep_object: bool):
      self.keep_object = keep_object
      print("init")

   def create_object(self):
      print("Created object using API")

   def delete_object(self):
      print("Deleting object using API")

   def __del__(self):
      print("Deleting object using API only if keep_object is False")
      if not self.keep_object:
         self.delete_object()

I've seen some memory leaks over Python programs, so obviously the GC isn't prefect (i.e., uncollectable objects).
My fear is that overriding the del function would cause a memory leak.
Is that possible?
If so, do you have any suggestion to a different, elegant solution?

A: Your intuition is right, overriding the __del__ method means that the base class's __del__ method is not automatically called anymore (although I don't think a memory leak is likely here). In fact the documentation explicitly mentions this:

If a base class has a __del__() method, the derived class's __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance.

A code example for this from the CPython repo:
    def __del__(self):
        # ... your cleanup code here ...
        super().__del__()  # call to base class


text:
Q: Host MEAN STACK APP using Github gh-pages https://github.com/shaneyvincent/MEAN-STACK-message-app <-- the github
https://shaneyvincent.github.io/MEAN-STACK-message-app/ <--what the host shows
Hello I am trying to Host a mean stack app using gh-pages.
When I run the site locally I use node server.js ( listening on port  5000
 connected to mongo) and then I use gulp serve to launch the page. it shows serving files from my SRC folder.
When I push to gh pages branch, and launch the page I get a 404 error, Why can it not find my index file in my SRC folder, also I tried copying the index.html  and placing it in the main folder, but then after I push that it just reads a blank page. any ideas?

A: Your index.js is the first problem.
Line #4 (app.set('port', (process.env.PORT || 5000));) will not work on Github Pages. It only allows for client-side languages or Jekyll, not server-side NodeJS apps.


text:
Q: sighandler_t typedef statement in Linux? While studying Signals in Linux, I came across this declaration :
typedef void (*sighandler_t)(int);
sighandler_t signal (int signo, sighandler_t handler);

The handler function must return void and its prototype has the form :
void my_handler (int signo);

Linux uses a typedef, sighandler_t, to define this prototype.
When I saw Linux Man pages for signal() function it is present there.
But I don't understand What that typedef statement here means.
Can anyone explain what that typedef sighandler_t means?

A: This is a bit of C magic that says the following:
typedef void (*sighandler_t)(int);

there is a special type called sighandler_t that is a pointer to a function that takes an integer argument and returns nothing.

sighandler_t signal(int signo, sighandler_t handler);

there is a function signal that takes an integer named signo and a function pointer handler as arguments and returns a function pointer.

The typedef literally means "type definition" and is used to define a placeholder for complex types — like function pointers or structures etc.
The definition of a function pointer is a bit beyond the scope of this question, but can be thought of as a command that the user writes, that the framework will call, without knowing exactly what that function will be.


text:
Q: How to invalidate session of one application while switching to other application I am building application using spring + spring security + cas.
CAS provides once login to access multiple applications. Now my problem is at the time of logout session is not invalidating for all the applications integrated in CAS.
How to solve this issue?
Thanks in advance

A: You will need to implement and turn on the CAS single logout feature. When you do that upon cas logout all other applications will be reached in and their session will be invalidated


text:
Q: habilitar cors headers en laravel 6 tuve este problema al tratar de consumir una API en laravel desde react:
Access to fetch at 'http://apirest.com/companies' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled

Encontre información y tengo una duda como agrego la ruta del end point http://apirest.com/register y http://apirest.com/companies al archivo routes? usé este codigo para laravel 6:
archivo cors.php:
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
  public function handle($request, Closure $next)
  {
    return $next($request)
       //Url a la que se le dará acceso en las peticiones
      ->header("Access-Control-Allow-Origin", "http://urlfronted.example")
      //Métodos que a los que se da acceso
      ->header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
      //Headers de la petición
      ->header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Token-Auth, Authorization");
  }
}

kernel.php:
protected $routeMiddleware = [
  ...,
  ...,
  "cors" => \App\Http\Middleware\Cors::class,
 ];

el codigo que hay que usar en el archivo de rutas:
Route::group(['middleware' => ['cors']], function () {
    //Rutas a las que se permitirá acceso
});

mi arhcivo de rutas web.php:
Route::resource('/','ClientsController');
Route::resource('/register','ClientsController');
Route::resource('/companies','CompaniesController');

archivo de rutas api.php:
<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});


text:
Q: Power function in a loop I need help with writing power function. So, I need to write a porogramm, that will output a table from 1 to 10 in a power in a LOOP. NOT USING POW or EXP
    Example of output:
0^0 == 1
1^1 == 1
2^2 == 4
3^3 == 27
4^4 == 256
(and so on, up to)
10^10 == 10000000000

NOT USING Cmath (NO POW or EXP)
for example:
e.g. power( 3.0, 5 ) will return 243 because 3*3*3*3*3 is 243
e.g. power( 173, 0 ) will return 1 because any number raised to the power of 0 is 1.
I did this Simple loop, But I have no idea how to insert power formula in it. I was also thinking about while loop
#include <iostream>
#include <string>
using namespace std;

int main(){

    int number = 0, tot;

    for (int table = 0; table < 10; table++)
    {
        tot = number * table;
        cout << tot << endl;
        number++;
    }
}

A: This is a recursive function that can calculate a value raised to an integer power
double power(double base, unsigned int exp)
{
    if (exp == 0)
    {
        return 1.0;
    }
    else
    {
        return base * power(base, exp - 1);
    }
}

An iterative method to do this would be
double power(double base, unsigned int exp)
{
    double product = 1.0;
    for (unsigned int i = 0; i < exp; ++i)
    {
        product *= base;
    }
    return product;
}

You can test either method with something like
int main()
{
    std::cout << power(5, 3);
}

Output
125

A: I think you already know the answer to your own question by now, but still; some hints:

*

*Exponentiation is a repeated multiplication of the base, the repetition is defined by the exponent.

*In C++, or any modern programming language, loops allow repetition of certain blocks of code: when the number of iterations is known beforehand, use the for-loop, otherwise, use the while-loop.

Combining both hints: you'll need to use a loop to repeat a multiplication; the amount of repetition (or iterations) is known beforehand, thus, a for-loop will be best.

int exponentiation(int base, int exponent) {
    int result = 1;
    for (int i = 0; i < exponent; ++i)
        result = result * base;
    return result;
}

Note: this will only suffice for integer exponentiation with positive exponents!

You can then call this function in a for-loop to let it compute the values you want:
#include <iostream>

int main(int argc, char** argv) {
    for(int i = 0; i <= 10; ++i)
        std::cout << exponentiation(i, i) << '\n';
}


text:
Q: Android Material Slider OnChangeListener Response Delay/Skip Problem So I have a "both" Slider which controls "width" Slider and "length" Slider, like below:
<com.google.android.material.slider.Slider
    android:id="@+id/width_slider"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:value="40"
    android:valueFrom="0"        <-
    android:valueTo="200"        <-
    android:stepSize="1"/>       <-

<com.google.android.material.slider.Slider
    android:id="@+id/height_slider"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:value="40"
    android:valueFrom="0"        <-
    android:valueTo="200"        <-
    android:stepSize="1"/>       <-

<com.google.android.material.slider.Slider
    android:id="@+id/both_slider"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:value="100"
    android:valueFrom="0"        <-
    android:valueTo="200"        <-
    android:stepSize="1"/>       <-

As I marked above, they all have same range (from & to) and the stepSize to 1 (important), and I set the behavior of

when adding/subtracting value 1 on the both Slider, the other two will be added/subtracted value 1  too.

Code as below:
private var previousValue = 50f        //initial value, same as on xml

binding.bothSlider.addOnChangeListener { slider, value, fromUser ->
    if (value > previousValue) {
        binding.widthSlider.value++
        binding.heightSlider.value++
    }

    if (value < previousValue) {
        binding.widthSlider.value--
        binding.heightSlider.value--
    }

    previousValue = value
}

And weird thing happens, it seems like the width and height Slider has some a bit slow reaction (I guess), and skip some point:

They should be synchronized, because they have same stepSize and value range (just the initial values are different). Any help would be appreciated.

A: Use the current value of the "both" slider to set the values of the others.
binding.bothSlider.addOnChangeListener { _, value, _->
    binding.widthSlider.value = value
    binding.heightSlider.value = value
}

It's a little hard to know exactly what you're trying to do. You could also do something similar to what you have but use a diff instead of just 1:
binding.bothSlider.addOnChangeListener { slider, value, fromUser ->
    val diff = value - previousValue
    binding.widthSlider.value += diff
    binding.heightSlider.value += diff

    previousValue = value
}

This will let the sliders diverge but will still solve the "speed" problem you're having.

A: Those sliders seem to have a different scale...
but actually it's the initial value which creates an offset of 60:
<com.google.android.material.slider.Slider
    android:id="@+id/both_slider"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:value="40" <-- 100 != 40
    android:valueFrom="0"
    android:valueTo="200"
    android:stepSize="1"/>


text:
Q: I want to capture all warnings while importing a solution programatically in CRM 2016. In the response object I am not getting any such information var importSolutionRequest = new ImportSolutionRequest
            {
                ImportJobId = Guid.NewGuid(),
                CustomizationFile = fileBytes,
                OverwriteUnmanagedCustomizations = true,
                PublishWorkflows = true,
                SkipProductUpdateDependencies = true,
            };
var response =  (ImportSolutionResponse)Service.Execute(importSolutionRequest);

I am not getting any useful information in this response object. What changes should I do to get warnings in this object, which occured while importing solution?

A: You have to query the ImportJob to get the results you want (https://msdn.microsoft.com/en-us/library/gg327847.aspx).
From the SDK (https://msdn.microsoft.com/en-us/library/gg509050.aspx):
                // Monitor import success
                byte[] fileBytesWithMonitoring = File.ReadAllBytes(ManagedSolutionLocation);

                ImportSolutionRequest impSolReqWithMonitoring = new ImportSolutionRequest()
                {
                    CustomizationFile = fileBytes,
                    ImportJobId = Guid.NewGuid()
                };

                _serviceProxy.Execute(impSolReqWithMonitoring);
                Console.WriteLine("Imported Solution with Monitoring from {0}", ManagedSolutionLocation);

                ImportJob job = (ImportJob)_serviceProxy.Retrieve(ImportJob.EntityLogicalName, impSolReqWithMonitoring.ImportJobId, new ColumnSet(new System.String[] { "data", "solutionname" }));

                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(job.Data);

                String ImportedSolutionName = doc.SelectSingleNode("//solutionManifest/UniqueName").InnerText;
                String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/@result").Value;

                Console.WriteLine("Report from the ImportJob data");
                Console.WriteLine("Solution Unique name: {0}", ImportedSolutionName);
                Console.WriteLine("Solution Import Result: {0}", SolutionImportResult);
                Console.WriteLine("");

                // This code displays the results for Global Option sets installed as part of a solution.

                System.Xml.XmlNodeList optionSets = doc.SelectNodes("//optionSets/optionSet");
                foreach (System.Xml.XmlNode node in optionSets)
                {
                    string OptionSetName = node.Attributes["LocalizedName"].Value;
                    string result = node.FirstChild.Attributes["result"].Value;

                    if (result == "success")
                    {
                        Console.WriteLine("{0} result: {1}",OptionSetName, result);
                    }
                    else
                    {
                        string errorCode = node.FirstChild.Attributes["errorcode"].Value;
                        string errorText = node.FirstChild.Attributes["errortext"].Value;

                        Console.WriteLine("{0} result: {1} Code: {2} Description: {3}",OptionSetName, result, errorCode, errorText);
                    }
                }


text:
Q: is there a faster version of fminbnd in matlab? I am now using fminbnd in Matlab, and I find it relatively slow (I am using it inside a nested loop). The function itself, its interface and the values it returns are great, but when looking into the .m file I see it is not optimized. As a matter of fact, I was hoping for something like that to be written as a mex.
Anyone knows of an alternative to fminbnd that works much faster and does not have as much overhead?

A: It's written like that because it has to evaluate (feval) your user-defined function(s) on every iteration. Matlab's ODE solvers work in the same way. In current Matlab it's costly for a C/C++ code to call a user-defined Matlab function and read in its return values iteratively.
Make sure you're using the options correctly, that fminbnd is the correct tool (maybe a simpler scheme would be better or, since this in a loop, maybe a multi-dimensional method like fminsearch would be more appropriate), and have optimized your objective function. The next easiest thing would be to try compiling your Matlab code to C or C++ (see codgen). You'll likely need to compile in your objective function, and all of the options, as well in order to avoid the slowdown issues mentioned above. I've not tried this for fminbnd, but I did see mention of it working online. If your objective function itself is complicated, you could try just converting it to a mex function.
fminbnd is based on Brent's method. You can find C, C++, and FORTRAN code for that here. The GSL also has a version: gsl_min_fminimizer_brent.


text:
Q: 500 Server Error in PHP If you visit my script "page.php" in the URL. A 500 Error appears. If you submit through a form it works.
<?php
## send forgot pass
$a=$_REQUEST['email_address'];
include("template.funcs.php");
$yz = mysql_connect("","","");
mysql_select_db("", $yz);
$b=mysql_real_escape_string($a);
$d=mysql_query("SELECT * FROM `customers` WHERE `customers_email` = '".$b."'");
    if (mysql_affected_rows()==0){
        header("Location: cart.php?pass=notsent");
    }else{
        send_registration_email($b,'','','');
        header("Location: cart.php?pass=sent");
    }
mysql_close($yz);
?>

A: I would assume this has something to do with $_REQUEST['email_address'] not being defined on normal page load...

A: A 500 error is a server side error, and I've found the best way to fix this is to check the logs on your server.
On the other hand, looking at your code, you may not have defined $_REQUEST['email_address']. Try this:
<?php
if (isset($_REQUEST['email_address'])) {
    ## send forgot pass
    $a=$_REQUEST['email_address'];
    include("template.funcs.php");
    $yz = mysql_connect("","","");
    mysql_select_db("", $yz);
    $b=mysql_real_escape_string($a);
    $d=mysql_query("SELECT * FROM `customers` WHERE `customers_email` = '".$b."'");
        if (mysql_affected_rows()==0){
            header("Location: cart.php?pass=notsent");
        }else{
            send_registration_email($b,'','','');
            header("Location: cart.php?pass=sent");
        }
    mysql_close($yz);
}
?>

A: Use useful variable names. Use indenting appropriately. Only escape input before inserting it into your database. Group often used functionality in functions. Don't use $_REQUEST. Fail fast. A few hints which massively increase your code quality.
Now have a look at this:
include("template.funcs.php");

function Redirect($to)
{
    header("Location: " . $to);
    exit();
}

if ($_SERVER['REQUEST_METHOD' != "POST" || !isset($_POST['email_address']))
{
    Redirect("cart.php?pass=notsent");
    // or redirect to your "forgot password" form
}

$mailAddress = $_POST['email_address'];

$dbconn = mysql_connect("","","");
mysql_select_db("", $dbconn);

mysql_query("SELECT * FROM `customers` WHERE `customers_email` = '".mysql_real_escape_string($mailAddress)."'");

if (mysql_affected_rows() == 0)
{
    Redirect("cart.php?pass=notsent");
}

send_registration_email($mailAddress,'','','');
Redirect("cart.php?pass=sent");


text:
Q: Python PhantomJS, i can not enter a number I want to send a number to the site. But you can not do this because the program hangs. Code:
input_code_user = input('Input code and press Enter:')
WebDriverWait(driver, timeout=10).until(lambda x: x.find_element_by_xpath("//label[@my-i18n='login_number_input_placeholder']")).click()
WebDriverWait(driver, timeout=10).until(lambda x: x.find_element_by_xpath("//input[@ng-model='credentials.phone_code']")).send_keys(input_code_user)

When the site is loaded, the code entry field looks like this:

The code for this form looks like this:

If you click on this field, it will look like this:

At the same place where the code was previously, it is replaced with a new one:

The program hangs on this code:
WebDriverWait(driver, timeout=10).until(lambda x: x.find_element_by_xpath("//input[@ng-model='credentials.phone_code']")).send_keys(input_code_user)

I'm trying to take a screenshot after this line of code, but it is not created. The program works, but nothing happens. Help me find a solution.


text:
Q: How to get the value from NSMutableArray to NSString stored in CoreData in Objective C I am new in iOS and I am facing a problem regarding to get the coredata mutablevalue in nsstring.
My code is like this
In Cell for row at Index Path
       static NSString *MyIdentifer =@"MyReuseIdentifer";
        UITableViewCell *cell=[tableView dequeueReusableHeaderFooterViewWithIdentifier:MyIdentifer];
        if (cell==nil)
        {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifer ];
        }
        // Configure the cell...
        NSManagedObject *device2 = [devices objectAtIndex:indexPath.row];
        NSLog(@"Devices =%@",devices);
        [cell.textLabel setText:[NSString stringWithFormat:@"%@", [device2 valueForKey:@"Key"]]];
        NSLog(@"Cell All Text =%@",cell.textLabel.text);
         NSString *string = [devices componentsJoinedByString:@","];
        NSLog(@"String value =%@",string);

        return cell;

Data in MutableArray is Like This
{
    Key = 46;
}),<NSManagedObject: 0x7f988612f560> (entity: Device; id: 0xd000000000080000 <x-coredata://7845A868-643C-4CFE-8FC8-283C1C7D0A37/Device/p2> ; data: <fault>),<NSManagedObject: 0x7f988612f5e0> (entity: Device; id: 0xd0000000000c0000 <x-coredata://7845A868-643C-4CFE-8FC8-283C1C7D0A37/Device/p3> ; data: <fault>),<NSManagedObject: 0x7f988612f660> (entity: Device; id: 0xd000000000100000 <x-coredata://7845A868-643C-4CFE-8FC8-283C1C7D0A37/Device/p4> ; data: <fault>),<NSManagedObject: 0x7f988612f6e0> (entity: Device; id: 0xd000000000140000 <x-coredata://7845A868-643C-4CFE-8FC8-283C1C7D0A37/Device/p5> ; data: <fault>),<NSManagedObject: 0x7f988612f760> (entity: Device; id: 0xd000000000180000 <x-coredata://7845A868-643C-4CFE-8FC8-283C1C7D0A37/Device/p6> ; data: <fault>),<NSManagedObject: 0x7f988612f7e0> (entity: Device; id: 0xd0000000001c0000 <x-coredata://7845A868-643C-4CFE-8FC8-283C1C7D0A37/Device/p7> ; data: <fault>),<NSManagedObject: 0x7f988612f860> (entity: Device; id: 0xd000000000200000 <x-coredata://7845A868-643C-4CFE-8FC8-283C1C7D0A37/Device/p8> ; data: <fault>)

I am Getting Correct value in TableView
How can I get the value of MutableArray in NSString.Note- Devices is a NSMutableArray.
Fetch Request
- (NSManagedObjectContext *)managedObjectContext {
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSManagedObjectContext *context = [self managedObjectContext];

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete object from database
        [context deleteObject:[self.devices objectAtIndex:indexPath.row]];

        NSError *error = nil;
        if (![context save:&error]) {
            NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
            return;
        }

        // Remove device from table view
        [self.devices removeObjectAtIndex:indexPath.row];
        [Audittable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

Thanks in Advance!


text:
Q: VBA excel multiline string search I want to search a multi line string in a text file using VBA excel macro.
I tried using InStr function.But its not working as I expected. My exact aim is to read a multi line string stored in a cell and check whether it is available in a text file. For that what i did is read the text file in to a variable, reading the string saved in the cell to another variable and comparing using Instr using binary comparison. Will InStr work for multi line string? If not any any other way to compare it?
This is  my code
Public Function string_compare() As String
    Dim strFilename As String
    Dim strSearch As String
    strFilename = "D:\test.txt"
    Dim strFileContent As String
    Dim iFile As Integer: iFile = FreeFile
    Open strFilename For Input As #iFile
    strFileContent = Input(LOF(iFile), iFile)
    Close #iFile
    strSearch = Sheet1.Cells(9, 1).Value
    If InStr(1, strFileContent, strSearch, vbBinaryCompare) > 0 Then
        MsgBox "success"
    Else
        MsgBox "failed"
    End If
End Function

When I checked the strings both seems to be identical.Even though the strings are identical, the searching result always failing. Any suggestions will be helpful.

A: As Tim and Mrig suggested I removed the cr and crlf from the text as follows. Now its working fine.I could use this for comparing multi line strings.I am posting my code  segment here.Hope it may help somebody else too.
Public Function stringcompare(sourcefile As String, Workbookname As Worksheet) As String
Dim strSearch As String
Dim strFileContent As String
Dim iFile As Integer: iFile = FreeFile
Open sourcefile For Input As #iFile
strFileContent = Input(LOF(iFile), iFile)
Close #iFile
strSearch = Workbookname.Cells(1, 1).Value
strFileContent = Application.WorksheetFunction.Substitute(strFileContent, vbCrLf, "")
strSearch = Application.WorksheetFunction.Substitute(strSearch, vbLf, "")
    If StrComp(strFileContent, strSearch, vbBinaryCompare) = 0 Then
        MsgBox "success"
    Else
        MsgBox "failed"
    End If
End Function


text:
Q: Chef-client not running automatically post bootstrap Is there some way to set up the periodic chef-client runs during the bootstrap phase?
I can successfully bootstrap a client from the chef server, I can then manually run chef-client on the client node. I can even get the client to run periodically like so:
sudo chef-client -d -i 1800 -s 13

I'd like to apply that step during the bootstrap phase.

A: It does not install itself as a service. Use the chef-client cookbook to do that.


text:
Q: django safe or escape on img alt attribute Should i use safe or escape on alt?
Example:
<img src="{{ post.img }}" alt="{{ post.title }}">

And what is difference between them? (example if possible)

A: Use escape and be careful with chaining.
Example:
{{ post.title|escape }}

Per, Django 3.1 documents:
If you are chaining filters, a filter applied after safe can make the contents unsafe again. For example, the following code prints the variable as is, unescaped:
{{ var|safe|escape }}

escape
Escapes a string's HTML. Specifically, it makes these replacements:
safe
Marks a string as not requiring further HTML escaping prior to output. When autoescaping is off, this filter has no effect.


text:
Q: SQL Connection without log steal I'm making a game with a login system which connect to a database, but my source code is not crypted and I worried about if someone decompile my program, he can get the SQL logins and wanted to know how prevent from that?

A: Since .NET Framework 2.0, there is a possibility of encrypting application configuration sections. However, it needs a bit of implementation.
Please refer to the following article.
https://msdn.microsoft.com/en-us/library/53tyfkaw(v=vs.110).aspx
Just another option... You can consider using "Integrated Security=SSPI" in your connection string. This will try to open connection to database with the user running your application main thread. However, this will require additional management on the SQL server side for permissions of the user but you won't be providing any usernames or passwords in your connection string.
And a note... Although i partially agree with Roblll with the comment on research, sometimes people need advice for the concept. If concept is not there and you are lost, you cannot share a line of code right? I think stackoverflow is a great platform to ask and learn from replies. So keep on asking... Do your homework and don't be shy! :)
Cheers


text:
Q: Empty request with some upload file in php I have a little problem about upload files in ajax. I sent a form-data to my backend server. The problem is that sometimes, depending on the files my backend doesn't receive anything. Nothing on $_REQUEST, nothing on $_POST, $_GET, $_FILES or even in file_get_contents(php://input).
I have already tried to put my memory_limit to -1 with post_max_size to 0 and my upload_max_filesize to 16M.
I tried with a small picture, an heavy one and one between the two.
The small failed. The heavy and the other one are good.
Did any of you have a clue about this problem ?
Edit : I'm using angularJS (angular 1.x.x) on my front-end.

A: Did you set the form encoding type to multipart/form-data?
<form action="foo.php" enctype="multipart/form-data" method="post">...

You didn't say how you were sending the files to the server via AJAX, but this SO answer Angularjs $http post file and form data would probably be helpful to you.


text:
Q: How to stop textview field from flashing when clicked I'm creating a timer application for my android.  It counts down from a specified time (i.e. 8 minutes) to 0.
I have coded it that when the app starts it shows the specified time.  When you click on the TextView displaying the time it starts the count down updating the TextView at the onTick() event.  When you click on the TextView again it will stop the countdown and save the remaining milliseconds to resume when the TextView is clicked the next time (essentially pausing the clock).
Everything works as expected.  However, when the TextView is clicked it disappears until the click is released.  If I hold the click down for 3 seconds then the TextView totally disappears while it is being held and reappears as soon as it is released.
How can I stop this behavior to continue to show the value of the TextView the whole time?
EDIT:
    tvPeriod.setOnLongClickListener( new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            valPeriod = 1;
            tvPeriod.setText( tvPeriodPrefix + "1" );

            return true;
        }
    });

A: You can probably do something like set the background to a color, or even transparent. Actually on the lower level, a Button is descended from a TextView, so that may explain why it can act like a Button.

A: Try with this sample code.
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView tv;
    CountDownTimer countDownTimer;
    boolean isRunning = false;
    long remainingTime = 90000;
    long elapsedTime = 0;

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

        tv = (TextView) findViewById(R.id.tv1);
        tv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isRunning) {
                    isRunning = false;
                    countDownTimer.cancel();
                    remainingTime = elapsedTime;
                } else {
                    countDownTimer = new CountDownTimer(remainingTime, 1000) {

                        public void onTick(long millisUntilFinished) {
                            elapsedTime = millisUntilFinished;
                            tv.setText("seconds remaining: "
                                    + millisUntilFinished / 1000);

                        }

                        public void onFinish() {
                            tv.setText("done!");
                        }
                    }.start();
                    isRunning = true;
                }

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}


text:
Q: Click an array element, show the element with the same index of another array I have a list of elements which is plotted via a ng-repeat and I am using a ng-click to get the index of the element of the array I am clicking on.
This is the html code:

    {{period}}

And this is what is inside the controller:
$scope.periodPercentage = ['a', 'b', 'c', 'd'];
$scope.getIndex = function(period) {
  console.log($scope.periodPercentage.indexOf(period));
};

In another part of the code, I am using again an ng-repeat to show the elements of another array with the same length.

    {{ratio}}

Is there a way to show only the {{ratio}} with the same index of {{period}} via ng-show and hide the other ones?
Thanks in advance for your replies!

A: It may help you.

    {{period}}

function testrahul($scope) {
$scope.periodPercentage = ['a', 'b', 'c', 'd'];
$scope.getindex = function(i){
    console.log(i);
}}

A: You could do that:

    {{period}}

and

    {{ratio}}

see updated fiddle

A: Something along the lines of:

    {{period}}

    {{ratio}}

function setVariable(index){ $scope.someVariable = index;}

A: One solution is this:
  $scope.periodPercentage = ['a', 'b', 'c', 'd'];
  $scope.ratePercentage = ['arate', 'brate', 'crate', 'drate'];
  $scope.rateShowPercentage = angular.copy($scope.ratePercentage);
  $scope.update = function(index){
    $scope.rateShowPercentage  = [$scope.ratePercentage[index]];
  }

In the HTML

    {{period}}

    {{rate}}

working code here

A: Somehing like:

    {{object.data}}

    {{object.data}}

and:

var otherList = [ some data ...]
 var otherListToShow = []

openOther(index){
listToShow.push(otherList[index])
}

A: you need to give $index into ng-click

  {{period}}


text:
Q: Garbage collector: перемещение объекта из поколения в поколение Когда у нас заполняется нулевое поколение кучи, происходит анализ этого поколения: удаляются "мёртвые"  объекты и перемещаются "выжившие" в следующее поколение - 1.  Вопрос: если в поколении 1 недостаточно места для приёма объектов из нулевой кучи, то что происходит? Очистка первого поколения?

UPDATE
Цитата (C# 5.0 in Nutshell, Albahari):

Среда CLR сохраняет раздел Gen() относительно небольшим (максимум 16 Мбайт в 32-битной версии для рабочей станции, с типичным размером от нескольких сотен Кбайт до нескольких Мбайт). Когда раздел Gen() заполняется, сборщик мусора GC инициирует сборку Gen() — что происходит относительно часто. Сборщик мусора применяет похожий порог памяти к разделу Gen1 (который действует как буфер для Gen2), поэтому сборки Gen1 являются тоже относительно быстрыми и частыми. Однако полные сборки мусора, включающие Gen2, занимают намного больше времени и, таким образом, происходят нечасто. Результат полной сборки мусора показан на рис. 12.2.

A: Достижение поколением порогового размера — всего лишь триггер для начала сборки мусора. Когда общий размер объектов в Gen0 станет больше порога, запустится сборщик мусора.
Когда сборщик мусора запустится, он смотрит, не превышает ли суммарный размер объектов в Gen2 порог. Если да, запускается полная, медленная сборка мусора всех трёх поколений.
Если Gen2 в порядке, но суммарный размер объектов а Gen1 превышает порог для Gen1, запускается ускоренная сборка, которая рассматривает только Gen0 и Gen1.
Если же Gen1 тоже в порядке, то запускается ускоренная сборка только Gen0.
Если после сборки Gen0 переполнится Gen1 (то есть, суммарный размер Gen1 станет выше порога), ничего не произойдёт до следующего запуска сборщика мусора. А когда он таки запустится (по переполнению Gen0), он обнаружит переполнение поколения Gen1 и соберёт его тоже.
(Кстати, размеры порогов на текущий момент не фиксированы, и фреймворк динамически подгоняет их во время пробега программы.)

Литература: Jeffrey Richter. The Managed Heap and Garbage Collection in the CLR.

A: Если произойдет "переполнение" (таки у поколений есть пороги) для первого поколения, GC вызовет проверку на первом поколении. Выжившие объекты перейдут во второе, не выжившие - умрут, никакой магии.
Рихтер в CLR via C# в главе 21 "Автоматическое управление памятью (уборка мусора)" хорошо описал это.


text:
Q: Example of a bounded set with measure zero, whose frontier has no measure zero. I am having a hard time trying to answer this question
Give an example of a bounded set $X \subset \mathbb{R}^m$ with zero measure such that $\partial X$ has no measure zero
My attempt: Since $X$ has zero measure, then its interior is empty. So $\partial X$ is equal to the closure of $X$. Then I tried to manipulate Cantor set, since its frontier has no measure zero, but unsuccessfully.
I'd really appreciate your help. Thanks in advance.

A: As pointed in the comments, one example is $X = [0, 1] \cap \mathbb{Q}$, with $X \subset \mathbb{R}$. $X$ is bounded. $X$ has zero measure because $X$ is countable ($X$ is a subset of $\mathbb{Q}$, which is countable). Finally, it's boundary $\partial X$ is $[0, 1]$, which does not have measure zero.


text:
Q: Comparing infinite numbers Suppose you have 2 infinite numbers, say $A$ and $B$.
$A$ is an element of the hyperreals, so that $A$ is greater than every real number.
$B$ is the size of the set of natural numbers, $\aleph_0$
Does it make sense to compare $A$ and $B$? And if so, how can you compare these kind of numbers?

A: In a nutshell: No. Hyperreal numbers are "non-sets objects" while $\aleph_0$ is essentially a notion of size for a set. While hyperreal numbers can be represented as sets (but not only, e.g. in ZF+Atoms the atoms may be given the structure of the hyperreal numbers), they are interpreted as something else, while $\aleph_0$ is a lot more "concrete" as it will always be interpreted as a set of some sort.
There are different notions of infinite numbers. There are hyperreal numbers, ordinal numbers, cardinal numbers, one can view real numbers as infinite sequences of rationals and so infinitely more accurate than rational numbers (just as infinitesimals give us the ability to be more accurate than real numbers).
These notions grew out of some place where they were needed, and sometimes these places are somewhat orthogonal or unrelated (at least not directly).
In this case, we consider cardinals vs. hyperreal numbers. The cardinalities (under the axiom of choice, without the axiom of choice this is an even bigger mess, however with somewhat surprising results - more on that later) are well ordered. This means that between $\aleph_0$ and $\aleph_1$ there are no other cardinals. There are ordinals but they are all countable as sets.
Suppose you could somehow identify an element, call it $B$, in the hyperreals, $^*\mathbb R$, to be $\aleph_0$. What is $B+1$? In cardinalities $\aleph_0+1=\aleph_0$. In the hyperreals this is impossible.
What you could say is that all the elements of the form $B\pm n$ are still "infinite numbers".
The same problem would be met if we chose instead to identify ordinal numbers, since $1+\omega=\omega$ (where $\omega$ is the ordinal representing the natural numbers), this addition is non-commutative, as well not inversible, since subtraction is even less nice than addition when applied on ordinal numbers.
A nice thing to consider: without the axiom of choice there can be cardinal numbers which are not $\aleph$-numbers (that is cannot be well ordered). It is consistent to have $2^{\aleph_0}$ cardinals so that they are ordered (by the natural ordering of cardinalities) like the real numbers. I would expect that it is possible to have that result extended to the hyperreal numbers. (Obviously we cannot expect cardinal addition and multiplication to be anything reversible)
This means that you can interpret the real numbers as cardinals. However none of them is even comparable with $\aleph_0$ (that is, none contain a countable subset).
(You might be interested in my answer here: "Homomorphism" from set of sequences to cardinals? which seems as though it may be somewhat relevant to this discussion.)

A: These are quite different notions, so the answer I suspect most people will give you is "NO" (and I suspect this question might get closed as well). However, I would like to point out that there are a lot of situations in mathematics where seemingly unrelated notions were later brought under the umbrella of some unifying idea. For example, the convex hull of a set and the sigma-algebra generated by a collection of sets, such as was pointed out yesterday: The $\sigma$-algebra of subsets of $X$ generated by a set $\mathcal{A}$ is the smallest sigma algebra including $\mathcal{A}$ Also, there are a lot of situations in mathematics where notational similarity or other essentially non-mathematical resemblance has led to the creation of unifying ideas. For example, fractional derivatives or the idea of complex-iterates of a function.
That said, I doubt anything nontrivial will come out of trying to find a unifying idea underlying these two notions of "infinite number". The only thing that occurs to me is that, in some kind of way that is relative to the underlying "universe" each notion is embedded in, we're looking at the smallest extension outside of certain "small numbers".


text:
Q: Undefined getException method while handling exception in Symfony 5 I created an exception class as follows:
<?php

declare(strict_types=1);

namespace App\Exception;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use function strpos;

final class HTTPExceptionListener
{
    public function onKernelException(ExceptionEvent $event): void
    {
        $exception = $event->getException();
        if (! ($exception instanceof HttpException) || strpos($event->getRequest()->getRequestUri(), '/api/') === false) {
            return;
        }

        $response = new JsonResponse(['error' => $exception->getMessage()]);
        $response->setStatusCode($exception->getStatusCode());
        $event->setResponse($response);
    }
}

I have added following to my services.yaml file:
 App\Exception\HTTPExceptionListener:
        tags:
            - { name: kernel.event_listener, event: kernel.exception }

But I am getting error:
Attempted to call an undefined method named "getException" of class "Symfony\Component\HttpKernel\Event\ExceptionEvent".

A: In Symfony 4.4 the getException method was deprecated, and was removed in Symfony 5.
Use getThrowable instead. Kindly read the documentation.


text:
Q: Swift - Execute multiple commands as root without asking password multiple times I want to write a litte program that checks a couple of directories as root.
I use the following code:
func execute(sudoCommands: String) -> String {
    return(execute(command: "osascript -e \"do shell script \\\"" + sudoCommands + "\\\" with administrator privileges\""))
}

func execute(command: String) -> String {
    var arguments:[String] = []
    arguments.append("-c")
    arguments.append( command )

    let task = Process()
    task.launchPath = "/bin/sh"
    task.arguments = arguments

    let pipe = Pipe()
    task.standardOutput = pipe
    task.standardError = pipe
    task.launch()
    task.waitUntilExit()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()

    return(NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String)
}

func getSize(path: String, asRoot: Bool = false) -> String {

    var result: String!

    if(asRoot){
        result = execute(sudoCommands: "sudo du -shm " + path)
    } else {
        result = execute(command: "du -shm " + path)
    }

    var sizesMB = 0
    for dirResult in result.components(separatedBy: "\n") where dirResult != "" {
        let currentDirSize = dirResult.components(separatedBy: "\t")[0]
        sizesMB = sizesMB + Int(currentDirSize)!
    }

return( "\(sizesMB) MB")
}

But if I run getSize("/Library/Caches/", asRoot: True) multiple times in a row, it (osascript) will always ask for my password again and again...
Is there some way (that's secure) to execute the commands as root without being prompt to enter the password?
I could ask for the password, save it in a variable and use it when necessary, but that really isn't safe or secure and I rather let Apple handle this one for me...


text: Q: Private Style in a StyleSheet with preformatted text I want to create a new Style in my private StyleSheet. I duplicated the Style "Text" and made some alterations. Now I want that a Cell with this style has an expression already filled in, for example "exercise 1.4" (with counters). How can I implement this in the StyleSheet, I already tried TextData[]. Seems, that I always make some syntax mistakes. How can it be done? Many thanks.


text:
Q: Optimize mysql with inner joins and where I have query:
SELECT DISTINCT h.id,
                h.host
FROM pozycje p
INNER JOIN hosty h ON p.host_id = h.id
INNER JOIN keywordy k ON k.id=p.key_id
AND k.bing=0
WHERE h.archive_data_checked IS NULL LIMIT 20

It's fast when some rows exists but if no results exists it takes 2,3 sek to execute. I would like to have less than 1 sec. Explain looks like:
http://tinyurl.com/gogx42n
Table pozycje has 30 000 000 rows, hosty has 4 000 000 rows and keywordy has 40 000 rows. Engine InnoDB, server with 32GB RAM
What indexes or improvements can I do to spped up query when no results exists?
edit:
show table keywordy;
 CREATE TABLE `keywordy` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `main_kw` varchar(255) CHARACTER SET utf8 NOT NULL,
 `keyword` varchar(255) CHARACTER SET utf8 NOT NULL,
 `lang` varchar(10) CHARACTER SET utf8 NOT NULL,
 `searches` int(11) NOT NULL,
 `cpc` float NOT NULL,
 `competition` float NOT NULL,
 `currency` varchar(10) CHARACTER SET utf8 NOT NULL,
 `data` date DEFAULT NULL,
 `adwords` int(11) NOT NULL,
 `monitoring` tinyint(1) NOT NULL DEFAULT '0',
 `bing` tinyint(1) NOT NULL DEFAULT '0',
 PRIMARY KEY (`id`),
 UNIQUE KEY `keyword` (`keyword`,`lang`),
 KEY `id_bing` (`id`,`bing`)
) ENGINE=InnoDB AUTO_INCREMENT=38362 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

A: can pls test this:
SELECT DISTINCT h.id,
                h.host
FROM hosty h
WHERE
    EXISTS ( SELECT 1 FROM keywordy WHERE id=p.key_id AND bing=0)
  AND
    EXISTS ( SELECT 1 FROM pozycje WHERE host_id = h.id)
  AND h.archive_data_checked IS NULL LIMIT 20

A: I would first offer the following question.  Which would have the smaller "set" if you did a query on
select count(*) from KeyWordy where bing = 0
vs
select count(*) from hosty where archive_date_checked IS NULL

I would then try to optimize the query knowing the smaller set and work with that as my primary criteria for indexing.  If KeyWordy is more likely to be the smaller set, I would offer your tables to have the following indexes
table       index
keywordy    (bing, id)   specifically NOT (id, bing) as bing FIRST is optimized for where or JOIN clause
pozycje     (key_id, host_id )
hosty       (archive_data_checked, id, host)

SELECT DISTINCT
      h.id,
      h.host
   FROM
      Keywordy k
         JOIN pozycje p
            ON k.id = p.key_id
            JOIN hosty h
               on archive_data_checked IS NULL
              AND p.host_id = h.id
   WHERE
      k.bing = 0
   LIMIT
      20

if the HOSTY table would be smaller base on the archive_data_checked IS NULL, I offer the following
table       index
pozycje     (host_id, key_id )    reversed of other option

SELECT DISTINCT
      h.id,
      h.host
   FROM
      hosty h
         JOIN pozycje p
            ON h.id = p.host_id
            JOIN Keywordy k
               on k.bing = 0
              AND p.key_id = k.id
   WHERE
      h.archive_data_checked IS NULL
   LIMIT
      20

One FINAL option, might be to add the keyword "STRAIGHT_JOIN" such as
select STRAIGHT_JOIN DISTINCT ... rest of query

If it works for you, what timing improvements does this offer.


text:
Q: Time consuming in xml parsing in android i am using a map in my android app and display multiple item on map. all data coming from web services (XML). i am using SAX parser for that. and parsing in asynchronous task.
my problem is that data is too large and my loader show for about 1 minutes for parsing xml.
so is there any way to resolve this problem.
i have one idea that when first item will parse than it will show on map and all remaining item will be loaded in thread. but how can i implement this?
is it possible?
need some suggestion and guidance.   thanks in advance.


text:
Q: Android custom View (TextView+Button+some customized behaviors)? This should be very easy to do, but somehow after some 15 minutes searching I still can't get the answer:
I want to make a custom Android View combining a TextView and a Button, plus some customized behaviors/methods, let's say when I click the button it should change the TextView to "Hello, world!".
I know that I'll have to extends the View class, and design the layout in a XML, then do some magic to link the two. Could you tell me what the magic is? I know how to do this in an Activity, but not in a custom View.
EDITED
Ok, so I found out I need to use a Inflater to inflate my class with the child views defined in a layout. Here's what I got:
public class MyView extends View  {

private TextView text;
private Button button;

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    View.inflate(context, R.layout.myview, null);
}

@Override
protected void onFinishInflate() {
    super.onFinishInflate();
    text = (TextView) findViewById(R.id.text);
    button = (Button) findViewById(R.id.button);
}
}

However, the text and button child views were null. Any idea? (The XML is very simple without any fancy edit, i just grabbed a TextView and a Button from the eclipse toolbar and throw in.)

A: Ok, so the answer to my own question is: (i) go get dinner, (ii) extends LinearLayout instead of View, this makes it a ViewGroup and thus can be passed into the inflate(...) method but don't have to override the onLayout(...) method. The updated code would be:
public class MyView extends LinearLayout  {
    private TextView text;
    private Button button;

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        View.inflate(context, R.layout.myview, this);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        text = (TextView) findViewById(R.id.text);
        button = (Button) findViewById(R.id.button);
    }
}


text:
Q: Write image as the value of sequence file with pyspark I am using pyspark to write sequence files, the key is image filename and the value is the image representing by bytestring
from PIL import Image

def get_image(filename):
 s = StringIO()
 im=io.imread(filename)
 io.imsave(s, im)
 return [(filename, s)]

rdd  =  sc.parallelize(filenames)
rdd.flatMap(get_image).saveAsSequenceFile("/user/myname/output")

but pyspark throws an exception which indicates that pickle does not support the format
Caused by: net.razorvine.pickle.InvalidOpcodeException: opcode not implemented: OBJ
    at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:224)
    at net.razorvine.pickle.Unpickler.load(Unpickler.java:85)
    at net.razorvine.pickle.Unpickler.loads(Unpickler.java:98)
    at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:151)
    at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:150)
    at scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:371)
    at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:308)
    at scala.collection.Iterator$class.foreach(Iterator.scala:727)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
    at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:48)
    at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:103)
    at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:47)
    at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:273)
    at scala.collection.AbstractIterator.to(Iterator.scala:1157)
    at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:265)
    at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1157)
    at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:252)
    at scala.collection.AbstractIterator.toArray(Iterator.scala:1157)
    at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$28.apply(RDD.scala:1298)
    at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$28.apply(RDD.scala:1298)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1850)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1850)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:88)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    ... 1 more

A: The OBJ opcode for pickling is used when you're trying to encode/decode a python class/object for serialization. In my case, I didn't intend to write an object to the sequence file, so the fix for me was just fixing that bug.
As for the overall ecosystem, the problem is that spark uses Pyrolite 4.13 but OBJ encoding/decoding wasn't introduced into the Pyrolite library until version 4.17. As far as what to do about this, I suppose you have a few options:

*

*Convince the spark maintainers, either through a pull request, or github issue, to use a later version of Pyrolite.

*Build your own version of Spark, using that version of Pyrolite

*Don't write classes/objects to your sequence files.


text:
Q: Permutation representations of general linear groups over finite fields Let $q=p^f$ be a prime power, $V$ is a $n$-dimensional vector space over $GF(q)$ and $G=GL(n,q)=GL(V)$. Is every transitive permutation representation $\rho$ of $G$ on $q^n-1$ points isomorphic to the natural action of $\tau\in G$ on $V\setminus\{0\}$?
Thanks in advance!

A: Apologies for all of my incorrect comments about Question 2. The correct answer is yes for $q=2$, but no otherwise.
A transitive permutation representation of $G$ of degree $q^n-1$ corresponds to a subgroup of $G$ of index $q^n-1$. The stabilizer $H$ of a 1-dimensional subspace of $V$ is a maximal subgroup of $G$ of index $(q^n-1)/(q-1)$. It has a normal elementary abelian subgroup $N$ of order $q^{n-1}$, and $H/N$ is isomorphic to a direct product $C_{q-1} \times {\rm GL}_{n-1}(q)$. This is easy to see directly.
Thje complete inverse image in $H$ of the direct factor ${\rm GL}_{n-1}(q)$ is the stabilizer of a nonzero vector in $V$, and so corresponds to the natural action on vectors. But for $q>2$ there are several other subgroups of $H$ with the same index $q-1$, such as the inverse image in $H$  of $C_{q-1} \times {\rm SL}_{n-1}(q)$. Since these are not isomorphic to the stabilizer of a vector, their corresponding permutation representations are not isomorphic to the natural one.


text:
Q: Java Waiting for all threads to complete Edit: My question is different, it has no relevance to the linked question.
I've following code with completion handler.
FutureTask<Void> futureTask = new FutureTask<Void>(() -> {
    System.out.println("callback");
    return null;
});

Runnable task = () -> {
    for(int i=0; i<5; i++) {
        System.out.println(Thread.currentThread().getName() + " " + i);
    }
    futureTask.run();
};

new Thread(task).start();
new Thread(task).start();

Basically I'm looking for completion handler for variable number of tasks, or is there another approach?
I'm inspired from this answer but seems it's part of some library while I'm looking for a native solution.
Completable Future???
Here's my attempt with completable futures with the result handler at the end.
public void test() {
    CompletableFuture
            .supplyAsync(() -> method1())
            .supplyAsync(() -> method2())
            .supplyAsync(() -> result());
}

public String method1() {
    System.out.println("calling 1");
    return "method1";
}

public String method2() {
    System.out.println("calling 2");
    return "method2";
}

public String result() {
    System.out.println("result");
    return "result";
}

A: Assuming that your method result() returns a value that you want to retrieve, i.e. is declared like Type result(), you can use
CompletableFuture<Type> f = CompletableFuture.allOf(
    CompletableFuture.runAsync(() -> method1()),
    CompletableFuture.runAsync(() -> method2())
).thenApply(_void -> result());

Each runAsync creates an individual asynchronous CompletableFuture that will be completed once the Runnable has been executed. It's the same as supplyAsync, except that it doesn't return a result.
allOf create a CompletableFuture that will be completed, once all specified futures are completed, hence, any chained dependent action will only run after all futures have been completed. By using thenApply we create a dependent future that will be completed with the return value of result().
If result() is not intended to return a value, but just an action that should run after all other actions have been completed, you can use
CompletableFuture.allOf(
    CompletableFuture.runAsync(() -> method1()),
    CompletableFuture.runAsync(() -> method2())
).thenRun(() -> result());

instead.

A: One easy approach is to submit your Runnable(s) to an ExecutorService, then call shutdown, then call awaitTermination:
ExecutorService executor = Executors.newWorkStealingPool();
executor.submit(task);
executor.submit(task);

executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

No need to use CompletableFuture.

A: Save the links to the threads you've created, and call join()
Thread a = new Thread(task);
Thread b = new Thread(task);
a.start();
b.start();

a.join();
b.join();
//guaranteed that both threads have completed here

A: Depending on how much control you want you could use a ThreadPoolExecutor:
tpe.execute(Runnable);
Wait for the active count == 0;
then shutdown the executor.
Or keep the threads in a structure.
Wait for an specific TTL then interrupt them if the state is RUNNABLE


text:
Q: C++ double wierd behaviour during incrementing in for loop I was making a progress bar when I noticed this, Something wierd is happening when incrementing doubles in for loop.
EDIT : I am not asking why floating points are broken !! My issue is that the for loop is iterating one extra time in case 1 and one less time in case 4 !
I have created 4 test cases. Please See the code below :-
#include <iostream>

using namespace std;

int main()
{
    cout << endl << "Should End on 0.9 :-" << endl; // Abnormal
    for (double i = 0 ; i < 1 ; i += 0.1) cout << i << endl;

    cout << endl << "Should End on 1 :-" << endl;
    for (double i = 0 ; i <= 1 ; i += 0.1) cout << i << endl;

    cout << endl << "Should End on 0.99 :-" << endl;
    for (double i = 0 ; i < 1 ; i += 0.01) cout << i << endl;

    cout << endl << "Should End on 1 :-" << endl;   // Abnormal
    for (double i = 0 ; i <= 1 ; i += 0.01) cout << i << endl;
}

Output :-
Should End on 0.9 :-
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1

Should End on 1 :-
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1

Should End on 0.99 :-
0
0.01
0.02
0.03
0.04
0.05
0.06
0.07
0.08
0.09
0.1
0.11
0.12
0.13
0.14
0.15
0.16
0.17
0.18
0.19
0.2
0.21
0.22
0.23
0.24
0.25
0.26
0.27
0.28
0.29
0.3
0.31
0.32
0.33
0.34
0.35
0.36
0.37
0.38
0.39
0.4
0.41
0.42
0.43
0.44
0.45
0.46
0.47
0.48
0.49
0.5
0.51
0.52
0.53
0.54
0.55
0.56
0.57
0.58
0.59
0.6
0.61
0.62
0.63
0.64
0.65
0.66
0.67
0.68
0.69
0.7
0.71
0.72
0.73
0.74
0.75
0.76
0.77
0.78
0.79
0.8
0.81
0.82
0.83
0.84
0.85
0.86
0.87
0.88
0.89
0.9
0.91
0.92
0.93
0.94
0.95
0.96
0.97
0.98
0.99

Should End on 1 :-
0
0.01
0.02
0.03
0.04
0.05
0.06
0.07
0.08
0.09
0.1
0.11
0.12
0.13
0.14
0.15
0.16
0.17
0.18
0.19
0.2
0.21
0.22
0.23
0.24
0.25
0.26
0.27
0.28
0.29
0.3
0.31
0.32
0.33
0.34
0.35
0.36
0.37
0.38
0.39
0.4
0.41
0.42
0.43
0.44
0.45
0.46
0.47
0.48
0.49
0.5
0.51
0.52
0.53
0.54
0.55
0.56
0.57
0.58
0.59
0.6
0.61
0.62
0.63
0.64
0.65
0.66
0.67
0.68
0.69
0.7
0.71
0.72
0.73
0.74
0.75
0.76
0.77
0.78
0.79
0.8
0.81
0.82
0.83
0.84
0.85
0.86
0.87
0.88
0.89
0.9
0.91
0.92
0.93
0.94
0.95
0.96
0.97
0.98
0.99

[Program finished]

First case should end on 0.9 but it's ending on 1
And 4th case should end on 1 but it's ending on 0.99
2nd and 3rd case are working normally.
Any ideas what's going on here ?
What am I doing wrong ?
I am using Clang compiler on aarch64 cpu.

A: The answer is that floating points are "broken" - or at least not trusted for exact values.
In loop 1, when it unexpectedly prints 1.0, the actual value is slightly less (0.999...), so the check that it is less than 1 is still true.
In loop 4, when you expect it to print 1.0, the actual value is slightly higher (1.0001 or something), so the check that it is <= 1 fails.


text:
Q: Can't resize  container with the use of transitions I am building a page in HTML/CSS at the moment and ran into a problem with the transition animations. Some context. First here is the HTML code:
This is the HTML code:

        <form id="contact" action="" method="post">

Your script has been approved!

            <fieldset>
            <textarea class = "textarea-script" id="script" style="display: none;"></textarea>
            </fieldset>
        </form>


text:
Q: How to handle SVN externals when migrating to Git I'm currently migrating our SVN repositories to git and I'm not sure how to handle the SVN externals.
I normally would clone and add them as git submodules since I want to keep track of the changes and also push commits to the submodule's repo. Unfortunately git by default clones the whole repo but I only need a subdirectory of it.
The external repo looks similar to this.
external/bar/lib/
external/foo/
external/foo.sln
...

So I thought about using sparse-checkout to only clone the external/bar/lib/directory to my main project but I'm not sure If I still can do normal git operations like commit, push, pull and branch in the submodule when using a sparse checkout or how to handle the case when I also want to include external/foo/ in my main project.

A: Ideally, each relevant folder of external/ should have been git-svn exported in their own individual Git repository:
external/bar/lib/ => lib.git
external/foo/ => foo.git

That way, no need to worry about sparse checkout (which would indeed limit the ability to push back commits)


text:
Q: The manual discount input not working on Shopify cart page I need a coupon code input on my cart page but it doesn't seem to work in its plain form:
<input type="hidden" name="discount" value="{{ settings.modal_promo_code }}" >

I have it right before the submit button, inside the form.
Live coupons are not being applied to the order on the checkout page.
Is there anything else I need to do for it to work?
Edit: The form looks like this —
<form action="/cart" method="post" class="cart">
         <input type="hidden" name="discount" value="{{ settings.modal_promo_code }}" >

And it redirects to a URL like this:
https://store.com/4934605xxxx/checkouts/04d6478feeb9d3262fbea5571b682ebc?_ga=2.260083023.358228188.1608464294-110675315.1604953057
it seems there is a conflict that doesn't let the discount apply to the URL or get removed by ?_ga=2.260083023.358228188.1608464294-110675315.1604953057 because when disabling the JS in the chrome setting and submitting the checkout again it works and the discount is getting applied.
any thoughts on this? how can I get this working like this:
https://store.com/4934605xxxx/checkouts/04d6478feeb9d3262fbea5571b682ebc?_ga=2.260083023.358228188.1608464294-110675315.1604953057&discount=TBSRWDVS
thank you

A: As long as your cart isn't utilizing AJAX to upgrade and divert this ought to work.
The checkout page acknowledges a get contention of ?rebate= and including a field with a name="discount" will include that contention to the checkout.
This works as it were in the event that you yield the standard shape specifically. (in the event that you overhaul the cart, the field rebate content will not be present and you wish to re-enter it again) If you must overhaul the shape you may get to keep the markdown code in a few ways, through overhauling the cart with ajax or putting away it as a cookie.
So your code ought to be working, I twofold-checked it on my dev store and there are no issues, it applies a rebate to the checkout page since the get contention is present.
PS: This does not include a rebate to the cart question, it is as it permitted for the checkout divert to incorporate a get contention, nothing else. So usually comparable to making an interface with
Checkout

A: A late response, but want to answer your questions and share a solution for this.
First off no you cannot apply a discount code to cart the way you discribed, it is possible and doable but a bit more complicated than ading an input field to a form.
There is no OOTB Shopify solution for this, but there is some undocumented API endpoints that can be used to create this feature.
Check out Shopify Discounter Web Component, it supports:

*

*Discount codes

*Automatic discounts

*Gift cards

*Discount combinations

*Multi currencies

*Internalization

*Style customization using css variables

*Place it anywhere in your store

Hope this helps.


text:
Q: displaying boolean value / invalid qualifier Maybe because it's been a long day......
I don't get it.
Why does this code give me an 'invalid qualifier' msg?
Sub UsingBooleans()
Dim MastNameNew As Boolean
MsgBox "mastnamenew value = " & MastNameNew.Value
End Sub

A: To your error : MastNameNew is a Boolean variable with only possible value as "False (0)" or "True (1)". So there are no properties available for a Boolean.
Please find the below code
If you want answer as "False" or True Then use below code:
Sub UsingBooleans()
Dim MastNameNew As Boolean
MsgBox "mastnamenew value = " & MastNameNew
End Sub

And if you want the answer as "0" or "1" then use the below code:
Sub UsingBooleans()
Dim MastNameNew As Boolean
MsgBox "mastnamenew value = " & CInt(MastNameNew)
End Sub


text:
Q: Split camelCase word into words with php preg_match (Regular Expression) How would I go about splitting the word:
oneTwoThreeFour

into an array so that I can get:
one Two Three Four

with preg_match ?
I tired this but it just gives the whole word
$words = preg_match("/[a-zA-Z]*(?:[a-z][a-zA-Z]*[A-Z]|[A-Z][a-zA-Z]*[a-z])[a-zA-Z]*\b/", $string, $matches)`;

A: You can use preg_split as:
$arr = preg_split('/(?=[A-Z])/',$str);

See it
I'm basically splitting the input string just before the uppercase letter. The regex used (?=[A-Z]) matches the point just before a uppercase letter.

A: You can also use preg_match_all as:
preg_match_all('/((?:^|[A-Z])[a-z]+)/',$str,$matches);

Explanation:
(        - Start of capturing parenthesis.
 (?:     - Start of non-capturing parenthesis.
  ^      - Start anchor.
  |      - Alternation.
  [A-Z]  - Any one capital letter.
 )       - End of non-capturing parenthesis.
 [a-z]+  - one ore more lowercase letter.
)        - End of capturing parenthesis.

A: $string = preg_replace( '/([a-z0-9])([A-Z])/', "$1 $2", $string );

The trick is a repeatable pattern  $1 $2$1 $2 or lower UPPERlower UPPERlower etc....
for example
helloWorld = $1 matches "hello", $2 matches "W" and $1 matches "orld" again so in short you get $1 $2$1 or "hello World", matches HelloWorld as $2$1 $2$1 or again "Hello World".  Then you can lower case them uppercase the first word or explode them on the space, or use a _ or some other character to keep them separate.
Short and simple.

A: I know that this is an old question with an accepted answer, but IMHO there is a better solution:
<?php // test.php Rev:20140412_0800
$ccWord = 'NewNASAModule';
$re = '/(?#! splitCamelCase Rev:20140412)
    # Split camelCase "words". Two global alternatives. Either g1of2:
      (?<=[a-z])      # Position is after a lowercase,
      (?=[A-Z])       # and before an uppercase letter.
    | (?<=[A-Z])      # Or g2of2; Position is after uppercase,
      (?=[A-Z][a-z])  # and before upper-then-lower case.
    /x';
$a = preg_split($re, $ccWord);
$count = count($a);
for ($i = 0; $i < $count; ++$i) {
    printf("Word %d of %d = \"%s\"\n",
        $i + 1, $count, $a[$i]);
}
?>

Note that this regex, (like codaddict's '/(?=[A-Z])/' solution - which works like a charm for well formed camelCase words), matches only a position within the string and consumes no text at all. This solution has the additional benefit that it also works correctly for not-so-well-formed pseudo-camelcase words such as: StartsWithCap and: hasConsecutiveCAPS.
Input:
oneTwoThreeFour
StartsWithCap
hasConsecutiveCAPS
NewNASAModule
Output:
Word 1 of 4 = "one"
Word 2 of 4 = "Two"
Word 3 of 4 = "Three"
Word 4 of 4 = "Four"
Word 1 of 3 = "Starts"
Word 2 of 3 = "With"
Word 3 of 3 = "Cap"
Word 1 of 3 = "has"
Word 2 of 3 = "Consecutive"
Word 3 of 3 = "CAPS"
Word 1 of 3 = "New"
Word 2 of 3 = "NASA"
Word 3 of 3 = "Module"
Edited: 2014-04-12: Modified regex, script and test data to correctly split: "NewNASAModule" case (in response to rr's comment).

A: When determining the best pattern for your project, you will need to consider the following pattern factors:

*

*Accuracy (Robustness)  -- whether the pattern is correct in all cases and is reasonably future-proof

*Efficiency -- the pattern should be direct, deliberate, and avoid unnecessary labor

*Brevity -- the pattern should use appropriate techniques to avoid unnecessary character length

*Readability -- the pattern should be keep as simple as possible

The above factors also happen to be in the hierarchical order that strive to obey.  In other words, it doesn't make much sense to me to prioritize 2, 3, or 4 when 1 doesn't quite satisfy the requirements.  Readability is at the bottom of the list for me because in most cases I can follow the syntax.
Capture Groups and Lookarounds often impact pattern efficiency.  The truth is, unless you are executing this regex on thousands of input strings, there is no need to toil over efficiency.  It is perhaps more important to focus on pattern readability which can be associated with pattern brevity.
Some patterns below will require some additional handling/flagging by their preg_ function, but here are some pattern comparisons based on the OP's sample input:
preg_split() patterns:

*

*/^[^A-Z]+\K|[A-Z][^A-Z]+\K/ (21 steps)

*/(^[^A-Z]+|[A-Z][^A-Z]+)/ (26 steps)

*/[^A-Z]+\K(?=[A-Z])/ (43 steps)

*/(?=[A-Z])/ (50 steps)

*/(?=[A-Z]+)/ (50 steps)

*/([a-z]{1})[A-Z]{1}/ (53 steps)

*/([a-z0-9])([A-Z])/ (68 steps)

*/(?<=[a-z])(?=[A-Z])/x  (94 steps) ...for the record, the x is useless.

*/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/ (134 steps)

preg_match_all() patterns:

*

*/[A-Z]?[a-z]+/  (14 steps)

*/((?:^|[A-Z])[a-z]+)/ (35 steps)

I'll point out that there is a subtle difference between the output of preg_match_all() and preg_split().  preg_match_all() will output a 2-dimensional array, in other words, all of the fullstring matches will be in the [0] subarray; if there is a capture group used, those substrings will be in the [1] subarray.  On the other hand, preg_split() only outputs a 1-dimensional array and therefore provides a less bloated and more direct path to the desired output.
Some of the patterns are insufficient when dealing with camelCase strings that contain an ALLCAPS/acronym substring in them.  If this is a fringe case that is possible within your project, it is logical to only consider patterns that handle these cases correctly.  I will not be testing TitleCase input strings because that is creeping too far from the question.
New Extended Battery of Test Strings:
oneTwoThreeFour
hasConsecutiveCAPS
newNASAModule
USAIsGreatAgain

Suitable preg_split() patterns:

*

*/[a-z]+\K|(?=[A-Z][a-z]+)/ (149 steps) *I had to use [a-z] for the demo to count properly

*/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/ (547 steps)

Suitable preg_match_all() pattern:

*

*/[A-Z]?[a-z]+|[A-Z]+(?=[A-Z][a-z]|$)/ (75 steps)

Finally, my recommendations based on my pattern principles / factor hierarchy. Also, I recommend preg_split() over preg_match_all() (despite the patterns having less steps) as a matter of directness to the desired output structure.  (of course, choose whatever you like)
Code: (Demo)
$noAcronyms = 'oneTwoThreeFour';
var_export(preg_split('~^[^A-Z]+\K|[A-Z][^A-Z]+\K~', $noAcronyms, 0, PREG_SPLIT_NO_EMPTY));
echo "\n---\n";
var_export(preg_match_all('~[A-Z]?[^A-Z]+~', $noAcronyms, $out) ? $out[0] : []);

Code: (Demo)
$withAcronyms = 'newNASAModule';
var_export(preg_split('~[^A-Z]+\K|(?=[A-Z][^A-Z]+)~', $withAcronyms, 0, PREG_SPLIT_NO_EMPTY));
echo "\n---\n";
var_export(preg_match_all('~[A-Z]?[^A-Z]+|[A-Z]+(?=[A-Z][^A-Z]|$)~', $withAcronyms, $out) ? $out[0] : []);

A: I took cool guy Ridgerunner's code (above) and made it into a function:
echo deliciousCamelcase('NewNASAModule');

function deliciousCamelcase($str)
{
    $formattedStr = '';
    $re = '/
          (?<=[a-z])
          (?=[A-Z])
        | (?<=[A-Z])
          (?=[A-Z][a-z])
        /x';
    $a = preg_split($re, $str);
    $formattedStr = implode(' ', $a);
    return $formattedStr;
}

This will return: New NASA Module

A: While ridgerunner's answer works great, it seems not to work with all-caps substrings that appear in the middle of sentence. I use following and it seems to deal with these just alright:
function splitCamelCase($input)
{
    return preg_split(
        '/(^[^A-Z]+|[A-Z][^A-Z]+)/',
        $input,
        -1, /* no limit for replacement count */
        PREG_SPLIT_NO_EMPTY /*don't return empty elements*/
            | PREG_SPLIT_DELIM_CAPTURE /*don't strip anything from output array*/
    );
}

Some test cases:
assert(splitCamelCase('lowHigh') == ['low', 'High']);
assert(splitCamelCase('WarriorPrincess') == ['Warrior', 'Princess']);
assert(splitCamelCase('SupportSEELE') == ['Support', 'SEELE']);
assert(splitCamelCase('LaunchFLEIAModule') == ['Launch', 'FLEIA', 'Module']);
assert(splitCamelCase('anotherNASATrip') == ['another', 'NASA', 'Trip']);

A: A functionized version of @ridgerunner's answer.
/**
 * Converts camelCase string to have spaces between each.
 * @param $camelCaseString
 * @return string
 */
function fromCamelCase($camelCaseString) {
        $re = '/(?<=[a-z])(?=[A-Z])/x';
        $a = preg_split($re, $camelCaseString);
        return join($a, " " );
}

A: Another option is matching /[A-Z]?[a-z]+/ - if you know your input is on the right format, it should work nicely.
[A-Z]? would match an uppercase letter (or nothing). [a-z]+ would then match all following lowercase letters, until the next match.
Working example: https://regex101.com/r/kNZfEI/1

A: You can split on a "glide" from lowercase to uppercase thus:
$parts = preg_split('/([a-z]{1})[A-Z]{1}/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
//PREG_SPLIT_DELIM_CAPTURE to also return bracketed things
var_dump($parts);

Annoyingly you will then have to rebuild the words from each corresponding pair of items in $parts
Hope this helps

A: First of all codaddict thank you for your pattern, it helped a lot!
I needed a solution that works in case a preposition 'a' exists:
e.g. thisIsACamelcaseSentence.
I found the solution in doing a two step preg_match and made a function with some options:
/*
 * input: 'thisIsACamelCaseSentence' output: 'This Is A Camel Case Sentence'
 * options $case: 'allUppercase'[default] >> 'This Is A Camel Case Sentence'
 *                'allLowerCase'          >> 'this is a camel case sentence'
 *                'firstUpperCase'        >> 'This is a camel case sentence'
 * @return: string
 */

function camelCaseToWords($string, $case = null){
    isset($case) ? $case = $case : $case = 'allUpperCase';

    // Find first occurances of two capitals
    preg_match_all('/((?:^|[A-Z])[A-Z]{1})/',$string, $twoCapitals);

    // Split them with the 'zzzzzz' string. e.g. 'AZ' turns into 'AzzzzzzZ'
    foreach($twoCapitals[0] as $match){
        $firstCapital = $match[0];
        $lastCapital = $match[1];
        $temp = $firstCapital.'zzzzzz'.$lastCapital;
        $string = str_replace($match, $temp, $string);
    }

    // Now split words
    preg_match_all('/((?:^|[A-Z])[a-z]+)/', $string, $words);

    $output = "";
    $i = 0;
    foreach($words[0] as $word){

            switch($case){
                case 'allUpperCase':
                $word = ucfirst($word);
                break;

                case 'allLowerCase':
                $word = strtolower($word);
                break;

                case 'firstUpperCase':
                ($i == 0) ? $word = ucfirst($word) : $word = strtolower($word);
                break;
            }

            // remove te 'zzzzzz' from a word if it has
            $word = str_replace('zzzzzz','', $word);
            $output .= $word." ";
            $i++;
    }
    return $output;
}

Feel free to use it, and in case there is an 'easier' way to do this in one step please comment!

A: Full function based on @codaddict answer:
function splitCamelCase($str) {
    $splitCamelArray = preg_split('/(?=[A-Z])/', $str);

    return ucwords(implode($splitCamelArray, ' '));
}


text:
Q: Calling and wrapping C function in Nodejs (Emscripten) I'm new to emscripten and web development.
Recently, I'm trying to build a node.js module based on C library.
I'm testing with a simple function like int add(int a, int b).
I use MODULARIZE to compile the C library to let it pass the module as a wrapped promise function instead of global Modules.
I can call the function in javascript with ccall method like how the emscripten document stated.
factory().then(instance => {
   instance.ccall('add', 'number', ['number', 'number'], [1, 1]);
});

But how can I wrap the function in a way that lets me call the function without dealing with Promises?
eg.
let sum = add(1, 2);
// sum = 3;

A: You can create a standalone wasm binary and then use WebAssembly.Instance to act as a wrapper.
First create a c file with no main.
#include <emscripten/emscripten.h>

EMSCRIPTEN_KEEPALIVE int add(int a, int b)
{
    return a + b;
}

NOTE: You have to use EMSCRIPTEN_KEEPALIVE before every function you want to export.
Then compile to standalone wasm using
$ emcc {Path to your c file } -o {The name of stand alone wasm} --no-entry

NOTE: You have to write extension in file names.
For example $ emcc abc.c -o xyz.wasm --no-entry should generate a single xyz.wasm and nothing else.

Now in your JS file, you can do
const readFileSync = require('fs').readFileSync;
const wasm_module = new WebAssembly.Instance(new
WebAssembly.Module(readFileSync(**{Path to the .wasm file you generated}**)));

Then all or your exported functions will be available in wasm_module.exports, so you can do something like
const add = wasm_module.exports.add;
let sum = add(1, 2);
// sum = 3

UPDATE
Now node supports experimantal wasm modules. So instead of that long JS code you can just import it from .wasm file directly, like:
import * from '**{Path to .wasm file you generated}**' as wasm_module;
let sum = wasm_module.add(1, 2);
// sum = 3

NOTE: This feature is experimental so you will need to enable it explicitly. i.e. Instead of $ node script.js, use $ --experimental-wasm-modules script.js.


text:
Q: Throw int to show that only the double catch handler executes... Why does this double handler catch an int? I have this code here:
int main()
{
   try // throw int
   {
      int a = 7;
      double b = 9.9;

      // throw int to show that only the double catch handler executes
      throw a < b ? a : b;
   } // end try
   catch ( int x ) // catch ints
   {
      cerr << "The int value " << x << " was thrown\n";
   } // end catch
   catch ( double y ) // catch doubles
   {
      cerr << "The double value " << y << " was thrown\n";
   } // end catch
} // end main

The output yields:
The double value 7 was thrown

I am trying to understand why the int (a=7) was caught by the double handler.
In other words, why wasn't the int handler executed, even though it comes before the double handler?
Could it be due to some implicit conversion? If so, I'm not quite sure how the conditionals (a and b) are involved.
Any help would be grateful. Thanks!