text:
Q: How Can I Configure Azure B2C Automatically? I have been following several Microsoft tutorials to configure Azure B2C with my web app and rest api. e.g. https://learn.microsoft.com/en-ca/azure/active-directory-b2c/tutorial-single-page-app-webapi?tabs=app-reg-ga
There was a lot of back and forth and now it is working.
All of the config was done in the portal and now it feels very fragile as it took me several attempts to get it all right.
The rest of my Azure deployment is configured with Terraform, Ansible and Azure CLI.
I couldn't see any support for B2C for any of these.
Is there an alternative? Can you export the config to a file as a backup?
What if something breaks? How do I roll back to a previously working version?

A: You can use the graph api and you can control it with a CICD pipeline.
https://learn.microsoft.com/en-us/azure/active-directory-b2c/microsoft-graph-operations
https://learn.microsoft.com/en-us/azure/active-directory-b2c/deploy-custom-policies-devops

A: You can automate the process by using below Powershell script to create a service principal and provider.tf:
#!/bin/bash

error()
{
  if [[ -n "$@" ]]
  then
    tput setaf 1
    echo "ERROR: $@" >&2
    tput sgr0
  fi

  exit 1
}

yellow() { tput setaf 3; cat - ; tput sgr0; return; }
cyan()   { tput setaf 6; cat - ; tput sgr0; return; }

# Grab the Azure subscription ID
subId=$(az account show --output tsv --query id)
[[ -z "$subId" ]] && error "Not logged into Azure as expected."

# Check for existing provider.tf
if [[ -f provider.tf ]]
then
  echo -n "The provider.tf file exists.  Do you want to overwrite? [Y/n]: "
  read ans
  [[ "${ans:-Y}" != [Yy] ]] && exit 0
fi

sname="terraform-${subId}-sp"
name="http://${sname}"

# Create the service principal
echo "az ad sp create-for-rbac --name \"$name\"" | yellow
spout=$(az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/$subId" --name "$sname" --output json)

# If the service principal has been created then offer to reset credentials
if [[ "$?" -ne 0 ]]
then
  echo -n "Service Principal already exists. Do you want to reset credentials? [Y/n]: "
  read ans
  if [[ "${ans:-Y}" = [Yy] ]]
  then spout=$(az ad sp credential reset --name "$name" --output json)
  else exit 1
  fi
fi

[[ -z "$spout" ]] && error "Failed to create / reset the service principal $name"

# Echo the json output
echo "$spout" | yellow

# Derive the required variables
clientId=$(jq -r .appId <<< $spout)
clientSecret=$(jq -r .password <<< $spout)
tenantId=$(jq -r .tenant <<< $spout)

echo -e "\nWill now create a provider.tf file.  Choose output type."
PS3='Choose provider block type: '
options=("Populated azurerm block" "Empty azurerm block with environment variables" "Quit")
select opt in "${options[@]}"
do
  case $opt in
    "Populated azurerm block")
      cat > provider.tf <<-END-OF-STANZA
    provider "azurerm" {
      subscription_id = "$subId"
      client_id       = "$clientId"
      client_secret   = "$clientSecret"
      tenant_id       = "$tenantId"
    }
    END-OF-STANZA

      echo -e "\nPopulated provider.tf:"
      cat provider.tf | yellow
      echo
      break
      ;;
    "Empty azurerm block with environment variables")
      echo "provider \"azurerm\" {}" > provider.tf
      echo -e "\nEmpty provider.tf:"
      cat provider.tf | yellow
      echo >&2

      export ARM_SUBSCRIPTION_ID="$subId"
      export ARM_CLIENT_ID="$clientId"
      export ARM_CLIENT_SECRET="$clientSecret"
      export ARM_TENANT_ID="$tenantId"

      echo "Copy the following environment variable exports and paste into your .bashrc file:"
      cat <<-END-OF-ENVVARS | cyan
    export ARM_SUBSCRIPTION_ID="$subId"
    export ARM_CLIENT_ID="$clientId"
    export ARM_CLIENT_SECRET="$clientSecret"
    export ARM_TENANT_ID="$tenantId"
    END-OF-ENVVARS
      break
      ;;
    "Quit")
      exit 0
      ;;
    *) echo "invalid option $REPLY";;
  esac
done

echo "To log in as the Service Principal then run the following command:"
echo "az login --service-principal --username \"$clientId\" --password \"$clientSecret\" --tenant \"$tenantId\"" | cyan

exit 0

The script will interactively:

*

*Create the service principal (or resets the credentials if it already exists)

*Prompts to choose either a populated or empty provider.tf azurerm provider block
exports the environment variables if you selected an empty block (and display the commands)

*Display the az login command to log in as the service principal

The following command will download and run it:
uri=https://raw.githubusercontent.com/azurecitadel/azurecitadel.github.io/master/automation/terraform/createTerraformServicePrincipal.sh
curl -sL $uri > createTerraformServicePrincipal.sh && chmod 750 createTerraformServicePrincipal.sh
./createTerraformServicePrincipal.sh

Refer to this great article by Richard Cheney on this - https://azurecitadel.com/automation/terraform/lab5/


text:
Q: Content Security Policy: Loading external javascript in Chrome extension I want to host my javascript file instead of packing it with the extension. I have read about whitelisting cross domain with Content Security Policy. This is what I have, but it throws error
"Could not load javascript '' for content script."
manifest.json
{
  "name": "My Chrome App",
  "version": "1.0",
  "manifest_version": 2,

  "content_scripts": [{
            "matches": ["<all_urls>"],
            "js": ["https://example.com/platform/myjs.js"],
            "run_at": "document_end"
  }],

  "background": {
        "scripts":["background.js"]
  },

  "description": "My app description goes here", //on hover
  "icons": {
              "128": "icon.png"
  },

  "browser_action": {
              "default_title": "My Chrome App",
              "default_popup": "popup.html"
  },

  "permissions": [
              "http://*/*", "https://*/*","tabs"
  ],

  "content_security_policy": "script-src 'self' https://example.com; object-src 'self'"

}

Is it impossible what I am trying to do? Or is there a workaround? I cannot find an updated answer to this question since CSP has been updated a couple years ago.
UPDATE: As suggested by @PredatorIWD I looked at this answer but I am receiving the following error when I inspect views of background page:
Unchecked runtime.lastError while running tabs.executeScript: Cannot access a chrome:// URL
I was confused about why until I found this answer which solved my problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get raw JSON body in Spring REST controller? The API below accept a json string from client, and the map it into a Email object. How can I get request body (email) as a raw String? (I want both raw-string and typed version of email parameter)
PS: This question is NOT a duplicate of: How to access plain json body in Spring rest controller?
@PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(@RequestBody Email email) {
    //...
    return new ResponseEntity<>(HttpStatus.OK);
}

A: You can do it in more than one way, listing two
 1. **Taking string as the paramater**,
     @PostMapping(value = "/mailsender")
        public ResponseEntity<Void> sendMail(@RequestBody String email) {
            //... the email is the string can be converted to Json using new JSONObject(email) or using jackson.
            return new ResponseEntity<>(HttpStatus.OK);
        }

 2. **Using Jackson**
         @PostMapping(value = "/mailsender")
            public ResponseEntity<Void> sendMail(@RequestBody Email email) {
                //...
                ObjectMapper mapper = new ObjectMapper();
                String email = mapper.writeValueAsString(email); //this is in string now
                return new ResponseEntity<>(HttpStatus.OK);
            }

A: Spring uses Jackson for this in the back, you could use it to serialize it to an string. Like so:
@Autowired private ObjectMapper jacksonMapper;

@PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(@RequestBody Email email) {
    //...
    log.info("Object as String: " + jacksonMapper.writeValueAsString(email));
    return new ResponseEntity<>(HttpStatus.OK);
}

A: I did not get all things about this question, but I try to answer as I understand. Well,
if you want to get request body:

*

*as you say How to access plain json body in Spring rest controller? here already writen how to do this. If something wrong, maybe you send wrong json or not suitable type as you wite inside Email class. Maybe your request comes url filter

*second way try like this:
private final ObjectMapper mapper = new ObjectMapper();

@PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(HttpServletRequest req) {
    // read request body
    InputStream body = req.getInputStream();
    byte[] result = ByteStreams.toByteArray(body);
    String text =new String(result,"UTF-8");
    //convert to object
    Email email = mapper.readValue(body, Email .class);
    return new ResponseEntity<>(HttpStatus.OK);
}

If you want to convert object to json string read this post

A: you can create json of type string using GSON library
Gson gson = new Gson();

@PostMapping(value = "/endpoint")
public ResponseEntity<Void> actionController(@RequestBody Car car) {
    //...
    log.info("Object as String: " + this.gson.toJson(car));
    return new ResponseEntity<>(HttpStatus.OK);
}


text:
Q: Get data from API call in JavaScript I am new to JS and I want to open a new window when I click on my button in SugarCRM without browser blocking it.
function authenticateCalendar() {
    var result;
    var url = app.api.buildURL("Users", 'authenticate_calendar');
    app.api.call('retrieve', url, null, {
        success: function(data) {
            if(data.needAuth) {
                result = JSON.parse(data.url) ;
            }
            else result = false;
        }
    });
    if(result)
        window.open(result);
}
<input type="button" onclick="authenticateCalendar();">

Is it possible to get the data.url string in my function?


text:
Q: C++ array excercise-help needed I'm C++ begginer. I did this excercise from Deitel's book:

Use a one-dimensional array to solve
  the following problem. Read in 20
  numbers, each of which is between 10
  and 100, inclusive. As each number is
  read, validate it and store it in the
  array only if it is not a duplicate of
  a number already read. After reading
  all the values, display only the
  unique values that the user entered.
  Provide for the "worst case" in which
  all 20 numbers are different. Use the
  smallest possible array to solve this
  problem.

Here is my code:
#include <iostream>

using namespace std;

bool compare(int arrayNum[],int arraySize,int element);

int main()
{
    const int size=20;
    int i=1;
    int num[size];
    int arrayElement;
    int counter=0;

    while(i<=20)
    {

        cin>>arrayElement;
        if(i==1)    //stores first element in array
            num[0]=arrayElement;
        //compare new element with stored elements
        //if element is not a duplicate store it in array
        else if (compare(num,size,arrayElement))
        {
            counter++;
            num[counter]=arrayElement;
        }

        i++;
    }
    //displays array elements
    for(int k=0;k<=counter;k++)
        cout<<num[k]<<endl;

    return 0;
}

//compare elements in array

bool compare(int arrayNum[],int arraySize,int element)
{
    for(int j=0;j<arraySize;j++)
    {
        if(arrayNum[j]==element)
            return false;
    }

    return true;
}

It works, but I'm not sure if I have interpreted the task correctly. I assume then I don't have to include conditional statement for range of numbers (10 to 100 inclusive), as this will be read from the keyboard and input by me. Therefore why was this instruction included? Also at the end it says

use the smallest possible array

I assume the max size has to be 20,but I don't think there is a way to dynamically expand array size (for example while storing new elements) as array size is const. I would appreciate if someone could help me with this. Any comments regarding code, or better solution are welcome.

A:
As each number is read, validate
  it and store it in the array

Emphasis mine. The text clearly says that your program has to validate the input. In other words, it has to check that the entered number is between 10 and 100, and if it is not, handle the error appropriately. So yes, you do need a conditional, although exactly what you do to handle the error is up to you.
And you're right, since arrays aren't dynamically resizable, the array size has to be at least 20.

A: You do need a conditional. Basically it's saying to take in a number between 10 and 100. If it's not a number between those ranges, don't store it. Also, if that number already exists in the array, don't store it. Then just print out the values in the array.
You assume correct about the array size, it's maximum size would be 20, although you may not store all 20 values (again, because some input might be bad).

A: The smallest possible array is a char[12], where the individual bits are used as flags.
char data[12]; // memset(data, 0, sizeof(data)); in main();

void set(int n_raw;)
{
   int n = n_raw - 10;
   int index = n/8;
   int offset = n-8*index;
   data[index] |= 1 << offset; // added "1 <<"
}

Reading the values back is left as an exercise for the student.

A:
I assume then I don't have to include
  conditional statement for range of
  numbers (10 to 100 inclusive), as this
  will be read from the keyboard and
  input by me. Therefore why was this
  instruction included?

Sure, in this case you wrote the code and know to enter numbers within the range expected; however, it is a standard best-practice to always validate input data from a user, always. That way erroneous values are handled gracefully (with an appropriate error message) and helps to make your program more robust.

Also at the end it says

use the smallest possible array

I assume the max size has to be 20,,,

I think what they might have been getting at here is that you could have used an array of 91 bytes as shown below.
int cnt = 0;      // count of unique values entered
byte values[91];  // values entered indicator array
int valIdx;       // used as values array index

memset((void *)values, 0, sizeof(values));  // initialize array to all zeros

while ( cnt < 20 )
{
   // [code for the following comments not shown]
   //   have user input a number
   //   validate the number (>= 10 && <= 100)
   //   subtract 10 from the number and store it in valIdx
   //   (now valIdx will contain a number >= 0 <= 90)

   if ( !values[valIdx] )
   {
      values[valIdx] = 1;
      ++cnt;
   }
}

// then to show the unique values...

for ( valIdx = 0; valIdx < sizeof(values); valIdx++ )
{
   if ( values[valIdx] )
   {
      cout << valIdx + 10 << endl;
   }
}

That solution however, would not have met the "use the smallest array possible" requirement.
Back to your code...
I would go ahead and add the user input validation, just for completeness (and to get into the habit of never trusting users (especially yourself).
As far as improvements go, here is one thing to think about. The compare routine goes through every array element when a unique number has been entered. It only needs to check against those that have a stored value in them. Making that change should lead you to refactor the contents of your while loop as well.

A: I'm studying C++ in the same book!!
My first implementation for solving this problem was one that don't use any complementar array.. it uses a linear search to find duplicates..
take a look:
#include <iostream>
using namespace std;

// remember: size_t = unsigned int
const size_t arraySize = 20;
size_t _array[ arraySize ];

// global variable to keep track of the last used
// position in the _array
size_t counter = 0;

// the argument is not changed, so pass it by
// const reference
bool dupSearch( const int & );

int main()
{
    // disregard this
    ios_base::sync_with_stdio( false );

    // "temp" variable declared outside the loop to
    // avoid repeated allocation and deallocation
    int i = arraySize, temp;

    // look at the loop condition below " ( i-- ) "
    // remember:
    // false = ( every expression evaluated to 0 )
    // true  = ( every expression evaluated to a non-zero result )
    // more details on pag. 108 of the book. 8/e Portability tip 4.1
    while ( i-- )
    {
        // read the number from the user
        cin >> temp;

        // if the number entered is valid, put the
        // number on _array[ counter ] and increment 'counter'
        if ( dupSearch( temp ))
        {
            _array[ counter ] = temp;
            ++counter;
        }
    }

    // print the result in column format
    cout << endl;
    for ( size_t j = 0; j < counter; ++j )
        cout << _array[ j ] << endl;
}

// validation: if the value is out of the described range, return false
// if is in the range, check for duplicates using linear search.
// if a duplicate is found, return false
// otherwise, return true.
bool dupSearch( const int &a )
{
    if ( a < 10 || a > 100 )
        return false;
    else
        for ( size_t i = 0; i < counter; ++i )
            if ( _array[ i ] == a )
                return false;

    return true;
}

the number of comparisons is
n = ( n * ( n + 1 )) / 2
where n = counter. worst case --> counter = 20 numbers --> loop 210 times through the program execution.


text:
Q: Gauss's Law and Flux through Sphere vs. Shell I'm having trouble understanding Gauss's law.
Suppose you have a sphere centered upon a positive charge. Then the flux through the sphere is some positive value, according to Gauss's law. I try to analogize the positive charge as this 3D source of water and the surface of the sphere is this boundary line. Since there is a net flow of water out of the sphere's boundary, the flux must be positive.
But for the case of a neutral, non-conducting shell centered upon a positive charge, wouldn't the flux be zero? Using the analogy, any water entering from the inner boundary of the shell also exits through the outer boundary, so there is no net flow of water. But Gauss's law states that any closed surface (including this shell) can be used to calculate flux, so it must be positive.
What am I misunderstanding?

A: If I understand your question, this might be helpful.
Gauss's Law refers to the net flux through a closed surface.  If the surface doesn't include any sources or sinks, then it is true that the net flux will be zero.
In the case you describe, the flux through the shell will be zero if you draw a closed surface that includes the inner boundary and outer boundary but not the charge at the center.  However, having a zero flux doesn't mean that the electric field is zero on the surface of the closed surface.  It means that the electric field points in the same direction as the surface normal on one side of the boundary and in the opposite direction as the surface normal on the other side, thus adding to zero net flux through the surface.
The below figure shows the arrangement:

I hope this helps.


text:
Q: Ajustar o slide do meio conforme o layout proposto Estou tentando ajustar os slides conforme o layout proposto, mas estou tento dificuldades.
Estou usando o plugin Owl Carousel, dei uma procurada em algum plugin pronto na internet que contenha essa opção, mas não achei nada.
Segue o layout:

Segue meu código:
Código (clique aqui)

$('.owl-carousel.vitrine').owlCarousel({
  center: true,
  items: 3,
  loop: true,
  //autoWidth:true,
  margin: 10,
  responsive: {
    600: {
      items: 3
    }
  }
});
@import url('https://fonts.googleapis.com/css?family=Montserrat');
* {
  font-family: 'Montserrat', sans-serif;
}

.divider {
  height: 3px;
  display: block;
  margin: 30px auto;
  background: #970202;
}

#produtos {
  padding: 130px 0;
}

#produtos .produto {
  background: #dcdcdc;
  margin: 10px 0;
}

#produtos .produto .img_produto {
  width: 100%;
}

#produtos .divider {
  height: 6px;
  width: 100%;
}

#produtos .divider.top {
  margin-top: -6px;
}

#produtos .divider.bottom {
  margin-bottom: -6px;
}

#produtos .produto h3 {
  color: #970202;
  margin: 0;
  display: block;
}

#produtos .produto .titulo {
  margin-top: 28px;
  font-size: 32px;
  font-size: 2rem;
}

#produtos .produto .sub_titulo {
  text-align: center;
  font-weight: 700;
  margin-bottom: 36px;
  font-size: 35px;
  font-size: 2.1875rem;
}

#produtos .produto .desc_produto {
  margin: 25px 0;
  display: block;
  padding: 0;
}

#produtos .produto .btn_orcamento {
  color: #fff;
  width: 100%;
  padding: 18px 0;
  font-size: 19px;
  font-size: 1.1875rem;
  background: #000;
  display: block;
}

#produtos .produto .btn_orcamento:hover {
  color: #fff;
  text-decoration: none;
}

#produtos .col-3.produto {
  height: fit-content;
}

#produtos .produto.center {
  margin-top: -45px;
  -ms-flex: 0 0 33.333333%!important;
  flex: 0 0 33.333333%!important;
  max-width: 33.333333%!important;
}

.center .produto {
  box-shadow: 0 0 25px rgba(0, 0, 0, 0.35);
}

#produtos .center .row .col-2 {
  -ms-flex: 0 0 25%!important;
  flex: 0 0 25%!important;
  max-width: 25%!important;
}

#produtos .center .row .col-8 {
  -ms-flex: 0 0 50%!important;
  flex: 0 0 50%!important;
  max-width: 50%!important;
}

<link rel="stylesheet" href="https://www.metaferragens.com.br/assets/css/owl.carousel.css">

churrasqueira

ROTATIVA

Lorem ipsum dolor sit amet, consectetur adipisicing elit, seLorem ipsum dolor sit

              ORÇAMENTO

churrasqueira

ROTATIVA

Lorem ipsum dolor sit amet, consectetur adipisicing elit, seLorem ipsum dolor sit

              ORÇAMENTO

churrasqueira

ROTATIVA

Lorem ipsum dolor sit amet, consectetur adipisicing elit, seLorem ipsum dolor sit

              ORÇAMENTO

Agradeço a ajuda!

A: Cara fiz uma adaptação com transform e transition, até que ficou bem legal, pode ser que vc tenha que ajustar um padding ou margin para ajusta-la no seu layout final.

Segue o código referente a imagem acima:

$('.owl-carousel.vitrine').owlCarousel({
  center: true,
  items: 3,
  loop: true,
  //autoWidth:true,
  margin: 10,
  responsive: {
    600: {
      items: 3
    }
  }
});
@import url('https://fonts.googleapis.com/css?family=Montserrat');
* {
  font-family: 'Montserrat', sans-serif;
}

.divider {
  height: 3px;
  display: block;
  margin: 30px auto;
  background: #970202;
}

#produtos {
  padding: 130px 0;
}

#produtos .produto {
  background: #dcdcdc;
  margin: 10px 0;
}

#produtos .produto .img_produto {
  width: 100%;
}

#produtos .divider {
  height: 6px;
  width: 100%;
}

#produtos .divider.top {
  margin-top: -6px;
}

#produtos .divider.bottom {
  margin-bottom: -6px;
}

#produtos .produto h3 {
  color: #970202;
  margin: 0;
  display: block;
}

#produtos .produto .titulo {
  margin-top: 28px;
  font-size: 32px;
  font-size: 2rem;
}

#produtos .produto .sub_titulo {
  text-align: center;
  font-weight: 700;
  margin-bottom: 36px;
  font-size: 35px;
  font-size: 2.1875rem;
}

#produtos .produto .desc_produto {
  margin: 25px 0;
  display: block;
  padding: 0;
}

#produtos .produto .btn_orcamento {
  color: #fff;
  width: 100%;
  padding: 18px 0;
  font-size: 19px;
  font-size: 1.1875rem;
  background: #000;
  display: block;
}

#produtos .produto .btn_orcamento:hover {
  color: #fff;
  text-decoration: none;
}

#produtos .col-3.produto {
  height: fit-content;
}

#produtos .produto.center {
  margin-top: -45px;
  -ms-flex: 0 0 33.333333%!important;
  flex: 0 0 33.333333%!important;
  max-width: 33.333333%!important;
}

.center .produto {
  box-shadow: 0 0 25px rgba(0, 0, 0, 0.35);
}

#produtos .center .row .col-2 {
  -ms-flex: 0 0 25%!important;
  flex: 0 0 25%!important;
  max-width: 25%!important;
}

#produtos .center .row .col-8 {
  -ms-flex: 0 0 50%!important;
  flex: 0 0 50%!important;
  max-width: 50%!important;
}

/* classes custom */
.owl-item.active {
  transition: all 500ms;
}
.owl-item.active.center {
  transform: scale(1.1);
  transform-origin: center;
  margin-top: -15px !important;
  z-index: 100;
}
.owl-carousel .owl-stage-outer {
  padding: 55px 0 !important;
}

<link rel="stylesheet" href="https://www.metaferragens.com.br/assets/css/owl.carousel.css">

churrasqueira

ROTATIVA

Lorem ipsum dolor sit amet, consectetur adipisicing elit, seLorem ipsum dolor sit

              ORÇAMENTO

churrasqueira

ROTATIVA

Lorem ipsum dolor sit amet, consectetur adipisicing elit, seLorem ipsum dolor sit

              ORÇAMENTO

churrasqueira

ROTATIVA

Lorem ipsum dolor sit amet, consectetur adipisicing elit, seLorem ipsum dolor sit

              ORÇAMENTO


text:
Q: vim :remove numbers in selection I want to delete the numbers in the following selection in vim, then remove newlines to change this:
    global cR,
cG , 3
cY , 4
cB , 5
cPink , 14
cC , 7
clC , 15
clY , 12
cGray , 9
clGray , 249
clG , 11
cllC , 82
cO , 209

to
 global cR,cG,...

I tried
'<,'>%s/\d\+//g

But it throws: E488 trailing characters


text:
Q: Android Machine is not on the network I am having a problem Running a network service when my app connects to a WiFi network.
I am getting a the following exception,
java.net.SocketException: socket failed: ENONET (Machine is not on the network) in the openPort() method bellow
BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();

    if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {

        NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

        if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
            welcomeService = new BroadcastService(context, "Welcome");
            Log.i(TAG, "onReceive: SUPPLICANT-STATE ---> Connected");
            //do something
            if (!serviceRegistered) {
                welcomeService.registerService();
                serviceRegistered = true;
            }
        }

        if (networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
            Log.i(TAG, "onReceive: SUPPLICANT-STATE ---> Disconnected");
            //do something
            unRegisterService();
        }
    }

}

public void unRegisterService() {
    if (serviceRegistered && welcomeService != null) {
        welcomeService.unregisterService();
        serviceRegistered = false;

    }
}

BroadcastService
public void registerService() {
    NsdServiceInfo serviceInfo  = new NsdServiceInfo();
    serviceInfo.setServiceName(mServiceName);
    serviceInfo.setServiceType("_http._tcp.");
    serviceInfo.setPort(openPort());

    mNsdManager = (NsdManager) mContext.getSystemService(Context.NSD_SERVICE);

    mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}

private int openPort() {
    try{
        // Line that throws the exception
        return  new ServerSocket(0).getLocalPort();
    }catch (IOException ioe){
        Crashlytics.logException(ioe);
        ioe.printStackTrace();
        return 0;
    }
}

This the Broadcast Receiver only runs on when the main activity is showing. and it works fine on the first run but when I change the WiFi network this happens. Help world be greatly appreciated.

A: Use Service which start service and stop service when  network would be change or when stop network.Also check same port which is using release first and after that use that port.Do whatever task you want  in onStartCommand().
@Override
public void onReceive(Context context, Intent intent) {
  Date now = new Date();
  Long time = now.getTime();
  String action = intent.getAction();

  NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

  if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {

    boolean check = isMyServiceRunning(context,
    service.getName());
    if (check) {
      Intent i = new Intent(sqlitewraper.context,service.class);
      stopService(i);
    }
    else{
      Intent i = new Intent(sqlitewraper.context,service.class);
      startservice(i);

    }

  }

  if (networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {

    boolean check = isMyServiceRunning(context,
    service.getName());
    if (check) {
      Intent i = new Intent(sqlitewraper.context,service.class);
      stopService(i);
    }
  }

  private boolean isMyServiceRunning(Context context, String Myservice) {
    ActivityManager manager = (ActivityManager) context
    .getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager
    .getRunningServices(Integer.MAX_VALUE)) {
      if (Myservice.equals(service.service.getClassName())) {

        return true;
      }
    }
    return false;
  }
}


text:
Q: Vector Union function performance in QGIS and ArcGIS DEsktop I am trying to find the union of two vector layers (both spatial indexed) - one land use polygons and another grid. In QGIS it is running since 4 days ago, but in ArcGIS Desktop it took less than 10 min.
Does anyone know if ArcGIS Desktop pre-processes vector(s) before actual union function?
The time difference cannot be this drastic!


text:
Q: "Compensated weak compactness" in $W^{1,1}$ In a problem I'm working on I want to show that a bounded sequence
$\{u_n\} \subset W_0^{1,1}((0,1))$ converges weakly.  Of course, since $W^{1,1}$ is not reflexive I don't get this for free.
The reason, I think, that bounded sequences don't converge is that $W^{1,1}$ can't detect the formation of step functions.  So I think that with additional assumptions on $u_n$, I might be able to show that my sequence does converge weakly.  Specifically, I think that I can prove that each $u_n$ is concave, which should control the formation of step functions except at the boundary.  However, I think it's plausible that I can control the growth of $Du_n$ (perhaps in some $L^p$ norm) in some small region near the endpoints.  Intuitively, this should allow me to globally control the growth of $Du_n$, which should buy me weak convergence in some $W^{1,p}$ space.  (This is actually what I need).
So my question is how the previous discussion can be made precise.  It boils down to the following:

What assumptions (in addition to the concavity of each $u_n$) could I use in order to show that $u_n$ converges weakly in some $W^{1,p}$?


text:
Q: Determine wether a skew-symmetric tensor is decomposable or not. For $x_1,x_2,x_3,x_4$ elements of a vector space $V$, I would like to find out wheter the skew-symmetric tensor $11x_1 \wedge x_2 + 10x_1 \wedge x_3 + 17x_1 \wedge x_4 − 13x_2 \wedge x_3 − 10x_2 \wedge x_4 + 11 x_3 \wedge x_4$ of $\bigwedge^2V$ is decomposable or not, in other words wheter it can be expressed as $u_1 \wedge u_2$ for $u_1,u_2 \in V$.
I've attempted to reduce it denoting $u_1 = ax_1 + bx_2 + cx_3 + dx_4$ and similarly for $u_2$, however I didn't end up with a clear solution..
Does anyone have any idea how to know wether this skew-symmetric tensor is decomposable or not ?

A: I'll assume that $x_1,x_2,x_3,x_4$ are linearly independent. Set
$$ \alpha = 11x_1 \wedge x_2 + 10x_1 \wedge x_3 + 17x_1 \wedge x_4 − 13x_2 \wedge x_3 − 10x_2 \wedge x_4 + 11 x_3 \wedge x_4 $$
and assume that $\alpha = u_1 \wedge u_2$ for some $u_1,u_2 \in V$. This means that both $\alpha \wedge u_1 = u_1 \wedge u_2 \wedge u_1$ and $\alpha \wedge u_2 = u_1 \wedge u_2 \wedge u_2$ are zero. So let's try to solve the equation $\alpha \wedge u = 0$. Write
$$ u = ax_1 + bx_2 + cx_3 + dx_4. $$
Then
$$ \alpha \wedge u = \left( 11c - 10b - 13a \right) x_1 \wedge x_2 \wedge x_3 + \left( 11d - 17b - 10a \right) x_1 \wedge x_2 \wedge x_4 + \left( 10d - 17c + 11a \right) x_1 \wedge x_3 \wedge x_4 + \left( 10c -13d + 11b \right) x_2 \wedge x_3 \wedge x_4 = 0 $$
iff
$$ \begin{pmatrix} -13 & -10 & 11 & 0 \\
-10 & -17 & 0 & 11 \\
11 & 0 & -17 & 10 \\
0 & 11 & 10 & -13 \end{pmatrix} \begin{pmatrix} a \\ b \\ c \\ d \end{pmatrix} = \begin{pmatrix} 0 \\ 0 \\ 0 \\ 0 \end{pmatrix}. $$
Solving this linear system of equations we see that the space of solutions is two dimensional and $u$ solves $\alpha \wedge u = 0$ iff
$$ u \in \operatorname{span} \left \{ -10x_1 + 13x_2 + 11x_4, 17x_1 -10x_2 + 11x_3 \right \}. $$
Now we can check that
$$
\left( -10x_1 + 13x_2 + 11x_4 \right) \wedge \left( 17x_1 -10x_2 + 11x_3
 \right) = \left( 10^2 - 13 \cdot 17 \right) x_1 \wedge x_2 + \\
\left( (-10) \cdot 11 \right) x_1 \wedge x_3 + \left( (-17) \cdot 11 \right) x_1 \wedge x_4 + \left( 13 \cdot 11\right) x_2 \wedge x_3 + \left( 10 \cdot 11 \right) x_2 \wedge x_4 + \\
\left( -11^2 \right) x_3 \wedge x_4 = \\
(-11) \cdot \left( 11x_1 \wedge x_2 + 10x_1 \wedge x_3 + 17x_1 \wedge x_4 − 13x_2 \wedge x_3 − 10x_2 \wedge x_4 + 11 x_3 \wedge x_4 \right) = \\
(-11) \alpha
$$
and so we see that
$$ \alpha = \left( \frac{10}{11} x_1 - \frac{13}{11} x_2 - x_4 \right) \wedge \left( 17x_1 -10x_2 + 11x_3  \right) $$
is decomposable.


text:
Q: Quadratic equations greater than zero, then we have at most one real root I'm watching this video on what's a metric (in topology), specifically I'm at the 5th minute, where the interlocutor says that quadratic equations greater than zero have at most one real root, because it touches zero only once. Specifically, the equation is talking about is $$f(t) = \sum_{i=1}^n (a_i + tb_i)^2 \geq 0$$
I'm aware of when the discriminant of the quadratic formula is negative, $0$ or positive we have respectively no, one and $2$ solutions (because of obvious reasons from arithmetic), but I'm not really getting the statement above.
Maybe it's an easy thing and I'm simply not currently seeing it...

A: $x^2$ for any $x \in \Bbb{R}$ is $0$ if and only if $x=0$. All other times, they are positive. Thus, summing $(a_i+b_i\cdot t)^2$ is summing a bunch of non-negative expressions and that sum can only be $0$ when all of them are zero: That is, they can only be zero when all of the $a_i+b_i\cdot t=0$, which can happen at most for one value of $t$.
For example, the following has one solution:
$$(t+2)^2 = 0$$
The above is only true when $t=-2$ since that's when $t+2=0$. All other times, the left-hand side is positive. Here, the discriminant is $0$.
Also, the following has no solution:
$$(t+2)^2+(3t+1)^2=0$$
This has no solutions because for the first term to be $0$, we need $t=-2$, but for the second term to be $0$, we need $t=-\frac{1}{3}$, meaning that both can not be $0$ at the same time, so the left-hand side is always positive. Here, the discriminant is $-100$.
Finally, the following has one solution:
$$(t+2)^2+(2t+4)^2=0$$
The first term is $0$ when $t+2=0 \implies t=-2$ and the second term is also $0$ when $2t+4=0 \implies t=-2$, so we get that there is one solution of $t=-2$ and for all other $t$, the left-hand side is positive. Here, the discriminant is $0$.

A: Since we are talking about real (and not complex) quantities, every square is $\ge 0$. Furthermore, if $f(t) = 0$ then all the squares inside $f$ must be $0$, i.e. $(a_i + t b_i)^2 = 0$ for all $i$, meaning that $a_i + t b_i = 0$ for all $i$. This implies $t = - \frac {a_i} {b_i}$ for all $i$. Letting $k$ be the common value of all these fractions, we get $a_i = k b_i$ for all $i$ so $f$ looks like $\sum_i (k b_i + t b_i)^2 = (k+t)^2 \sum_i b_i^2$.
To conclude, either $f$ has no root, or if it has, then $f$ must have the very peculiar form shown above and the root is unique (well, if you really want to be strict, then the root has multiplicity $2$).


text:
Q: Returning data from the find() in mongodb I have the following code.
function getNextFiveFixtures(teamname) {
   var fixtures = fixtureModel.find({
       Home : teamname
   },function(err,doc){
       console.log(doc);
   });
}

This print the data on the screen. Though , when i tried to return the data through the following code.
function getNextFiveFixtures(teamname) {
   var fixtures = fixtureModel.find({
       Home : teamname
   },function(err,doc){
       return doc;
   });
   return fixtures;
}

var fixture = getNextFiveFixtures('Chelsea');
console.log(fixture);

This prints a mongodb object. How to get the result in a variable. Appreciate the help.


text:
Q: Is it always possible to algebraically express a function defined by a set of rules? Let's say you have an arbitrary function defined by a set of rules such that for example:
Domain $\hspace{9mm}$     Range
$\hspace{5mm}$ 1 $\hspace{23mm}$  2
$\hspace{5mm}$ 2 $\hspace{23mm}$  2
$\hspace{5mm}$ 3 $\hspace{23mm}$  2
$\hspace{5mm}$ 4 $\hspace{23mm}$  17
$\hspace{5mm}$ 5 $\hspace{23mm}$  0
$\hspace{5mm}$ 11 $\hspace{20mm}$  2435
...which can also include conditions such as $x > a$, etc...
Could you always express such a function algebraically, no matter how complex it is?
How would you prove it?
My intuition says you could, but I have no idea how to prove it.


text:
Q: _pickle.UnpicklingError: invalid load key, '\x00' my code
def read_from_pickle():
    with open("RF.pkl",'rb') as file:
         clf = pickle.load(file)
         df = pd.read_csv("path")

         x_test = df.iloc[:, 0:48]
         y_test= df.iloc[:, -1]
         print(x_test)

         y_pred = clf.predict(x_test)

         score = accuracy_score(y_test, y_pred)

         cm = confusion_matrix(y_test, y_pred)
         cm_list = cm.ravel()
         if (len(cm_list) > 1):
             tp, fn, fp, tn = cm_list

         else:
             tp = cm_list
             fn = 0
             fp = 0
             tn = 0

         print(cm_list)

with open("RF.pkl",'rb') as file:
         clf = pickle.load(file)

Error I'm receiving is
C:\Users\Dell\PycharmProjects\Crispr_project\venv1\lib\site-packages\sklearn\base.py:306: UserWarning: Trying to unpickle estimator DecisionTreeClassifier from version 0.20.2 when using version 0.21.3. This might lead to breaking code or invalid results. Use at your own risk.
  UserWarning)
C:\Users\Dell\PycharmProjects\Crispr_project\venv1\lib\site-packages\sklearn\externals\joblib\__init__.py:15: DeprecationWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.
  warnings.warn(msg, category=DeprecationWarning)
Traceback (most recent call last):
  File "C:/Users/Dell/PycharmProjects/Crispr_project/load_RFpkl_model.py", line 68, in <module>
    clf = pickle.load(file)
_pickle.UnpicklingError: invalid load key, '\x00'.

How to solve this error, I am trying to get the test accuracy from already trained model..
I have already tried re-downloading the file and try to run the code
And Changing the Decision tree classifier version
but nothing is working...
Can anyone please help


text:
Q: Stored procedure timing out on particular connection pool I have a stored procedure which occasionally times out when called from our website (through the website connection pool).  Once it has timed out, it has always been locked into the time-out, until the procedure is recompiled using drop/create or sp_recompile from a Management Studio session.
While it is timing out, there is no time-out using the same parameters for the same procedure using Management Studio.
Doing an "ALTER PROCEDURE" through Management Studio and (fairly drastically) changing the internal execution of the procedure did NOT clear the time out - it wouldn't clear until a full sp_recompile was run.
The stored procedure ends with OPTION (RECOMPILE)
The procedure calls two functions, which are used ubiquitously throughout the rest of the product.  The other procedures which use these functions (in similar ways) all work, even during a period where the procedure in question is timing out.
If anyone can offer any further advice as to what could be causing this time out it would be greatly appreciated.
The stored procedure is as below:
ALTER PROCEDURE [dbo].[sp_g_VentureDealsCountSizeByYear] (
  @DateFrom         AS DATETIME = NULL
  ,@DateTo          AS DATETIME = NULL
  ,@ProductRegion   AS INT = NULL
  ,@PortFirmID      AS INT = NULL
  ,@InvFirmID       AS INT = NULL
  ,@SpecFndID       AS INT = NULL
) AS BEGIN
-- Returns the stats used for Market Overview
DECLARE @IDs    AS IDLIST
INSERT INTO @IDs
    SELECT IDs
    FROM dbo.fn_VentureDealIDs(@DateFrom,@DateTo,@ProductRegion,@PortFirmID,@InvFirmID,@SpecFndID)

CREATE TABLE #DealSizes (VentureID INT, DealYear INT, DealQuarter INT, DealSize_USD DECIMAL(18,2))
INSERT INTO #DealSizes
    SELECT vDSQ.VentureID, vDSQ.DealYear, vDSQ.DealQuarter, vDSQ.DealSize_USD
    FROM dbo.fn_VentureDealsSizeAndQuarter(@IDs) vDSQ

SELECT
    yrs.Years Heading
    ,COUNT(vDSQ.VentureID)          AS Num_Deals
    ,SUM(vDSQ.DealSize_USD) AS DealSize_USD
FROM tblYears yrs
    LEFT OUTER JOIN #DealSizes vDSQ ON vDSQ.DealYear = yrs.Years
WHERE (
        ((@DateFrom IS NULL) AND (yrs.Years >= (SELECT MIN(DealYear) FROM #DealSizes))) -- If no minimum year has been passed through, take all years from the first year found to the present.
            OR
        ((@DateFrom IS NOT NULL) AND (yrs.Years >= DATEPART(YEAR,@DateFrom)))   -- If a minimum year has been passed through, take all years from that specified to the present.
    ) AND (
        ((@DateTo IS NULL) AND (yrs.Years <= (SELECT MAX(DealYear) FROM #DealSizes))) -- If no maximum year has been passed through, take all years up to the last year found.
            OR
        ((@DateTo IS NOT NULL) AND (yrs.Years <= DATEPART(YEAR,@DateTo)))   -- If a maximum year has been passed through, take all years up to that year.
    )
GROUP BY yrs.Years
ORDER BY Heading DESC
OPTION (RECOMPILE)
END

A: If you wanted to recompile SP each time it is executed, you should have declared it with recompile; your syntax recompiles last select only:
ALTER PROCEDURE [dbo].[sp_g_VentureDealsCountSizeByYear] (
  @DateFrom         AS DATETIME = NULL
  ,@DateTo          AS DATETIME = NULL
  ,@ProductRegion   AS INT = NULL
  ,@PortFirmID      AS INT = NULL
  ,@InvFirmID       AS INT = NULL
  ,@SpecFndID       AS INT = NULL
) WITH RECOMPILE

I could not tell which part of your procedure causes problems. You might try commenting out select part to see if creating temp tables from table functions produces performance issue; if it does not, then the query itself is a problem. You might rewrite filter as following:
WHERE (@DateFrom IS NULL OR yrs.Years >= DATEPART(YEAR,@DateFrom))
  AND (@DateTo   IS NULL OR yrs.Years <= DATEPART(YEAR,@DateTo))

Or, perhaps better, declare startYear and endYear variables, set them accordingly and change where like this:
declare @startYear int
set @startYear = isnull (year(@DateFrom), (SELECT MIN(DealYear) FROM #DealSizes))
declare @endYear int
set @endYear = isnull (year(@DateTo), (SELECT MAX(DealYear) FROM #DealSizes))
...
where yrs.Year between @startYear and @endYear

If WITH RECOMPILE does not solve the problem, and removing last query does not help either, then you need to check table functions you use to gather data.


text:
Q: Understanding why we can use Chinese Remainder Theorem to Breakdown a congruence problem I am trying to understand why the procedure for solving congruence equations with the CRT works.
An example from my notes is:
$$x^2 + 1 \equiv 0 \text{ mod 10}$$
We do this problem by considering the solutions to the two congruence equations $x^2 + 1 \equiv 0 \text{ mod 2 }$ and $x^2 + 1 \equiv 0 \text{ mod 5 }$. I don't have a problem doing the rote calculation, but I'm not quite getting why this works.
Specifically, is it true that if  $x$ is a solution to $x^2 + 1 \equiv 0 \text{ mod 2}$, and $x^2 + 1 \equiv 0 \text{ mod 5}$, is it necessarily a solution to $x^2 + 1 \equiv 0 \text{ mod 10}$? I can see why the converse is true, but not this way.
Because the procedure, for example, for finding one solution to the original congruence equation is to note that $(x \equiv 1 \text{ mod 2}, x \equiv 3 \text{ mod 5)}$ is a solution to the simultaneous congruence equation: $x^2 + 1 \equiv 0 \text{ mod 2 }$ and $x^2 + 1 \equiv 0 \text{ mod 5}$. But then I don't see how we can conclude that this will be a solution to our original equation?*
*Note: I know by the CRT the simultaneous solution to $(x \equiv 1 \text{ mod 2}, x \equiv 3 \text{ mod 5)}$ is necessarily a congruence class in $\mathbb{Z}_{10}$, I just don't see how we know for certain it will satisfy the congruence equation $x^2 + 1 \equiv 0 \text{ mod 10}$.

A: It may be easier to see when the modular arithmetic statement
is written in equivalent divisibility language:
if $2|x^2+1$ and $5|x^2+1$, then $10|x^2+1$.

A: Suppose that $\,f(x)\,$ is a polynomial with integer coef's and $\,m,n\,$ are coprime integers. By CRT, solving  $\,f(x)\equiv 0\pmod{\!mn}\,$ is equivalent to solving $\,f(x)\equiv 0\,$ mod $\,m\,$ and mod $\,n.\,$ By CRT, each combination of a root $\,r_i\,$ mod $\,m\,$ and a root $\,s_j\,$ mod $\,n\,$ corresponds to a unique root $\,t_{ij}\,$ mod $\,mn\,$ i.e.
$$\begin{eqnarray} f(x)\equiv 0\!\!\!\pmod{\!mn}&\overset{\rm CRT}\iff& \begin{array}{}f(x)\equiv 0\pmod{\! m}\\f(x)\equiv 0\pmod{\! n}\end{array} \\
&\iff&  \begin{array}{}x\equiv r_1,\ldots,r_k\pmod {\!m}\phantom{I^{I^{I^I}}}\\x\equiv s_1,\ldots,s_\ell\pmod{\! n}\end{array}\\
&\iff& \left\{ \begin{array}{}x\equiv r_i\pmod{\! m}\\x\equiv s_j\pmod {\!n}\end{array} \right\}_{\begin{array}{}1\le i\le k\\ 1\le j\le\ell\end{array}}^{\phantom{I^{I^{I^I}}}}\\
&\overset{\rm CRT}\iff& \left\{ x\equiv t_{i j}\!\!\pmod{\!mn} \right\}_{\begin{array}{}1\le i\le k\\ 1\le j\le\ell\end{array}}\\
\end{eqnarray}\qquad\qquad$$
Let's work a simple example for $\,f(x) = (x\!+\!2)(x\!+\!3)\,$ and $\,m,n = 11,17$.
$$(x\!+\!2)(x\!+\!3)\equiv 0\!\!\!\pmod{\!11\cdot 17}\iff \begin{align} x\equiv -2,-3\!\!\!\pmod{\!11}\\ x\equiv -2,-3\!\!\!\pmod{\!17}\end{align}\qquad\qquad $$
which combine to $4$ solutions $\,x\equiv (\color{#90f}{{ -2,-2}}),\,(\color{#0a0}{-3,-3}),\,(-2,-3),\,(-3,-2)\,$ mod $(11,17).\,$  By CCRT, $\bmod 187\:$  the first two yield $\,x\equiv \color{#90f}{ -2}\,$ and $\,\color{#0a0}{-3}.\,$ The third case  $\,(-2,-3)\,$ yields by CRT:
$\!\bmod\, \color{#c00}{11}\!:\,\  {-}2 \equiv\, x \equiv -3+17\,\color{#c00}k \equiv-3+6k \iff 6k\equiv1\equiv12 \iff \color{#c00}{k \equiv 2}$
therefore we infer $\ x = -3+17(\color{#c00}{2+11}n) = 31+187n,\ $ so $\ (-2,-3)\,\mapsto 31$
Finally   $\ (-3,-2) + \underbrace{(-2,-3)}_{\large31}\equiv \underbrace{(-5,-5)}_{\large -5}$ $\,\Rightarrow\,(-3,-2)\,\mapsto\, -5-31\equiv -36\ $
Hence we conclude that there are four roots $\,x \equiv \color{#90f}{-2},\, \color{#0a0}{-3},\, 31,\, -36\pmod{\!11\cdot 17}$

A:
Claim: If $y$ is both a multiple of $2$ and multiple of $5$. then $y$ must be  a multiple of $10$.

Notice that $2$ and $5$ are coprime to each other, there exists integers $s, t$ such that $2s+5t=1$.
$$2sy+5ty=y$$
Since $2$ divides $y$, we can write $y=2k$. Since $5$ divides $y$, we can write $y=5l$.
$$2s(5l)+5t(2k)=y$$
$$10(sl+kt)=y$$
I just use the property that $2$ and $5$ are coprime. In general, if $y$ is both a multiple of $n_1$ and multiple of $n_2$ where $n_1$ and $n_2$ are coprime, then $y$ must be a multiple of $n_1n_2$

A: The explanation is very simple with the 'abstract' version of the Chinese remainder theorem:

Let $a,b$ be coprime integers, and $ua+vb=1$ a Bézout's relation. Then the natural map
\begin{align}
\mathbf Z&\longrightarrow \mathbf Z/a\mathbf Z\times \mathbf Z/b\mathbf Z,\\
n&\longmapsto(n\bmod a,n\bmod b),
\end{align}
is a surjective ring homomorphism with kernel the ideal $ab\mathbf Z$, hence it induces a ring isomorphism $\;\mathbf Z/ab\mathbf Z\overset{\sim}{\longrightarrow}\mathbf Z/a\mathbf Z\times\mathbf Z/b\mathbf Z$, and the inverse isomorphism  is
\begin{align}
\mathbf Z/a\mathbf Z\times\mathbf Z/b\mathbf Z &\longrightarrow \mathbf Z/ab\mathbf Z,\\
(x\bmod a,y\bmod b)&\longmapsto yua+xvb\bmod ab.
\end{align}


text:
Q: How to fix discord XML file issue? <Error>
    AccessDenied
    <Message>Access denied.</Message>
    Anonymous caller does not have storage.objects.get access to discord/app.
</Error>

I have tried uninstalling, restarting, and nothing on google says anything about this. All the posts iv'e seen are about images or whatever but literally this is all i see when i boot up disord. Can't do anything. :/

A: Open the Discord folder and will get this.
Discord folder
Then open the app-0.0.305 folder or the app-0.0.306. Then run the Discord.exe.
The app-0.0.305 or app-0.0.306 folder
That worked for me.


text:
Q: Search with responsive design... Width 100%? I am trying to design a search engine that is responsive design but i have a problem with the search button and the textbox when the length of the window decreases. I do not know if I could help me. I want the textbox and button together occupy 100% of my container
This is what I've come up with:
https://jsfiddle.net/wfbchc1y/

.mainBox{
 max-width: 800px;
 box-sizing: border-box;
 border: solid 1px #D5D4D4;
 background-color: #FFF;
 margin:0 auto;
 padding:20px;
}
#txtSearch{
 height: 40px;
 margin-right: 10px;
 border: solid 1px #CBCBCB;
 border-radius: 4px;
 outline: none;
 box-sizing: border-box;
 padding: 10px;
 color: #6D6A6A;
 width: 92%;
 float: left;
}

#btnSearch{
 box-sizing: border-box;
 height: 40px;
 padding: 10px 15px;
 border-radius: 4px;
 outline:none;
 cursor:pointer;
 transition:All .5s ease;
 border:solid 1px #000;
 background-color:#009;
 color:white;
}

  <input type="text" name="peticion" placeholder="Search" id="txtSearch">
  <input type="button" value=">" id="btnSearch">

A: You can use css calc to calculate the width of input.
width: calc(92% - 40px);//92% - width of input

Jsfiddle

A: Try to use display flex on the main container.

.mainBox{
 max-width: 800px;
 box-sizing: border-box;
 border: solid 1px #D5D4D4;
 background-color: #FFF;
 margin:0 auto;
 padding:20px;
        display: flex;

}
#txtSearch{
 height: 40px;
 margin-right: 10px;
 border: solid 1px #CBCBCB;
 border-radius: 4px;
 outline: none;
 box-sizing: border-box;
 padding: 10px;
 color: #6D6A6A;
 width: 92%;
 float: left;
}

#btnSearch{
 box-sizing: border-box;
 height: 40px;
 padding: 10px 15px;
 border-radius: 4px;
 outline:none;
 cursor:pointer;
 transition:All .5s ease;
 border:solid 1px #000;
 background-color:#009;
 color:white;
}

  <input type="text" name="peticion" placeholder="Search" id="txtSearch">
  <input type="button" value=">" id="btnSearch">

A: Hope this solved!

.mainBox{
    position:relative;
 max-width: 800px;
    width:100%;
    height:80px;
 box-sizing: border-box;
 outline: solid 1px #D5D4D4;
 border: solid 20px #fff;
 background-color: #FFF;
 margin:0 auto;
}
#txtSearch{
    position:absolute;
    top:0px;
    left:0px;
 height: 40px;
 margin-right: 10px;
 border: solid 1px #CBCBCB;
 border-radius: 4px;
 outline: none;
 box-sizing: border-box;
 padding: 10px;
 color: #6D6A6A;
 width: 88%;
}

#btnSearch{
    position:absolute;
    top:0px;
    right:0px;
 box-sizing: border-box;
 height: 40px;
 padding: 10px 15px;
 border-radius: 4px;
 outline:none;
    width: 10%;
 cursor:pointer;
 transition:All .5s ease;
 border:solid 1px #000;
 background-color:#009;
 color:white;
}

  <input type="text" name="peticion" placeholder="Search" id="txtSearch">
  <input type="button" value=">" id="btnSearch">

A: Please try following code.

.mainBox{
 max-width: 800px;
 box-sizing: border-box;
 border: solid 1px #D5D4D4;
 background-color: #FFF;
 margin:0 auto;
 padding:20px;
}
#txtSearch{
    width: 100%;
 height: 40px;
 border: solid 1px #CBCBCB;
 border-radius: 4px;
 outline: none;
 box-sizing: border-box;
 padding: 10px;
 color: #6D6A6A;
 float: left;
}

#btnSearch{
    width: 100%;
 box-sizing: border-box;
 height: 40px;
 padding: 10px 15px;
 border-radius: 4px;
 outline:none;
 cursor:pointer;
 transition:All .5s ease;
 border:solid 1px #000;
 background-color:#009;
 color:white;
}

         <input type="text" name="peticion" placeholder="Search" id="txtSearch">

         <input type="button" value=">" id="btnSearch">


text:
Q: Perl threads, sockets and STDIN interference I am trying to use a perl threads and sockets, to create a simple client/server application. The problem comes in client side, when trying to mix STDIN with socket reading in different threads. Note, I succeeded with using Tkx as workaround to STDIN. But my intention is to build short samples for teaching purposes only, in several programming languages. I intend to create the program minimal, with no UI, as simple as possible.
Here is the code of client, which has the problems:
use strict;
use IO::Socket::INET;
use threads;

our $sock = new IO::Socket::INET ( PeerAddr => 'localhost', PeerPort => 1234, Proto => 'tcp') or die "cannot connect to localhost";
my $thr = threads->create(\&msg_proc, $sock); #, $sock);

for (my $msg; $msg ne "exit";)
{
   $msg = <STDIN>;
   $msg =~ s/[\r\n\s\0]*\Z//g;
   $sock->send ("$msg\n");# or die "can't send";
};
$sock->close();
print "exit main thread\n";

$thr->join() if $thr->is_running();
print "exit all\n";

sub msg_proc
{
   my $svr = shift;
   my $i = 0;
   while ($svr)
   {
      sleep(1);
      $svr->send  ("{slept $i}\n") or die "server closed connection";
      my $svr_msg = <$svr> or die "server closed connection";

      $svr_msg =~ s/[\r\n\s\0]*\Z//g;
      print "From server: <<$i $svr_msg>>\n";

      $i++;
   }
   print "sock exit\n";
}

The problem starts when I remove the line $svr->send in the thread procedure msg_proc. In this case the client fails to read normally from STDIN, looks like interfering with socket reading operation <$svr>. Looks like it interferes with <STDIN> operation. For some reason these two can't coexist in parallel. Note, the C++ and Java versions of these demos do not have this problem.
This is the code of the server:
use strict;
use IO::Socket::INET;
use threads;

my $sock = IO::Socket::INET -> new (LocalPort => 1234, Proto => 'tcp', Listen => 1, Reuse => 1) or die  "Could not create socket: $!\n";
print "server started\n";

my $i = 0;
while (my $s = $sock->accept())
{
   print "New connection\n";
   my $thr = threads->create(\&client_proc, $s, $i);
   $s->send("welcome $i\n");
   $i++;
}

sub client_proc
{
   my $client = shift;
   my $client_no = shift;
   print "## client $client_no started\n";
   $client->send("hello $client_no\n");
   for (my $msg; $msg ne "exit";)
   {
      $msg = <$client> or die "client $client_no closed connection";
      $msg =~ s/[\r\n\s\0]*\Z//;
      print "From client $client_no: '$msg' len: ", length ($msg), "\n";
      $client->send( "client $client_no: $msg\n" ) or die "client $client_no closed connection";
   };
   $client->close();
   print "## client $i exit\n";
}

As I understand from here, the use of interpreter-based threads in perl is officially discouraged. But I can't understand, what interpreter-based threads actually means, and what is exactly the alternative provided. Does this mean using threads is discouraged in perl at all?
Note: I am using Strawberry Perl 5.32.1 64 bit under Windows 11, zip package, no msi. But under ActiveState Perl the problem was identically the same.


text:
Q: Using Wildcard with Apache Pig Interger Equality Comparison Is there a way to perform an integer equality comparison in Apache Pig using a wildcard parameter?
For example, I'm trying to Filter data based off a certain integer in the range 1-9.
data = load 'path/filename.parquet' USING parquet.pig.ParquetLoader('number:int');
filteredData = FILTER data BY (number == $numberProvidedByParameter);

This code works whenever an integer is provided by the $numberProvidedByParameter parameter variable. However, I would like to have the option to pass in a variable that provides all data, essentially a wildcard parameter that returns true for all numbers. I understand that this essentially defeats the purpose of the FILTER, but it seems like a logical route to go when the user is unsure what data they would like to view.
I understand from the Apache Pig Reference Manual on Comparison Operators that you cannot compare an integer to a string using the == comparator so is there another way to provide a wildcard that equals any given integer?
I have tried the following inputs to no avail:
(number == *);
(number == ?);
(number == [0-9]);


text:
Q: Unmarshall JSON with multiple value types and arbitrary number of keys I'm attempting to read a JSON with the following form
{
  string: int,
  string: string,
  string: MyStruct,
  string: MyStruct,
  ...
  string: MyStruct,
}

For example
{
  "status": 200,
  "message": "some cool text",
  "coolKeyA": {
    "name": "yoda",
    "age": 900
   },
  "CoolKeyB": {
    "name": "Mahalalel",
    "age": 895
   },
   "CoolKeyC": {
    "name": "Prince",
    "age": 57
   },
}

The desired outcome is to get a map of map[string]MyStruct. There are an elastic or arbitrary number of "CoolKeyX" keys but the other keys are static, e.g., status and message.
Since the values in the JSON are different types I tried to reach them in to a blank map[string]interface{}. Then the goal is to loop through the keys and pluck out they keys of interest and convert the keys of map[string]inferface{string: string, string: int} to MyStruct.
scaryAcceptAll := map[string]interface{}{}
  if err = json.Unmarshal(byteArray, &scaryAcceptAll); err != nil {
    log.Printf("error: %v", err)
    return err
  }

  for k,v := range scaryAcceptAll {
    if (k == "val0" ) || (k == "val1") {
        continue
    }
    desiredMap[k] = models.MyStruct{Name: v["name"], Age: v["age"]}
  }

Which gives me the following error: NonIndexableOperand: invalid operation: cannot index v (variable of type interface{})
I know the basic idea of unmarshalling JSONs is to create a struct that looks like the json and use that but since I don't know the exact number of keys or what the "CoolKey" key really is (because it's a string containing a hash "000ab8f26d") I didn't know how. I know interfaces are sort of a catch all but then I'm not sure how to pull my desired data out of it.

A: One approach would be implement a custom json.Unmarshaler:
type Obj struct {
    Status   int
    Message  string
    CoolKeys map[string]Person
}

type Person struct {
    Name string
    Age  int
}

func (o *Obj) UnmarshalJSON(data []byte) error {
    // first, unmarshal the object into a map of raw json
    var m map[string]json.RawMessage
    if err := json.Unmarshal(data, &m); err != nil {
        return err
    }

    // next, unmarshal the status and message fields, and any
    // other fields that don't belong to the "CoolKey" group
    if err := json.Unmarshal(m["status"], &o.Status); err != nil {
        return err
    }
    delete(m, "status") // make sure to delete it from the map
    if err := json.Unmarshal(m["message"], &o.Message); err != nil {
        return err
    }
    delete(m, "message") // make sure to delete it from the map

    // finally, unmarshal the rest of the map's content
    o.CoolKeys = make(map[string]Person)
    for k, v := range m {
        var p Person
        if err := json.Unmarshal(v, &p); err != nil {
            return err
        }
        o.CoolKeys[k] = p
    }
    return nil
}

https://go.dev/play/p/s4YCmve-pnz


text:
Q: Should the pre-defined MVC ApplicationDbContext be moved to a different layer, domain or storage? When using MVC5 I add a domain layer and storage layer using dependency injection for all the business data.  But I have always left the ApplicationDbContext in the main MVC application layer project.
I've read a great many posts on SO and see many people recommend moving the ApplicationDbContext out of the MVC project.  I'd like to understand why ApplicationDbContext should or should not be moved.  Are there any reasons to not move this context?
On the one hand, ApplicationDbContext uses a data model which suggests it should be moved to the storage layer but that will require large DTO's.  On the other hand, ApplicationDbContext really relates primarily to application access and I have a separate roles/permissions functionality for the business data anyway.  Several SO posts also suggested checking roles in the application layer, not the domain layer, but that seems suspect; don't we want to check business roles in the domain layer?
So I'm confused and before I go to the work to move the ApplicationDbContext to a different layer, I'd like to make sure I'm making a sound and informed decision.

A: It is not a must, but it is advisable if you are doing DDD and your project tends to grow large.
Although DDD is not about implementation details, DDD asks for a clear separation of concerns. Then you should separate domain logic from infrastructure.
You could achieve that separation in many ways. One way would be to have a single project with folders for Domain, Application and Infrastructure, and have your DbContext reside in the Infrastructure folder. This is suitable for small projects.
In large projects, however, I would recommend you to evaluate the Clean Architecture, which will take this separation to project level.

I'd like to understand why ApplicationDbContext should or should not be moved. Are there any reasons to not move this context?

It can be moved, there's no rule against it. But the tooling will then require you to specify both startup and database projects as parameters, like this:
dotnet ef database update --project <path> --startup-project <path>

But since you're using MVC5, you're probably not using EF Core. In case of EF 6 or lower, you'll be using the Package Manager Console (PMC) to manage migrations and database-updates, which will make your life easier in that regard, since you can mark you MVC project as the Startup Project from the context menu, and select the target project from a dropdown control in the PMC.

Several SO posts also suggested checking roles in the application layer, not the domain layer, but that seems suspect; don't we want to check business roles in the domain layer?

Yes, roles are related to permissions, which are business rules. People probably recommend checking that in the application layer because you need to pull this data from the database, but you could do it like this:
Use the Specification Pattern to represent roles and permissions as an specification in the Domain Layer. But the IRepository interfaces would best be defined in Application Layer, as they represent infrastructure (which will be concretely implemented in the Infrastructure Layer). So you would start the role-checking in the Application Layer by using repositories to retrieve data, but the actual permission validation would be done by an Specification in the Domain Layer.
That would be one way to do it.


text:
Q: C- possible memory leak? I feel that a piece of code I have would cause a memory leak. I have a data structure with two two-dimensional arrays, one containing ints and one containing pointers to dynamically-allocated objects (sprites). The data structure is a tilemap, and the ints are the numeric index of each location, which are read from a file. I call that index 'tiles'. This tells what kind of tile it is, for behavioral purposes (i.e. player responds differently to water than to dirt or ice). The objects are the sprites to draw at their respective locations. That index is known as 'images'. That index tells the tilemap what sprite to draw at that position.
typedef struct
{
    int** tiles;
    sprite*** images;
    int w, h;
} tilemap;

I have a function that creates a new tilemap, initializes it, and returns it.
tilemap* new_tilemap(int w, int h, const char* filename)
{
    tilemap* tm = malloc(sizeof(tilemap));
    tm->w = w;
    tm->h = h;

    /*allocate memory space for the tiles index*/
    tm->tiles = malloc(sizeof(int) * h);
    int i, j;
    for (i = 0; i < h; ++i)
    {
        tm->tiles[i] = malloc(sizeof(int) * w);
    }

    /*fill the index with the appropriate data from a file*/
    FILE* file = fopen (filename, "rb");
    if (file == NULL)
    {
        printf("Failed to open map %s\n", filename);
    }

    for (j = 0; j < h; ++j)
    {
        for (i = 0; i < w; ++i)
        {
            fscanf(file, "%d", &(tm->tiles[j][i]));
        }
    }
    fclose(file);

    /*allocate space for the images*/
    tm->images = malloc(sizeof(sprite*) * h);
    for (i = 0; i < h; ++i)
    {
        tm->images[i] = malloc(sizeof(sprite*) * w);
    }

    /*load images based on what type of tile is at that position*/
    for (j = 0; j < h; ++j)
    {
        for (i = 0; i < w; ++i)
        {
            switch (tm->tiles[j][i])
            {
                case 0:
                tm->images[j][i] = new_sprite_file("dat/tiles/0.bmp", 1);
                break;
                case 1:
                tm->images[j][i] = new_sprite_file("dat/tiles/1.bmp", 2);
                break;
            }
            tm->images[j][i]->x = i*tm->images[j][i]->w;
            tm->images[j][i]->y = j*tm->images[j][i]->h;
        }
    }
    return tm;
}

Then, to free the tilemap and all it's structures I have this function:
void free_tilemap(tilemap* tm)
{
    /*loop through and free each of the images in the array*/
    int i, j;
    for (j = 0; j < tm->h; ++j)
    {
        for (i = 0; i < tm->w; ++i)
        {
            free(tm->images[j][i]);
         }
    }
    /*free the actual array*/
    free(tm->images);
    /*free the tile array?*/
    free(tm->tiles);
    /*free the entire tilemap structure*/
    free(tm);
}

However, I feel that it isn't freeing up all the memory I have allocated, because I used malloc twice on the tiles, but only free'd once. I don't know if this is a problem though, seeing as they are ints, but I think that I may have to loop through the tiles array, free every row, then loop through and free every column (containing the rows), in the same manner as it was allocated. Is that what needs to be done or am I just being ignorant and/or paranoid? The same with the images array. Also, feel free to point out other flaws in my code as I know I'm not the best programmer.

A: Of course you should mirror the mallocs when you free.
for (i = 0; i < h; ++i)
{
    tm->tiles[i] = malloc(sizeof(int) * w);
}

/* Inside free_tilemap. */
for (i = 0; i < h; ++i)
{
    free(tm->tiles[i]);
}
free(tm->tiles);

Same goes for the other fors that closely resemble this one. Freeing just tiles doesn't automatically free tiles[0..h] in cascade.

A: Looking at the code quickly I would say that you are indeed missing the free's on the tiles. I would suggest to use a memory analyzer to find out for yourself. E.g. http://www.cprogramming.com/debugging/valgrind.html
That will give you a good overview of allocated memory, and possible memory leaks when the program exits.


text:
Q: Calling react function in electron ipcRender I am trying to call the following function from react with ipc.renderer
componentDidMount() {
    ipcRenderer.on('log-out', function () {
       localStorage.setItem('user', 'null');
       this.forceUpdate();
    });
}

but every Time i call it I get the following error
Uncaught TypeError: this.forceUpdate is not a function
    at EventEmitter.<anonymous> (App.js:30)
    at emitOne (events.js:96)
    at EventEmitter.emit (events.js:191)

What am I doing wrong or how it suppose to be done ?
Thank you.

A: This part:
componentDidMount() {
    ipcRenderer.on('log-out', function() {
        localStorage.setItem('user', 'null');
        this.forceUpdate();
    });
}

The this in this.forceUpdate(); is not the this you are looking for. To fix the problem, you need to bind this to the corresponding context (your component), as:
componentDidMount() {
    ipcRenderer.on('log-out', function() {
        localStorage.setItem('user', 'null');
        this.forceUpdate();
    }.bind(this));
}

Or creating a closure using the this to self like:
componentDidMount() {
    self = this;
    ipcRenderer.on('log-out', function() {
        localStorage.setItem('user', 'null');
        self.forceUpdate();
    });
}

A: That's the very common issue of fat arrow.
Here you can read more about fat arrow (here)
We can solve this by 2 ways:

First:
Replace this:
function () {

with:
() => {

Second:
ipcRenderer.on('log-out', function () {
   localStorage.setItem('user', 'null');
   this.forceUpdate();
}).bind(this);


text:
Q: Upgrading postgresql v9.4 to v12 but get pg_upgrade: command not found I'm on Ubuntu 20.04 and currently running my app on postgresql 9.4.
I installed postgres version 12 and I'm trying to migrate my data over from postgres v9.4 to postgres v12. I also have postgres version 11 installed from an earlier time.
I'm trying to do this from pg_upgrade
So when I run pg_lsclusters I get:
9.4 main    5432 online                postgres  /var/lib/postgresql/9.4/main /var/log/postgresql/postgresql-9.4-main.log
11  main    5433 down                  postgres  /var/lib/postgresql/11/main  /var/log/postgresql/postgresql-11-main.log
12  main    5434 down                  postgres  /var/lib/postgresql/12/main  /var/log/postgresql/postgresql-12-main.log

When change to the postgres user (from the root) and run pg_upgrade --check I get:
pg_upgrade: command not found

Where is it looking for the pg_upgrade file/command?


text:
Q: Best approach when renaming a well rooted model Lets say I am modifying an already existing web application and I want to rename my People model to User. I have about 100 pages that reference the People model, I would have to change that to reference User. I have made those changes, but I must have forgotten a couple. Is there a way to automated this process?

A: Obviously, you should use testing to avoid such problems. But, if there's no tests already, you can use any text editor to search in all project files. For example, in Sublime text you can use "Ctrl+Shift+F" or "Cdm+Shift+F" combination.


text:
Q: Why is more faster do access a local variable instead a field in the Dalvik VM, I was reading the notepad tutorial of google and I found that at exercise two:
"We assign the mNotesCursor field to a local variable at the start of the method. This is done as an optimization of the Android code. Accessing a local variable is much more efficient than accessing a field in the Dalvik VM, so by doing this we make only one access to the field, and five accesses to the local variable, making the routine much more efficient. It is recommended that you use this optimization when possible."
The code:
Cursor c = mNotesCursor;
c.moveToPosition(position);
Intent i = new Intent(this, NoteEdit.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
startActivityForResult(i, ACTIVITY_EDIT);

Why is more faster to access a local variable instead a field?
The notepad tutorial is accessible at: http://developer.android.com/training/notepad/notepad-ex2.html
This part is in the step 5.

A: According to Dianne Hackborn (Android framework engineer): "When accessing a member variable, the compiler will very often need to dereference 'this' and reload the value from memory each time it is access, since the value could have changed since it was last used.  Accessing a local variable in contrast can be done just by using the existing value in a register."  See: Link.
However, going overboard there would seem to go against other Android performance tips such as avoiding the creation of unnecessary objects. Link.  Also, later that article, on the use of internal Getters it says, "Without a JIT, direct field access is about 3x faster than invoking a trivial getter. With the JIT (where direct field access is as cheap as accessing a local), direct field access is about 7x faster than invoking a trivial getter."


text:
Q: NodeJS organize loop with repeated records I have a table where I store the sales of certain products. I need to fetch the records by client id.
I did like this:
public async getData(clientID: any): Promise<any> {
    try {
      return await client
        .scan({
          TableName: "dbSales",
          FilterExpression: "contains(clientID, :clientID)",
          ExpressionAttributeValues: {
            ":clientID": clientID,
          },
        })
        .promise()
        .then(async (response) => {
          let data = [];

          for (let i = 0; i < response.Count; i++) {
            if(data.filter(product => product.productId == response.Items[i]['productId']) != undefined){
                const resultData = await this.getProduct(response.Items[i]['productId']);
                data.push(resultData);
            }
          }

          return {
            status: 200,
            data: data,
          };
        })
        .catch((error: AxiosError) => {
          throw error;
        });
    } catch (e) {
      throw new HttpError(500, e.message);
    }
  }

There it will get all the records with that customer id, and then through a condition it will get the product name of each record it found, through another function (getProduct), with the repetition loop.
The problem is that I'm getting a lot of repeated results, i.e. for the same product id and customer.
I need that when there is more than one record in dbSales with the same customer id and with the same product id, it returns me only one result for those records.
That is, one row for each record that contains the same customer ID and product ID.
This is generating a long delay in the search for data, as I only need which products a particular customer has purchased, without the information being repeated when he has more purchases of the same product.

A: Problem solved! Solution:
The solution presented by our friend @jarmod solved my problem, in a simple way.
let result = response.Items.filter((e, i) => {
    return response.Items.findIndex((x) => {
    return x.productId == e.productId}) == i;
 });

for (let i = 0; i < result.length; i++) {
    if(data.filter(product => product.productId == result[i]['productId']) != undefined){
        const resultData = await this.getProduct(result[i]['productId']);
        data.push(resultData);
    }
 }

Proposed solution: How to remove duplicates objects in array based on 2 properties?


text:
Q: Existence and uniqueness of the central value of a probability measure by Doob. Let $\mu$ be a one-dimensional probability measure. The central value $\gamma = \gamma(\mu)$ is defined by J.L. Doob to be the real number $\gamma$ such that
$$\int_{R^1} \arctan(x-\gamma) \mu(dx)=0.$$
The existence and the uniqueness of $\gamma$ follow from the fact that for $x$ fixed, $\arctan(x-\gamma)$ decreases strictly and continuously from $\pi/2$ to $-\pi/2$ as $\gamma$ moves from $-\infty$ to $\infty$.
This is an excerpt from Ito's Stochastic Processes. I don't follow the existence and uniqueness argument. $x$ itself is random here so how tdoes the above properties of $\arctan(x-\gamma)$ guarantee the existence and uniqueness of such $\gamma$?

A: Hints:

*

*Using the dominated convergence theorem show that the mapping $$\gamma \mapsto F(\gamma) := \int_{\mathbb{R}} \arctan(x-\gamma) \, \mu(dx)$$ is continuous.

*Conclude from the fact that $y \mapsto \arctan(y)$ is strictly increasing that $\gamma \mapsto F(\gamma)$ is strictly increasing.

*Use the dominated convergence theorem to show that $$\lim_{\gamma \to \infty} F(\gamma) = - \frac{\pi}{2} \quad \text{and} \quad \lim_{\gamma \to -\infty} F(\gamma) = \frac{\pi}{2}.$$

*Conclude.


text:
Q: Datevalue can't read december month I work on a macro vba which manipulate different dates.
I have an incomprehensive error with Decembre. For exemple
DateValue("11-NOV-14")

return : 11/11/2014
DateValue("11-DEC-14")

return an error type '13'
I already try to put the string into a var and pass it to DateValue but same results.
Maybe i can get around this problem but i want to know why i have this mystic error.
Thanks for your help.

A: Your is a system-dependent problem. The month of November passes well because, in French, November = Novembre so "11-NOV-14" is equal to the English version.
However, "Décembre" is different because it has an accent on the second letter. In fact, on a French system, this will be ok:
a = DateValue("11-DéC-14")

while this will be not:
a = DateValue("11-DEC-14")

To avoid this problem and make the code "language-independent" (without asking the user to change the date formatting from the Control Panel), I think you should add a function that translate dates from string to date values:
Function MyDateValue(ByVal myDate As String) As Date
    myDay = Left(myDate,2)
    myMonth = Right(Left(myDate,6),3)
    Select Case myMonth
        Case "JAN":
            myMonth = 1
        'etc.
    End Select
    myYear = Right(myDate,2)
    MyDateValue = DateSerial(myYear,myMonth,myDay)
End Function

So, you will be able to use myDateValue rather than DateValue and will make sure that it will work with your input data whatever will be the system language.


text:
Q: How can triggers and stored procedures be represented in an ER Diagram? Is it a good idea to show triggers and stored procedures in an Entity Relationship Diagram? If yes, what is the notation? Information seems really scarce on this topic. Also, are there any UML diagrams you would use to represent triggers?

A: Since Triggers are based on actions in sequence, I haved used a UML sequence diagram rather than an ERD.  The swimlanes would be the base tables and the messages would be the triggers firing.  For stored procedures, the same approach could be taken if the stored procedures were centered around a certain table.  If not, a collaboration diagram could be used.

A: As Steve said, you may represent the dynamic of a trigger or stored proc in a dynamic diagram. But for triggers specifically, if you just want to declare them, you can also add them as operations in classes used to represent the corresponding tables in your Entity Relationship Diagram. In this case, you might want to use relevant stereotypes on these operations, such as <<trigger>>.

A: ER diagrams have never been intended for that purpose and are therefore not very well suited.
The UML event sequences (swimlanes) as suggested elsewhere, might be a tad better, but imo it's still problematic.  The arrows cannot distinguish between an insert and a delete, hence you'd have to have several distinct charts for each table (one for what happens upon insert and one for what happens upon delete, and then there's still the gray area of update).  I'm also not very sure whether the swimlanes charts allow to document very well what precisely happens to the other (targeted) tables.  Insert or delete ?  Of which row(s) exactly ?  etc. etc.


text:
Q: Get all requests urls of a page in Python Is there anyway to get all requested urls of a page? For example, when I visit a site, browsers make multiple network requests to for example, html, css and other files from the server that are necessary to display the page. I want to get all those assets urls using Python. Basically, I want to get all the urls like from the screenshot below. Can anyone point me in the right direction?
PS: I want to do this with scripting to automate the task. I know that I can accomplish this kind of task using Wireshark which I cannot automate.

A: For others interested: the next snippet, which I got from a post from pythoncode, worked for me.
I am sure it has some limitations as the ones described above (different browsers, different paths, etc., making this hack non-general), but it may save someone's day.
# get the CSS files
css_files = []

for css in soup.find_all("link"):
    if css.attrs.get("href"):
        # if the link tag has the 'href' attribute
        css_url = urljoin(url, css.attrs.get("href"))
        css_files.append(css_url)
print(css_files) # list of URLs of the files called

A: You can use gtk + webkit2. Check this gist for a full working example.
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('WebKit2', '4.0')
from gi.repository import Gtk, WebKit2

def on_resource(webview, resource, request):
    print(request.get_uri())
    return True

def load(url):
    window = Gtk.Window()
    window.set_default_size(800, 600)
    window.connect("destroy", Gtk.main_quit)

    webview = WebKit2.WebView()
    webview.connect("resource-load-started", on_resource)
    webview.load_uri(url)

    window.add(webview)
    window.show_all()

    Gtk.main()


text:
Q: Bootstrap Thumbnail Gallery skips first image I'm loading the gallery progmatically using C# and sql.
Everything is fine on the query side
Here is my sample query
and its results:
SELECT productName,productType,image_desc
                               FROM Products3
                               WHERE productType = 'Souvenirs'

The results would be like this

But if I use this query along with my c# codes. Button Pins does not appear it is being skipped.
    private void load_souvenirs_products()
    {
        con.Open();
        cmd = new SqlCommand(@"SELECT productName,productType,image_desc
                               FROM Products3
                               WHERE productType = 'Souvenirs'", con);

        rdr = cmd.ExecuteReader();

        if (rdr.Read())
        {
            while (rdr.Read())
            {
                product_name = rdr["productName"].ToString();
                product_type = rdr["productType"].ToString();
                image_desc = rdr["image_desc"].ToString();

                // foreach()

                lbl_table.Text += @"

" + product_name + @"

";

            }
        }

        con.Close();
    }

This query should load all data that has productType of Souvenirs.
Here is my current output:

Where did I go wrong?Because this happens on all my Product List as well.All first Row being skip.
I'm following this example for bootstrap gallery.

A: Because your while loop is nested inside the if statement, you're essentially calling rdr.Read twice before accessing the data.  This means the first row of the returned results is always skipped.
You should get rid of the if statement and just use the while loop.


text:
Q: Unable to import name '_TPU_AVAILABLE' from 'pytorch_lightning.utilities' I'm trying to import aitexten package to work on a GPT-2 solution. But I'm encountering an error:ImportError: cannot import name '_TPU_AVAILABLE' from 'pytorch_lightning.utilities' (/usr/local/lib/python3.7/dist-packages/pytorch_lightning/utilities/init.py)

I tried downgrading pytorch to v1.11.0 but that isn't helping too. Please help!

A: This worked for me in Google Colab. And it's with aitextgen version 0.6.
!pip uninstall -qqy torch torchvision torchtext torchaudio fastai
!pip install -qq torch==1.9.0 pytorch-lightning==1.7.7 aitextgen==0.6.0

A: I ran into the same problem! I fixed it by downgrading aitextgen.
In the beginning of my notebook, I ran this command:
!pip3 install -q aitextgen==0.5.2
Make sure to restart your kernel.

A: try this  :
pytorch-lightning==1.4.0rc0
torchmetrics==0.6.0
aitextgen==0.5.2


text:
Q: XNA, winform and full screen I have integrated XNA and winform with this tutorial http://roy-t.nl/index.php/2008/10/09/xna-30-and-winforms-the-easy-way/ the problem is that I would like be able to view the content XNA in full screen. How do that?
Thanks!

A: If you want to resize content in picturebox you will need to add event SizeChanged
in which you will update BackBuffer width and height.Otherwise rendering output will become pixalated.
 PresentationParameters params;
 params.BackBufferWidth = control.ClientSize.Width;
 params.BackBufferHeight = control.ClientSize.Height;
 GraphicDevice.Reset(params);


text:
Q: Weird Dropdown Behaviour I've a very confusing issue where the li with class 'search is moved down under the dropdown box when it is shown, all other li's stay in place where they should be, any suggestions?
It's only when the dropdown is displayed otherwise the 'search' li appears and works as expected.
http://i43.tinypic.com/2z686md.png
EXAMPLE
HTML:

HOME

        CATEGORIES

Unable to find category listings.

        SEARCH: <input type="text" name="search">

CSS:
ul.nav .dropdown {
    position: relative;
    width: 98%;
    height: 130px;
    margin-top: 38px;
    margin-left: -2%;
    padding: 2%;
    color: #FFFFFF;
    background: #0F2F54;
    opacity: 0.95;
    z-index: 1;
}
ul.nav li .dropdown {
    display: none;
}
ul.nav li:hover .dropdown {
    display: block;
}
.dropdown ul.category li a {
    width: 23%;
    color: #FFFFFF;
    font-size: 20px;
    border-right: none;
}
.dropdown ul.category li a:hover {
    background: none;
    text-decoration: underline;
}
ul.nav li.search {
    float: right;
    height: 32px;
    margin-right: 2%;
    padding: 6px 10px 0 10px;
    border-left: 1px #336198 solid;
    border-right: 1px #336198 solid;
    display: inline;
}
ul.nav li.search input {
    width: 200px;
    padding: 4px;
}

Javascript:
$("ul.nav .dropdown").on({
    mouseenter: function () {
        $(this).prev().css('background', '#0F2F54');
    },
    mouseleave: function () {
        $(this).prev().css('background', '');
    }
});

A: Here is a fix for your code, just making the dropdown class as absolute will not affect other elements on the page.
fiddle

A: make the position of dropdown absolute;
DEMO

A: in your css .dropdown class has position:relative that means it aligns itself relative to its adjacent elements changing it to absolute will make .dropdown align as per absolute position.
ul.nav .dropdown {
    position: absolute;
    width: 98%;
    height: 130px;
    margin-top: 38px;
    margin-left: -2%;
    padding: 2%;
    color: #FFFFFF;
    background: #0F2F54;
    opacity: 0.95;
    z-index: 1;
}


text:
Q: DIV does not show on link with variables For some reason a certain div will now show up when i click a button. I'm fairly new to JS so can't really figure out why is it only on that one. Basically the order should be
Click on Add Shots -> Show Games and Rounds ( Works Fine) -> Click Submit -> Show Targets on each round (Works Fine) -> Click Target -> Show Fill in form (the "fillshotsdiv") (NOT working).
Below is my code. What am i missing?
JS

HTML

  <form action="">
    <select name="gameShots" class="gameShot">

    </select>
    <select name="roundShots" class="roundShot">
      <option value="nothing">-----</option>
      <option value="Round 1">Round 1</option>
      <option value="Round 2">Round 2</option>
    </select>
    <button type="submit" >Submit</button>
  </form>

    <form method="post" action="addScoreToRound.php?targetNo=<?php echo $_GET['targetNo'];?>&gameNo=<?php echo $_GET['gameNo'];?>&roundName=<?php echo $_GET['roundName']; ?>">

Shot Number	Arrow 1	Arrow 2	Arrow 3

1	<input type="text" name="arrow_1_1">	<input type="text" name="arrow_1_2">	<input type="text" name="arrow_1_3">

2	<input type="text" name="arrow_2_1">	<input type="text" name="arrow_2_2">	<input type="text" name="arrow_2_3">

3	<input type="text" name="arrow_3_1">	<input type="text" name="arrow_3_2">	<input type="text" name="arrow_3_3">

4	<input type="text" name="arrow_4_1">	<input type="text" name="arrow_4_2">	<input type="text" name="arrow_4_3">

5	<input type="text" name="arrow_5_1">	<input type="text" name="arrow_5_2">	<input type="text" name="arrow_5_3">

6	<input type="text" name="arrow_6_1">	<input type="text" name="arrow_6_2">	<input type="text" name="arrow_6_3">

7	<input type="text" name="arrow_7_1">	<input type="text" name="arrow_7_2">	<input type="text" name="arrow_7_3">

8	<input type="text" name="arrow_8_1">	<input type="text" name="arrow_8_2">	<input type="text" name="arrow_8_3">

9	<input type="text" name="arrow_9_1">	<input type="text" name="arrow_9_2">	<input type="text" name="arrow_9_3">

10	<input type="text" name="arrow_10_1">	<input type="text" name="arrow_10_2">	<input type="text" name="arrow_10_3">

    <button type="submit">Submit</button>
  </form>

PHP that refreshTargets calls is
if($_GET['function']=="drawTargets")
    {
        $gameNo = $_GET['gameShots'];
        $roundName = $_GET['roundShots'];
        $sql=mysql_query("SELECT * FROM tbl_Round WHERE match_id='$gameNo' && round_name='$roundName'")
            or die(mysql_error());
        while ($row = mysql_fetch_array($sql)) {
            echo '
<button class="but" id="fillshots" type="button">'.$row["target_name"].'- Player'.$row['player_id'].'</button>
';
        }
    }

A: You need to use event delegation on your click handler because .but is a dynamically inserted element:
$('.targetinfo').on('click', '.but', function(e) {
    e.preventDefault();
    $('.contentfill').hide();
    $('#' + this.id + 'div').show();
});


text:
Q: Where to put this block of script so that this slideshow can move automatically? I asked a question before on how to make the jQuery Blinds slideshow move automatically and somebody answered on this page (the one with 12 votes):
Is there a way to make this slideshow move automatically?
Seems like the code is working for most people but I can't get it to work for me. I used the original demo file and placed the code at the very bottom of jquery.blinds-0.9.js, right after "})(jQuery);" but still the slideshow isn't moving. What am I doing wrong? I checked the class names and they are correct.
This is that block of script:
var SlideChanger = function(seconds_each) {
  var index = -1;
  // on the first cycle, index will be set to zero below
  var maxindex = ($(".change_link").length) - 1;
  // how many total slides are there (count the slide buttons)
  var timer = function() {
  // this is the function returned by SlideChanger
    var logic = function() {
    // this is an inner function which uses the
    // enclosed values (index and maxindex) to cycle through the slides
      if (index == maxindex)
        index = 0; // reset to first slide
      else
        index++; // goto next slide, set index to zero on first cycle
      $('.slideshow').blinds_change(index); // this is what changes the slide
      setTimeout(logic, 1000 * seconds_each);
      // schedule ourself to run in the future
    }
    logic(); // get the ball rolling
  }
  return timer; // give caller the function
}

SlideChanger(5)(); // get the function at five seconds per slide and run it

A: Try wrapping the last line SlideChanger(5)(); in a document.ready, like this:
$(function(){SlideChanger(5)();})
Otherwise $(".change_link").length will prob return 0


text:
Q: How can I specialize a C++ template for a range of integer values? Is there a way to have a template specialization based on a range of values instead of just one? I know the following code is not valid C++ code but it shows what I would like to do.  I'm writing code for a 8-bit machine, so there is a difference in speed for using ints and chars.
template<unsigned SIZE>
class circular_buffer {
   unsigned char buffer[SIZE];
   unsigned int head; // index
   unsigned int tail; // index
};

template<unsigned SIZE <= 256>
class circular_buffer {
   unsigned char buffer[SIZE];
   unsigned char head; // index
   unsigned char tail; // index
};

A: Another possible option:
template <unsigned SIZE>
struct offset_size {
    typedef typename offset_size<SIZE - 1>::type type;
};

template <>
struct offset_size<0> {
    typedef unsigned char type;
};

template <>
struct offset_size<257> {
    typedef unsigned int type;
};

template<unsigned SIZE>
class circular_buffer {
   unsigned char buffer[SIZE];
   typename offset_size<SIZE>::type head; // index
   typename offset_size<SIZE>::type tail; // index
};

(Ideone example)

A: Try std::conditional:
#include <type_traits>

template<unsigned SIZE>
class circular_buffer {

    typedef typename
        std::conditional< SIZE < 256,
                          unsigned char,
                          unsigned int
                        >::type
        index_type;

    unsigned char buffer[SIZE];
    index_type head;
    index_type tail;
};

If your compiler doesn't yet support this part of C++11, there's equivalent in boost libraries.
Then again, it's easy to roll your own (credit goes to KerrekSB):
template <bool, typename T, typename F>
struct conditional {
    typedef T type;
};

template <typename T, typename F>  // partial specialization on first argument
struct conditional<false, T, F> {
    typedef F type;
};

A: Use an extra defaulted bool parameter:
// primary template handles false
template<unsigned SIZE, bool IsSmall = SIZE <= 256>
class circular_buffer {
   unsigned char buffer[SIZE];
   unsigned int head; // index
   unsigned int tail; // index
};

// specialization for true
template<unsigned SIZE>
class circular_buffer<SIZE, true> {
   unsigned char buffer[SIZE];
   unsigned char head; // index
   unsigned char tail; // index
};

A: I hate how messy dealing with types can be so I propose something a bit simpler, leveraging constexpr. This variant allows for differing behavior when a varying type is not required and addresses the need to fit within a range and not just one side of a value:
template<bool> struct If;

constexpr bool InClosedRange(std::size_t Value, std::size_t Lower, std::size_t Upper)
{
    return (Lower <= Value) && (Value <= Upper);
}

// Usage:
template<size_t Width, If<true>>
class Foo;

template<size_t Width, If<InClosedRange(Width, 1, 41)>>
class Foo { /* ... */ };

template<size_t Width, If<InClosedRange(Width, 42, 142)>>
class Foo { /* ... */ };

Inspired by: https://stackoverflow.com/a/9516959/929315


text:
Q: How to define _FILE_OFFSET_BITS & _LARGE_FILES macro for Solaris and HP-AIX I Have a C Program as follow.
I don't what to use stat64 instead of stat in both Solaris & HP-AIX.
I want to build this Program this on both Solaris & HP-AIX.
#include "zunx.h"
#include <nls.h>

/*
 * NAME:        zunx_file_exists
 *
 * PURPOSE:     Checks if a file exists.
 *
 * INVOCATION:  boolean zunx_file_exists(name)
 *              char *name;
 *
 * INPUTS:      name    - file to check
 *
 * OUTPUTS:     TRUE or FALSE
 *
 * DESCRIPTION: zunx_file_exists does a stat on the specified file,
 *              and returns TRUE if a stat is found.  No check is
 *              made to determine what type of file it is.
 */
boolean zunx_file_exists
   (const char *buf)
{

#if defined(UNIX)
   struct stat fstat;

   if (buf != NULL && stat(I2E1(buf), &fstat) == 0)
      return TRUE;
   else
      return FALSE;
#endif

#ifdef NT_OS
   struct _stat64 fstat;

   if (buf != NULL && _stat64((char *) I2E1(buf), &fstat) == 0)
      return TRUE;
   else
      return FALSE;
#endif
}

I came across  a macro in Solaris like :
 #ifdef UNIX
    #define _FILE_OFFSET_BITS 64
 #endif

is this definition is correct for above program?
for HP-AIX its use _LARGE_FILES macro.
but I don't know how to define this macro in above program in order to run successfully on both OS.
Please suggest some ideas.

A: Detailed data for accessing large files, including large file compile, link, and other flags can be found for Solaris on the lfcompile man page:

lfcompile

*

*large file compilation environment for 32-bit applications

  Description
All 64-bit applications can manipulate large files by default. The
  methods described on this page allow 32-bit applications to manipulate
  large files.
...

Note that the man page specifically states that defines other than those returned via getconf are necessary:

Set the compile-time flag _FILE_OFFSET_BITS to 64 before including any headers. Applications may combine objects produced in the large file compilation environment with objects produced in the transitional compilation environment, but must be careful with respect to interoperability between those objects. Applications should not declare global variables of types whose sizes change between compilation environments.

along with

Applications wishing to access fseeko() and ftello() as well as the POSIX and X/Open specification-conforming interfaces should define the macro _LARGEFILE_SOURCE to be 1 and set whichever feature test macros are appropriate to obtain the desired environment (see standards(5)).

See the examples section of the man page for details.

A: The exact names and values of these #define's are implementation dependent.  Fortunately, the getconf shell command will tell you what these are when you pass it the LFS_CFLAGS parameter.  You can then pass them in on the command line when you compile.
gcc `getconf LFS_CFLAGS` -o program program.c

A: Linux/Solaris/HP-UX
-D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE

AIX
-D_LARGE_FILES

Effective for AIX >= 5.1
See also: https://www.ibm.com/docs/en/aix/7.1?topic=volumes-writing-programs-that-access-large-files


text:
Q: Improve performance of powershell script I am using following Powershell script to break the folder permissions inside the Record Libraries:
    $webUrl = 'http://intranet'
    $web = Get-SPWeb $webUrl;
    $SPBaseTypeDocumentLibrary = [Microsoft.SharePoint.SPBaseType]::DocumentLibrary
    $lists = $web.GetListsOfType($SPBaseTypeDocumentLibrary);
    foreach ($list in $lists)
    {
    if ($list.BaseTemplate.ToString() -eq "1302")
    {
    $folders = $list.Folders
    foreach ($spFolder in $folders)
    {
        # Add claims to folder
        $folderName = $spFolder.Name
        $spFolder.BreakRoleInheritance($false);
        $claimToken = "c:0-.t|clientcontracts|" + $folderName
        $claimUserDisplayName = "Claim User " + $folderName
        $roleAssignment = New-Object microsoft.sharepoint.SPRoleAssignment($claimToken,"",$claimUserDisplayName,"")
        $roleAssignment.RoleDefinitionBindings.Add($web.RoleDefinitions["Read"]);
        $spFolder.RoleAssignments.Add($roleAssignment);
        $spFolder.Update();
        }
        }
       }

       $web.Dispose()

The issue is that the script is gets very sluggish. I have about 100 Libraries and each library contains 1000 folders.
Is there any way to improve the performance of this script? How can we break permissions of folders in batches?

A: This really isnt a PowerShell issue. Instead it clearly stipulates why setting unique permissions (especially alot of different ACL's) on items/folders in a SharePoint list is not recommended, especially for large lists.
I would recommend rethinking the design...
@james-love also made a couple of posts on his blog on this issue
http://e-junkie-chronicles.blogspot.dk/2011/03/sharepoint-2010-performance-with-item.html
http://e-junkie-chronicles.blogspot.dk/2011/03/sharepoint-2010-performance-with-item_23.html