text:
Q: Is this a correct iText design? I´m making some pdf reports to be used on a web app.
I wonder if the way I´m taking to make the designs is appropriated.
This would be a screenshot of the way I´m doing the things.

As you can see, I´m using tables to position everything in the document. I think this is a pretty much similar design to HTML. But I want to know is there is a better way to get the same result I got.
This is the document without cell borders:

I could post the code if necessary. By the way, why should I spend long hours programming these kind of stuff with iText tool when I could do things faster and maybe better looking with iReport? I like iText, it´s just a question.
Sorry for my english and thanks!

A: I think with iText using a table like you have done is going to be the best route.  Looks good, nice job.


text:
Q: Outputting Huffman codes to file I have a program that reads a file and saves the frequency of each character. It then constructs a huffman tree based on each character's frequency and then outputs to a file the huffman codes for the tree.
So an input like "Hello World" would output this sequence to a file:
01010101 0010 010 010 01010 0101010 000 01010 00101 010 0001

This makes sense because the most frequent characters have the shortest codes. The issue is, this increases the file size ten-fold. I realized the reason why is because each 1 and 0 is being represented in memory as its own character, so they get each get expanded out to a byte of data.
I was thinking what I could do is convert each code (E.G. "010") to a character and save that to file - but that still would pad the code to be a byte long (Or mess it up if the code is longer than a byte).
How do I go about this? I can give code snippets if needed - I'm basically saving each code into a string so that's why the file's coming out so big (It's outputting each "bit" as a byte). If I were to convert the code to a long for example, then a code like 00010 would be represented as 2 and a code like 010 would also be represented as 2.

A: You basically have to do it a byte (or a word) at a time. Maintain a byte which you fill with bits, and a record of how many bits have been filled in so far. When you get to 8, write the byte and start over with an empty one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to read env vars into Angular 2 application So I am trying to set up an Angular 2 application for a prod and dev environment but the issue that I am running into is that I need it to point at separate urls as well as have a different javascript key and application id (which shouldn't be committed and should be env vars). Does anyone know how to get them to be useable by the app (client side)?
A little more info is that it is currently using lite server w/ the angular app and connecting to a Parse server (open source server) for information.


text:
Q: How does Core data concurrency work with multithreading in Swift 3? In my program, it uses both of
DispatchQueue.global(qos: .background)

and
self.concurrentQueue.sync(flags: .barrier)

to deal with the background multithread issues.
It is swift 3 so I use the latest way to get the childContext:
lazy var context: NSManagedObjectContext = {
    return (UIApplication.shared.delegate as! AppDelegate).persistentContainer.newBackgroundContext()
}()

I also enable -com.apple.CoreData.ConcurrencyDebug 1 to debug
Then the problem occurs:
1, When there's an API call and in the callback block (background thread), I need to fetch the core data, edit, then save. I tried to use self.context from the code above to call performBlockAndWait and do save inside of this block. The whole process goes fine but when I try to access my result outside of this block but inside of the callback block, the error occurs. I have also tried to get the objectId and getObjectById by both self.context and self.context.parent and the error occurs on this line. What did I do wrong and how should I do this? since I need to use the result everywhere in many different thread (not context).
2, I read a post says that I need one context per thread, then in my case, how do I determine which exact thread it is if it's a call back from API call and do I really need to do this?
3, You might ask that why do I need a privateConcurrentType, because my program has things need to be running in background thread so that it has to do it this way, (read from other post), is this right?
4, Even in my question 1, get object by passing objectId to different Context still not working in my case. Let's assume this is the proper way. How am I gonna manage passing so many objectID throughout my entire program in different thread without being super messy? To me this sounds crazy but I suppose there's a much cleaner and easier way to deal with this.
5, I have read many posts some are pretty old (before swift 3), they have to   do childContext.save then parentContext.save, but since I use the code above (swift 3 only). It seems that I can do childContext.save only to make it work? Am I right?

A: Core data in general is not multithreading friendly. To use it on concurrent thread I can assume only bad things will happen. You may not simply manipulate managed objects outside the thread on which the context is.
As you already mentioned you need a separate context per thread which will work in most cases but by my experience you only need one background context which is read-write and a single main thread read-only context that is used for fetch result controllers or other instant fetches.
Think of a context as some in-memory module that communicates with the database (a file). Fetched entities are shared within the context but are not shared between contexts. So you can modify pretty much anything inside the context but that will not show in the database or other contexts until you save the context into the database. And if you modify the same entity on 2 contexts and then save them you will get a conflict which should be resolved by you.
All of these then make quite a mess in the code logic and so multiple contexts seem like something to avoid. What I do is create a background context and then do all of the operations on that context. Context has a method perform which will execute the code on its own thread which is not main (for background context) and this thread is serial.
So for instance when doing a smart client I will get a response from server with new entries. These are parsed on the fly and I perform a block on context to get all the corresponding objects in the database and create the ones that do not exist. Then copy the data and save the context into database.
For the UI part I do similar. Once an entry should be saved I either create or update the entity on the background context thread. Then usually do some UI stuff on completion so I have a method:
    public func performBlockOnBackgroundContextAndReturnOnMain(block: @escaping (() -> Void), main: @escaping (() -> Void)) {
        if let context = context {
            context.perform {
                block()
                DispatchQueue.main.async(execute: { () -> Void in
                    main()
                })
            }
        }
    }

So pretty much all of the core data logic happens on a single thread which is in background. For some cases I do use a main context to get items from fetch result controller for instance; I display a list of objects with it and once user selects one of the items I refetch that item from the background context and use that one in the user interface and to modify it.
But even that may give you trouble as some properties may be loaded lazily from database so you must ensure that all the data you need will be loaded on the context and you may access them on the main thread. There is method for that but I rather use wrappers:
I have a single superclass for all the entities in the database model which include id only. So I also have a superclass wrapper which has all the logic to work with the rest of wrappers. What I am left with in the end is that for each of the subclass I need to override 2 mapping methods (from and to) managed object.
It might seem silly to create additional wrappers and to copy the data into memory from managed object but the thing is you need to do that for most of the managed objects anyway; Converting NSData to/from UIImage, NSDate to/from Date, enumerations to/from integers or strings... So in the end you are more or less just left with strings that are copied 1-to-1. Also this makes it easy to have the code that maps the response from your server in this class or any additional logic where you will have no naming conflicts with managed objects.


text:
Q: ADC registers setup using spi communication I'm new to microcontrollers - I'm trying to read external ADC values from an AD7798 ADC using SPI communication.
Initially I have to setup some ADC registers - some registers are not configured. To configure the registers, I have to use the communication register to select which register I want to configure.
For example, I want to set the AD7798 configuration register (16bit). I have code like this:
      #include
    #define ADC_CS PORTB.3
    #define WG_CS  PORTB.4
    #define MOSI   PORTB.5
    #define MISO_PU PORTB.6
    #define MISO_PIN PINB.6
    #define SCK    PORTB.7
//global functions.
unsigned int adcConfig;
unsigned int adcMode;
unsigned int adcId;

void init_io(void)
{
DDRB = 0xBF;        // make SCK, MOSI, CS1, CS2 outputs
ADC_CS = 1;              //disable ADC
WG_CS = 1;               //disable WaveGenerator
MISO_PU = 1;             //enable pull-up on MISO so we can test !RDY
}

unsigned char spi(unsigned char data)
{
//Start transmision
SPDR = data;
//Wait for transmision complete
while (!(SPSR & (1<<SPIF)));
return SPDR;
}

//Sets the waveform generator output to given phase
void SetWGPhase(unsigned int phase)
{
SPCR = 0x5A; // mode #2 F_CPU/64
WG_CS = 0;                      // enable
spi(0x20);
spi(0x00);
spi((phase >> 8) | 0xC0);       //Load into phase register 0
spi(phase & 0x00FF);
WG_CS = 1;
}

void setupAd(){
    SPCR = 0x5D;
    ADC_CS = 0;
   // while(spi(0x10) != 0x10);
    spi(0x10);                  //set up communication register for configuration reg.
    spi(0x07);
    spi(0x10);

    spi(0x08);                  //set up communication register for mode reg.
    spi(0x00);
    spi(0x0A);
    ADC_CS = 1;
    }

 unsigned int ReadAd(void)
 {
unsigned int data;
SPCR = 0x5D; // mode #3 F_CPU/16
CheckStatus();
ADC_CS = 0;                     // enable
while (MISO_PIN != 0) ;         // wait for  DOUT/!RDY line to go low
//Read data
spi(0x58);                      //Place readinstruction in communication register
data = spi(0xFF);               // read hi-byte
data = (data << 8) | spi(0xFF); // and lo-byte.
ADC_CS = 1;                     // disable
return data;
}

 unsigned char CheckStatus(void)
{
char adcStatus;
            SPCR = 0x5D;
            ADC_CS = 0;                     // enable
            while(ADC_CS_PIN);
            adcStatus = 0xFF;
while(!(adcStatus & 0x80)){

             spi(0x40);
             adcStatus = spi(0xFF);
          }
ADC_CS = 1;

return adcStatus;
}

unsigned int ReadAdConfReg(void)
{
  unsigned int retvalconfig;
SPCR = 0x5D;
ADC_CS = 0;
while (MISO_PIN != 0) ;
spi(0x50);
adcConfig = spi(0xFF);
adcConfig = (adcConfig << 8) | spi(0xFF);
retvalconfig= adcConfig;
ADC_CS = 1;
return retvalconfig;
}

unsigned int ReadAdModeReg(void)
{
  unsigned retvalmode;
SPCR = 0x5D;
ADC_CS = 0;
while (MISO_PIN != 0) ;
spi(0x48);
adcMode = spi(0xFF);
adcMode = (adcMode << 8) | spi(0xFF);
retvalmode =adcMode;
ADC_CS = 1;
return retvalmode;
}
unsigned int ReadAdIdReg(void)
{

SPCR = 0x5D;
ADC_CS = 0;
while (MISO_PIN != 0) ;
spi(0x60);
adcId = spi(0xFF);
ADC_CS = 1;
 return adcId;
}

when I print configuration register it is giving value"16383". but when I power off/on the target i am getting "1808(which is equivalent to 0x0710)" after that it is giving same value as"16383". I have tested with different configurations also but it is not changing, always printing "16383" except power off/on.I think default value.
Even with mode register it is always printing"10(which is equivalent to 0x000A)" but that is the value i am getting always, even if I change the configuration to "0x0022".
Even I have tried to read Id register, but it is giving "0x48". but in data sheet it mentioned "0xX8" for AD7798.
Thanks in advance.
Someone help me please, I am not getting any idea about what mistake I am doing here.

A: While this datasheet is making my eyes bleed with the complexity of doing a simple conversion/read, you need to make some simple changes.
I'm not sure why people are making this harder than it really is.  You pull the chip select line low, and the target IC should simply read whatever you give it until you pull it high again.  Just because your method takes an 8-bit value doesn't mean you can't call it twice to pass a 16-bit value to your IC.  There is no need to bit-bang anything.  That is nonsense.
Call your SPI method to tell the ADC you're looking to write to the configuration register:
spi(0x10);

As I understand from the datasheet, you can immediately write your 16-bit value to the configuration register after that, so you'd do:
spi(0x07);
spi(0x10);

I forget which way that'll end up being assembled on the target IC side, so you could simply reverse them if things don't work right.  There's no need to bit shift any values at all.  Worst case scenario is you have to pull the CS line back high before pulling it low again to actually send the data to write to the configuration register.
Otherwise, this is super simple.  Remember, if the target SPI device expects more than one byte, i.e. a 16-bit value, chances are good that sending the bytes in the order they'd otherwise appear normally (so if you want to send 0x1234, you'd have 0x12 and 0x34) will work fine and you won't need to shift anything.

A: The chip select line on the AD7798 is active low.  It looks like you have the polarity backwards in your code.
You need to set CS to low (0) at the beginning of the transfer, and high after the transfer.  So try this:
void setupADC()
{
    ChipSelectAd(0); // was 1
    spi(0x10);
    spi(0x07);
    spi(0x10);
    ChipSelectAd(1); // was 0
}

Also check that you're using the correct SPI mode (called CPOL and CPHA on many microcontrollers, for "clock polarity" and "clock phase").  This determines which edge of the clock triggers data transitions, and what level the clock has between transactions (during idle).
The AD7798 requires CPOL=1 and CPHA=1 (SPI mode 3).

A: Like RocketMagnet says
spi(0x07)<<8;

makes no sense. Even though the function spi() is defined char, you're shifting that to the left, and then discard it.
spi(0x07 << 8);

shifts the argument 8 bits to the left, so it will be 0x0700. But that doesn't do what you want. You don't de-assert SS (Slave Select) between calls of the spi() function, so that will be automatic. I would change it to have an optional argument hold_ss, so that you can shift in the first byte, then the second one, and only then de-assert SS.
That way you'll be able to shift 16 bits of data to the ADC, without having to shift data before the spi() call. Alternatively you can write a function spi16():
unsigned int spi16(unsigned int data16)
{
    assert_SS(IOpin);
    spi8(data >> 8); /* assuming LSB is shifted first */
    spi8(data);
    deassert_SS(IOpin);
}

(I'm ignoring the incoming data for the moment.)
The datasheet indicates that the Configuration Register indeed needs 16 bit, but while it doesn't give details, I would expect it needs them as a single transfer. Check the spi() function of your microcontroller's compiler, and the microcontroller's datasheet to see if 16-bit transfers are actually possible in the first place.
If the controller can do 16-bit transfers you should be able to do this:
spi(0x0710);

If only 8-bit transfers are possible, I think you'll have to resort to a bit-banged SPI (which is not that hard).
edit
Rocketmagnet points me to the definition of the spi() function:
char spi(char data)

That says it all: the argument is of type char, so only 8-bit.
(Thanks for the pointer (no pun intended), Rocketmagnet)

A: What micro are you using? You provided no information as to what is spi() doing there. It might be sending 8bits. In which case your 8 bit shift results in nonsense.
Now, you stated you want to send "0x0710". Think for a second what may be happening in your code.
You seem to be confused about how this SPI transfer takes place.
First, you're sending 0x10. Then, supposing your spi() function sends 16 bits, you're sending 0x0700. You've just transferred 0x100700.
I'm quite sure your spi() function does not in fact send your 16 bits. So you're basically sending two bytes: 0x10 and 0x00. Well done.
You have to reverse the byte order when sending multiple bytes via SPI. First, send 0x07, and only then send 0x10.


text:
Q: Can someone please fix it so that the function can detect whether the input has at least one symbol in it? import os
import time

def strong(password, verifier):
  symbols = "! # $ % & ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~"
  password = str(password)
  if len(password) > 8:
    if len(password) < 15:
        for i in symbols:
          if password.find(symbols) is True:

I want to see if I can fix this part because I am not sure how I can use this function to find a special character in the password.
            if password.isalnum():
              verifier = 1
              return 'good password', verifier
            elif password.isalpha():
              return 'Your password is only letters'
            elif password.isnumeric():
              return 'Your password is only numbers'
          else:
            return 'no symbols'
    else:
      return 'Too big'
  else:
    return 'Too small'

A: You can use any() along with a generator comprehension to check this:
if any(ch in password for ch in symbols):

I will point out that the symbols list also contains spaces, so you may want to take those out if you don't want a space to qualify as a symbol.

A: You can simplify this (and make debugging easier) by just returning after each failed check instead of having all the deeply nested if/else.  Since in the "good password" case you're returning a "verifier" as well as the "good password" message, I'm figuring you probably want to return a false value for the "bad password" cases as well:
def is_strong(password):
    symbols = set("!#$%&()*+,-./:;=?@[]^_`{|}~")
    if len(password) < 9:
        return "Too small", False
    if len(password) > 14:
        return "Too big", False
    if not any(c in symbols for c in password):
        return "No symbols", False
    if password.isalpha():
        return "Your password is only letters", False
    if password.isnumeric():
        return "your password is only numbers", False
    return "Good password", True

Once the function is simplified down, we can see that the isalpha and isnumeric checks won't actually do anything, because we've already established that the password contains non-alphanumeric symbols!  Instead I think you want to do:
def is_strong(password):
    symbols = set("!#$%&()*+,-./:;=?@[]^_`{|}~")
    if len(password) < 9:
        return "Too small", False
    if len(password) > 14:
        return "Too big", False
    if not any(c in symbols for c in password):
        return "No symbols", False
    if not any(c.isalpha() for c in password):
        return "No letters", False
    if not any(c.isdigit() for c in password):
        return "No numbers", False
    return "Good password", True

We can test the function like this:
strong, password = False, ""
while not strong:
    password = input("Set password: ")
    msg, strong = is_strong(password)
    print(msg)

Set password: bob
Too small
Set password: bobledeboingerberoo
Too big
Set password: bobbington
No symbols
Set password: bobbington!
No numbers
Set password: bobbington3!
Good password

A: Make your list of special characters a set and you'll be able to use the isdisjoint function to check that there are no symbols in the password:
if {*"!#$%&()*+,-./:;=?@[]^_`{|}~"}.isdisjoint(password):
    print("Password has no symbols")
else:
    print("Password contains at least one symbol")


text:
Q: Fetch OpportunityLIneItem along with OpportunityId in Map Map<Id,List<OpportunityLineItem>> oliList=new Map<Id,List<OpportunityLineItem>>();
 for(Opportunity opp:eligibleOpp)
           {
               if(opp.opportunitylineitems.size()>0)
               {
                if(oliList.containsKey(opp.Id))
                   {
                    oliList.get(opp.Id).add(opp.opportunitylineitems);
                    System.debug('Map values iteration '+oliList);

                   }
                else
                  { oliList.put(opp.Id,new list<OpportunityLineItem>{opp.OpportunityLineItems});
                     oliListToDel.add(opp.OpportunityLineItems);
                     System.debug('Map values iteration else con'+oliList);

                  }
               }
           }

On this line I am getting error :
oliList.put(opp.Id,new list<OpportunityLineItem>{opp.OpportunityLineItems}
Please help me on this. I am getting

List has more than 1 rows for assignment.

Even if  I have taken list of lineitems still I am getting this error.

A: The syntax for creating a list as a copy of another list is
List<sObject> myList = new List(someOtherList);
rather than the {} notation used to write list literals.
Here, you don't need to create a new list at all. Just put opp.OpportunityLineItems directly into your Map.


text:
Q: How to use arrow functions inside other functions? the full code is in the link I am to trying declare an arrow function by assigning it to the variable randomColor using the array.push() method, but I am getting the error "randomColor is not defined" when I run the code. Please help.
function generateRandomColors(num){
 let arr = [];
 for(let i=0;i < num;i++){
     arr.push(randomColor());
 }
 return arr;
}

let randomColor = () => {
    //random for red
    let r = Math.floor(Math.random() * 256);
    //random for blue
    let g = Math.floor(Math.random() * 256);
    //random for green
    let b = Math.floor(Math.random() * 256);
    //return rgb
    return "rgb(" + r + ", " + g + ", " + b +")";
};

A: When you use let (e.g. let randomColor), the variable you declare isn't usable before its declaration. So if you try calling generateRandomColors before your let randomColor = ... declaration, you'll find that generateRandomColors isn't yet defined.
See especially the Temporal Dead Zone for let and const:

Temporal Dead Zone
let bindings are created at the top of the (block) scope containing the declaration, commonly referred to as "hoisting". Unlike variables declared with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. Accessing the variable before the initialization results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.

If that doesn't solve your problem, can you share the code where you try calling generateRandomColors?


text:
Q: Need help to vibrate a motor for an original musical instrument everyone. I am asking you to help me out for making original musical instrument.
The goal is to vibrate a small motor by square wave signal witch is generated in a synthesizers in my Mac.
Here is what I tried;
Square wave sound (in my laptop)
-> stereo output
-> stereo cable
-> headphone amplifier
-> stereo cable
-> motor
I cut the end of the stereo cable to connect the left(or right) wire and the ground wire.
(please check the photo below)

However, it doesn't work. I could hear the sound from the amplifier by headphone, so there might be problems between the amp and the motor.
Let me tell you the specs of the amplifier;
make/model: Pyle Audio, PHA40
input impedance: 100K-ohm, Unbalanced
Max Input Level: +15dBu
output impedance: 80-Ohm, Unbalanced
Max output Level: 40mW in 100ohm
Max Gain: 20dB
S/N Ratio: More than 90dB
THD: Less than 0.03%
And the motor is DC 1.5-6V 1750-7000(<- I have no idea what does this, mA?)
Hope I can get any ideas/answers from you guys.
Thanks,

A: The voltage from your amplifier is AC so on average it's 0v, and even if it's swinging above 1.5v it's not doing so for long enough, or with enough current capability, to even get the motor started.
First try creating a source of DC for the motor, perhaps with a transistor, then you can think about making the speed controllable / modulatable.

A: I'm not quite sure what you are trying to achieve.  Are you trying to make the motor speed represent the frequency from your oscillator?
RPM is Rotations Per Minute.  1750 - 7000 RPM would correspond to about 29 Hz through about 117 Hz.
If you want motor speed to be proportional to the incoming frequency, you can use a circuit block called a "Frequency To Voltage" converter.


text:
Q: Extract first and last column from text file I have a text file, I only want the first column and the last column.  However the problem is they are separated by both whitespace and tabs at random places, making it hard for me to use cut
USER02163 name BAD
USER5415 ab lsi ei GOOD
USER15356 sl oe ow BAD

Desired output is:
USER02163 BAD
USER5415 GOOD
USER15356 BAD

Does anyone have a hacky way I can get my desired output?

A: Easiest by using awk.  The command is:
awk '{print $1, $NF}' filename

A: When you specify field separator as space in awk it will include single and multiple spaces. So you can use like this,
awk -F " " '{print $1,$NF}' file

Same as unxnut answer. Added with field separator which gives clear insight.

A: Use this sed command
$ sed -r 's/([^ ]*) (.*) (.*$)/\1  \3/' filename

The output is :
   USER02163  BAD
   USER5415  GOOD
   USER15356  BAD


text:
Q: Array section with vector subscript as procedure argument Here is an example of my problem (in my real program, A would be much larger and random) :
    MODULE MOD_TST
        contains
        subroutine function_tst(A,B)
            real,intent(in) :: A(:)
            real,intent(out) :: B(:)
            integer :: i, n
            n = size(A)
            do i=1,n; B(i) = A(i); end do
        end subroutine function_tst
    end module MOD_TST

    PROGRAM PROG_TST
      USE MOD_TST

      IMPLICIT NONE
      integer,allocatable :: A(:),B1(:),B2(:),subA(:),subB(:)
      integer :: i, n = 10, p = 3
      integer,allocatable :: list(:)

      allocate(A(n),B1(n),B2(n))
      A = (/ 9, 5, 4, 7, 8, 1, 6, 0, 3, 2/)

      list = pack ( [( i, i=1,n )] , modulo(A,p) .eq. 0)
      allocate(subA(size(list)),subB(size(list)))
      subA=A(list); subB=B1(list);

      call function_tst(subA,subB)
      B1(list) = subB

      call function_tst(A(list),B2(list))

      write(*,*)'A ',A
      write(*,*)'B1',B1
      write(*,*)'B2',B2
    END PROGRAM PROG_TST

The output I get is :

A  9  5  4  7  8  1  6  0  3  2
B1 9  0  0  0  0  0  6  0  3  0
B2 0  0  0  0  0  0  0  0  0  0

Is there a way to make it work without having to create an intermediate variable for the procedure?

A: An array section with vector subscript is very heavily restricted in how it can be used. As a general (subjective) rule, it's fair to say they should be avoided if possible. Before coming on to the details, what is an array section with vector subscript?
A vector subscript is an integer array or rank 1, and an array section with such a subscript is one where the elements of the whole are selected by this subscript array:
integer :: i(5)=[1,2,3,4,5]
print *, i([1,2,5])

The array section has a vector subscript whenever this form is used, whether it has all of the elements of the whole array, is a contiguous sub-array, or selects an element more than once.
At the highest level, an array with vector subscript is particularly restricted when the vector array specifies the same element more than once: such an array section can never be subject to "definition":
integer i(5)
i([1,3,2]) = [1,2,3]  ! Allowed
i([1,3,1]) = [1,2,3]  ! Not allowed

So, in many cases assignment such as can be seen in the subroutine function_tst can be done directly to the array section.
However, in the case of a passing such an array section to a procedure, the dummy array is never1 definable, even if there is no repeat or if the array section is a contiguous part of the whole array.  This means, in the case of the question
call function_tst(A(list),B2(list))

is never allowed.
Note also that an array section with vector subscript is subject to restrictions which avoid easy "hacking":

*

*an array section with vector subscript cannot be a target of a pointer

*an associate name associated with an array section with vector subscript is never definable

One way around this is to create a temporary copy and pass the changes back to the original. This is very general, even if painful to write. It isn't, though, guaranteed to be safe for all procedures:
Btemp = B(list) ! If the argument is for an intent(inout), skip if inient(out)
call other_subroutine(A(list), Btemp)
B(list) = BTemp  ! Can be dangerous

Specific to the type of action in the specific example is an elemental procedure.  Just as we can write
B2(list) = A(list)  ! No repeats in list

we can
call function_tst(A(list),B(list))

if we make that subroutine elemental
elemental subroutine function_tst(A,B)
  integer, intent(in) :: A
  integer, intent(out) :: B
  B=A
end subroutine function_tst

If the subroutine is suitable to be elemental, then you also have the option of looping over the indexing array:
do i=1, size(list)
  call function_tst(A(list(i):list(i)), B(list(i):list(i)))
end do

These are suitable only when there is total independence between elements.
Intermediate between these extremes is rewriting as a function (as shown in veryreverie's answer. With a function you also may be able to consider masked assignment, such as with WHERE statements and constructs.
As with simple assignment activities, such an elemental or looped subroutine or function, or masked assignment will not be so general as to cover all desires. Each alternative has its own potential pitfalls or drawbacks. To repeat: vector subscripts are highly restricted. They can, however, frequently be avoided.

1 There is are two exceptions: continue reading for one; the second is the VALUE attribute (which doesn't help in this case).

A: If you're okay modifying function_tst, then you can change it from a subroutine to a function, e.g.
module mod_tst
  implicit none
contains
  function function_tst(A) result(B)
    real, intent(in) :: A(:)
    real, allocatable :: B(:)

    B = A
  end function
end module MOD_TST

And then the relevant part of your program is simply
B1(list) = function_tst(A(list))

This approach works well for replacimg most subroutines with exactly one intent(out) argument, but cannot trivially replace subroutines:

*

*with intent(inout) arguments

*which leave parts of the intent(out) argument undefined (hat tip @francescalus)

*with multiple intent(out) arguments.


text:
Q: How can I specify as return type of a method the type of the object upon which the method is called? Let's say I have an Interface 'Inter', and Inter has a method
Inter someMethod();

How can I specify that the type of the return object has to be the same as the object upon which the method is called?
So if I have two classes 'C1' and 'C2' that implement Inter, if an instance of C1 calls someMethod (c1.someMethod()) the result will be an instance of C1, whereas if an instance of C2 calls someMethod the result will be an instance of C2.
How about parameters? If Inter has a second method
void someMethod2(Inter inter)

How can I specify that the parameter has to be an instance of the same class as the object calling the method?

A: You can try  something like this
public interface Inter<T> {

    public T doSomething();
}

public class C1 implements Inter<C1> {

    @Override
    public C1 doSomething() {
        return new C1();
    }
}

public class C2 implements Inter<C2> {

    @Override
    public C2 doSomething() {
        return new C2();
    }
}

A: Using Generics.
public interface Inter<T> {

    T someMethod();
    void someMethod2(T obj);

}

public class C1 implements Inter<C1> {

    public C1 someMethod() {
      // ..
    }

    public void someMethod2(C1 obj) {
      // ..
    }

}

public class C2 implements Inter<C2> {

    public C2 someMethod() {
      // ..
    }

    public void someMethod2(C2 obj) {
      // ..
    }

}

Reference :
Generic Types (The Java™ Tutorials > Generics)
Edit : (Using a bounded generic type; in response to OP's comments)
public interface Inter<T extends Inter<T>> {

    T someMethod();
    void someMethod2(T obj);
}

public class C1 implements Inter<C1> {

    public C1 someMethod() {
        return new C1();
    }

    public void someMethod2(C1 obj) {
      // ..
    }
}

public class C2 implements Inter<C3> { // ERROR
    ..
}

But, here comes the catch.
public class C2 implements Inter<C1> { // COMPILES!
    ..
}

Because, C1 also satisfies T extends Inter<T>. This is as far as this can go I believe.
Reference :
Bounded Type Parameters (The Java™ Tutorials > Generics)

A:
How can I specify that the type of the return object has to be the
  same as the object upon which the method is called?

You cannot do this in Java.


text:
Q: Are there performance improvements to Google services APIs if your server is hosted on Google App Engine? We are currently hosted on Amazon's AWS platform, however our server makes extensive use of many of the Google services API's including:

*

*Google Maps

*Google Static Maps

*Google Places

During normal usage, some of these API requests can take over 1-3 seconds and that's not exactly great for user experience. I wonder if there are any performance gains if we were to host our server on top of Google App Engine instead. An example would be getting better performance if you make use of as many AWS platforms for your system rather than spreading them out between multiple cloud services provider.

A: Yes the roundtrip to call the api will be faster but not the actual api. It can make a noticeable difference if you are calling many google apis on the same servlet call.


text:
Q: section value is always 1 in numberOfRowsInSection in UITableViewController I have two sections in tableview that is located inside tableviewcontroller
For some reason the section value in method numberOfRowsInSection is always "1". Thats quite strange because, everything seems fine.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    int i=section;
    if(section==0)
        return 1;
    else{
        return [self.flightDetailsArray count];
    }
}

In storyboard i have a table with two sections
Ok, once again doing it for you to understand the problem. Watch this code
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.

    NSLog(@"Section: %d",(int)section);
    if(section==0)
        return 1;
    else{
        return [self.flightDetailsArray count];
    }
}

in Log i see "1" always
what's that? its strange

A: I dont understand the reason behind this due to the fact i'm also a beginner but as far as I'm concerned i think you're trying to return 1 row at first time and in the next step you want to return count of the flightDetailsArray so maybe you can achieve that by these steps :-
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    static int i=0
    if(i==0)
        return 1;
        i++;
    else{
        return [self.flightDetailsArray count];
    }

}

A: I think that you want to return only 1 row in your 1st section and then the number of objects in your flightDetailsArrayin the second section. If that is the case, then just do this,
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section==0)
        return 1;
    else{
        return [self.flightDetailsArray count];
    }
}

Now, it may be possible that your second section will also hold 1 row if there is only one object in your flightDetailsArray.
Please try to print NSLog(@"%@", [self.flightDetailsArray count]) and see the object number.

A: Sorry, guys. The problem was that i used satic type of tableview, but had inside also dynamic cells. So i didn't pay attention to it. Then i changed id to dynamic, and added he dynamic sections and it worked just fine. Sorry for taking your time.


text:
Q: Regular expression to verify that string contains a separator comma ( , ) but not a point ( . ) I'm using SoapUI and I have responses of JSON which contains strings.
For example about string "84,96". I need to create a regular expression which verifies that all value decimals of this JSON are containing a comma (,) but not a point (.)
Examples:
"84,96" is Good
"84.96" is wrong

A: ^(\d+?,?\d+)$

this solves your question test here Test

A: Numbers
84,96 <-- good
84.96 <-- bad

REGEXEP:
\d+,\d+

Explanation:
\d+ <= All Numbers (84)
,   <= Only Comma  (,)
\d+ <= All Numbers (96)

Result:
84,96

Test Here: https://regex101.com/r/7NNRZy/1


text:
Q: Docker Compose - Network_mode:Service: - 2 containers cant talk to each other Over the last couple weeks I have been getting to grips with docker and decided to teach myself. I'm getting a fairly good grasp of it now and have just ventured out into using docker compose.
I have a docker compose yml file that I found online and have been modfying it to my needs.
Basically this docker compose file runs Sonarr, Radarr, Transmission, openvpn and nginx.
Sonarr and Radarr are using service:vpn as their network so that their traffic passes through the VPN.
NGINX is used as a reverse proxy to get to Sonarr and Radarr at the following urls - http://radarr:7878 & http://sonarr:8989 using "sonarr.myredacteddomain/com" "radarr.myredacteddomain/com" which is working great.
NGINX uses the "Link:" to be able get to sonarr and radarr as you can see from my yml below. Problem i'm now having is that I need Radarr and Sonarr to be able to talk to transmission so that they both know where my download client is located. If on Sonarr I enter transmission:9091 or transmission.myredacteddomain/com Sonarr/Radarr cant see it.
Looking at these containers Radarr and Sonarr dont seem to have an IP address so how is it that NGINX can see them via radarr:7878 etc but Sonarr and Radarr cant see transmission in the same way? Can anyone help me with my yml file here?
version: '3.0'
networks:
  default:
    ipam:
      driver: default
services:
  jackett:
    image: linuxserver/jackett
    depends_on:
      - vpn
    restart: always
    network_mode: "service:vpn"
    environment:
      PGID: 1000
      PUID: 1000
      TZ: Europe/London
    volumes:
      - /mnt/user/config/jackett:/config
      - /mnt/user/media/downloads/jackett:/downloads

  transmission:
    image: linuxserver/transmission:48
    depends_on:
      - vpn
    environment:
      TZ: 'Europe/London'
      PGID: 1000
      PUID: 1000
    network_mode: "service:vpn"
    tmpfs:
      - /tmp
    restart: unless-stopped
    stdin_open: true
    tty: true
    volumes:
      - /mnt/user/config/transmission:/config
      - /mnt/user/media/downloads:/downloads

  radarr:
    image: linuxserver/radarr
    depends_on:
      - vpn
    restart: always
    network_mode: "service:vpn"
    environment:
      PGID: 1000
      PUID: 1000
      TZ: Europe/London
    volumes:
      - /mnt/user/config/radarr:/config
      - /mnt/user/media/downloads/complete:/downloads
      - /mnt/user/media/movies:/movies

  sonarr:
    image: linuxserver/sonarr
    depends_on:
      - vpn
    restart: always
    network_mode: "service:vpn"
    environment:
      PGID: 1000
      PUID: 1000
      TZ: Europe/London
    volumes:
      - /mnt/user/config/sonarr:/config
      - /mnt/user/media/downloads/complete:/downloads
      - /mnt/user/media/tvshows:/tv

  vpn:
    image: dperson/openvpn-client
    sysctls:
      - net.ipv6.conf.all.disable_ipv6=0
    cap_add:
      - net_admin
    dns:
     - 8.8.4.4
     - 8.8.8.8
    environment:
      TZ: 'Europe/London'
    read_only: true
    tmpfs:
      - /tmp
    restart: unless-stopped
    security_opt:
      - label:disable
    stdin_open: true
    tty: true
    volumes:
      - /dev/net:/dev/net:z
      - /mnt/user/config/vpn:/vpn

  web:
    image: nginx
    depends_on:
      - transmission
      - sonarr
      - jackett
      - radarr
    environment:
      TZ: 'Europe/London'
      IPV6: 0
    links:
      - vpn:transmission
      - vpn:jackett
      - vpn:radarr
      - vpn:sonarr
    ports:
      - "80:80"
      - "443:443"
    read_only: true
    volumes:
      - /mnt/user/config/nginx:/etc/nginx/conf.d:ro
      - /mnt/user/config/nginx/ssl:/etc/nginx/ssl:ro
    tmpfs:
      - /run
      - /tmp
      - /var/cache/nginx
    restart: unless-stopped
    stdin_open: true
    tty: true

A: Managed to work it out!
Turns out that containers that are using the Network_Mode:Service:vpn share the ip address of the VPN docker.
Solved my own problem!


text:
Q: Django RAW SQL query how to pass date comparison I am working with Django Raw SQL as I want to build a relatively complex query,
As part of it, I have a case statement that says 'if the date on the record is < today then 1 else 0 - this works.
overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).raw('''

     SELECT '1' as id, case when research_due < "2022-12-01" AND research_status != "done" then 1 else 0 end as count
     from app_task where taskid = "''' + taskidx + '''"''')

overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).raw('''

 SELECT '1' as id, case when research_due < "2022-12-01" AND research_status != "done" then 1 else 0 end as count
 from app_task where taskid = "''' + taskidx + '''"''')

However, when I want to swap the hard coded date for TODAY() I can't make it work. I have tried passing a python date variable into the script (td = datetime.date.today()), but it doesn't return the right results!
Can anyone advise me please?

A: There is no need to do this. You can use condition expressions [Django-doc]:
from django.db.models import Case, Q, Value, When

overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).annotate(
    count=Case(
        When(
            ~Q(research_status='done'),
            research_due__lt='2022-12-01',
            then=Value(1),
        ),
        default=Value(0),
    )
)
Or if a boolean is sufficient as well:
from django.db.models import Q

overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).annotate(
    count=~Q(research_status='done') & Q(research_due__lt='2012-12-01')
)
or for older versions of Django with an ExpressionWrapper [Django-doc]:
from django.db.models import BooleanField, ExpressionWrapper, Q

overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).annotate(
    count=ExpressionWrapper(
        ~Q(research_status='done') & Q(research_due__lt='2012-12-01'),
        output_field=BooleanField(),
    )
)
You can replace '2022-12-01' with date.today().


text:
Q: What is the best practice to create MSI with some other child MSI as prerequisite? Currently we are using Inno Setup as a bootstrapper to install the MSI prerequisites. It makes bit complex to maintain the setup. I found the Burn tool which may help us to resolve this issue by having a single setup to install whatever we need. I could not find either documentation or sample for this tool. Is anyone have idea about this? Or is there an alternative solutio?
I am looking for the alternative solution for the actions that we do with the ISS bootstrapper now:

*

*Extract the files (Main setup, Prerequisite setup)

*Need to ensure prerequisites status and install on demand.

*Start main install.

A: The Burn tool is still a bit raw to be used in production. Many people in the WiX community recommend dotNetInstaller.


text:
Q: Tag html width overflow-y and fancybox scroll I apologize in advance for possible mistakes in English.
My question is next. In my style.css, html tag have propertie overflow-y:scroll. Farther i'm connect fancybox v3. When i call fancy modal, it is opened correct. But window doesn't fixed by center, because fancy inherite overflow-y:scroll from html tag. How do i fix this? When fancy is opened scrollbars should don't show to me.

A: You could simply change the CSS-definition via jQuery or something when opening the modal, then revert to "scroll" when closing it. Something like this...
$('[data-fancybox]').fancybox({
    afterShow: function( instance, slide ) {

        $('html').css('overflow-y','inherit');

    },
    afterClose: function( instance, slide ) {

        $('html').css('overflow-y','scroll');

    }
});


text:
Q: How can i implement fluid in typoscript I'm currently trying to implement a way to render images responsive. Right now i have different cropvariants in the TYPO3 image tool for different screensizes. The problem is i can't use fluid because of how the template is done. So right now I'm looking for a way to transfer the fluid code to Typoscript but sadly I'm not very experienced in Typoscript.
This is my fluid code:
<f:for each="{images}" as="image">
<picture>
    <source srcset="{f:uri.image(image: image, maxWidth: settings.maxImgWidth, cropVariant: 'default')}" media="(min-width: 1200px)">
    <source srcset="{f:uri.image(image: image, maxWidth: '992', cropVariant: 'default')}, {f:uri.image(image: image, maxWidth: '1984', cropVariant: 'default')} 2x" media="(min-width: 992px)">
    <source srcset="{f:uri.image(image: image, maxWidth: '768', cropVariant: 'tablet')}, {f:uri.image(image: image, maxWidth: '1536', cropVariant: 'tablet')} 2x" media="(min-width: 768px)">
    <source srcset="{f:uri.image(image: image, maxWidth: '768', cropVariant: 'mobile')}, {f:uri.image(image: image, maxWidth: '1536', cropVariant: 'mobile')} 2x" media="(max-width: 767px)">
    <!---Fallback--->
    <img class="img-responsive" src="{f:uri.image(image: image, maxWidth: settings.maxImgWidth, cropVariant: 'default')}" alt="{image.alternative}" longdesc="{image.description}" title="{image.title}">
</picture>

I would be grateful for any advice.

A: You always could use a FLUIDTEMPLATE object in typoscript, but that wiold mean you have to provide all the necessary data used in the fluid as variables. That is even possible for defining variables for other FLUID templates.
But you probably are looking for realizing the same you have in FLUID in pure typoscript.
That is possible as it was used before FLUID (and without marker templates).
Just build a COA and use wraps everywhere.
Your outer structure is the f:for loop which iterates over some files.
Now you need this loop in typoscript. That could be a dataprocessor or a FILES object.
some inspirations (not tested):
temp.test = FILES
temp.test {
  references {
    table = pages
    uid.data = current:uid
    fieldName = media
  }
  renderObj = COA
  renderObj {
    wrap = <picture>|</picture>
    10 = IMGRESOURCE
    10 {
      wrap = <source srcset="|" media="(min-width: 1200px)">
      file {
        import.data = file:current:uid
        treatIdAsReference = 1
        maxWidth < plugin.....settings.maxImgWidth
        cropVariant = default
      }
    }
    20 = COA
    20 {
      noTrimWrap = |<source srcset="| 2x" media="(min-width: 992px)">|
    }
    20.10 < .10
    20.10.file.width = 992m
    20.10.wrap = |,
    20.20 < .10
    20.20.file.width = 1984m

    30 < .20
    30 {
      noTrimWrap = |<source srcset="| 2x" media="(min-width: 768px)">|
      10.file {
        cropVariant = tablet
        width = 768m
      }
      20.file {
        cropVariant = tablet
        width = 1536m
      }
    }
    40 < .30
    40 {
      noTrimWrap = |<source srcset="| 2x" media="(max-width: 768px)">|
      10.file.cropVariant = mobile
      20.file.cropVariant = mobile
    }
    // fallback
    50 = IMAGE
    50 {
      file {
        import.data = file:current:uid
        treatIdAsReference = 1
        cropVariant = default
        width < plugin.......settings.maxImgWidth
      }
      class = img-responsive
      altText.data = file:current:alternative
      titleText.data = file:current:title
    }
  }
}


text:
Q: ShinyDashboard - Zoom entire browser with CSS I am trying to implement zoom on my ShinyDashboard as the layout looks better when it is at 80% zoom for the web browser.
I found an article on SO for a Shiny app, however, it doesn't work for Shinydashboard. When I implement the CSS, I get a lot of dead white space.
Article to SO: Zoom out shiny app at default in browser
Simple Code Example:
library(shiny)
library(shinydashboard)

header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody(
  tags$style("
              body {
             -moz-transform: scale(0.8, 0.8); /* Moz-browsers */
             zoom: 0.8; /* Other non-webkit browsers */
             zoom: 80%; /* Webkit browsers */
             }
             "),
  "test")

ui <- dashboardPage(header, sidebar, body)

server <- function(input, output, session) {}

shinyApp(ui, server)

A: I do not know if this solves your problem, but try adding a height in your app
library(shiny)
library(shinydashboard)

header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody(
  fluidPage(
   tags$head(tags$style(HTML('
                         .content-wrapper,
                        .right-side {
                          background-color: #ffffff;
                          height: 1200px;
                         }

                body{
                -moz-transform: scale(0.8, 0.8); /* Moz-browsers */
                zoom: 0.7; /* Other non-webkit browsers */
                 zoom: 70%; /* Webkit browsers */
                }
                          '))),
  "test")
  )

ui <- dashboardPage(header, sidebar, body)

server <- function(input, output, session) {}

shinyApp(ui, server)

A: library(shinyjs)

runjs(
  "document.body.style.zoom = 0.8;
  var elem = document.getElementsByClassName('wrapper');
  elem[0].style.height = '125vh';"
)

This snippet stretches shinydashboard content relatively to fill the screen while zooming it out. However, I don't recommend this because I ran into issues with interactive map mechanics, a different set of problems on different browsers. Specifically, I'm using googleway's google maps and it stops rendering map tiles, zooms from a distance away where you clicked, and map markers move randomly as you drag the map.
This is an isolated instance of bugs, but I'm sure there are other you could run into as well, hence my recommendation against this.
In addition, you may have to fiddle with the right vh value and stretch whatever objects inside your dashboard to make it look right.


text:
Q: IntelliJ navigation I'm using IntelliJ to do Java Development for an application where we use JSF in a few places.  In the .jsp file I have defined my backing class and the code runs properly.
My question is: How do I set up my environment so that when I center click on the method names, which use EL format, IntelliJ navigates to the proper method in the proper class.

A: Having taken a quick look at my IntelliJ install, if you go to File->Settings, there should be a keymap section under the IDE Settings header.  Make a new keymap profile other than default.  You can probably just copy the default and give it a new name.  In the actions window, open Main Menu->Go To and there should be an action called "Implementation(s)".  The description of this action seems to match what you are looking for.  Click Add Mouse Shortcut, and center click in the click pad area to set it.  I didn't want to actually change my settings, so I didn't finish the steps myself, but this should do what you are wanting to do.  It may warn you that you are overwriting a shortcut to another action, so be aware of that.
Hope this helps.
This is using IntelliJ Version 9 beta.

A: in JSP I am using something like this
<%--@elvariable id="owner" type="com.mysite.data.Owner"--%>

This is a comment specific for intellij I guess. In this way when the owner variable is used anywhere like:
${owner.name}

is known to intellij that is of a Owner type. Intellij then automatically go to the class definition by pressing CTRL+B or middle mouse button.
This is working with intellij idea 9 beta and I remember that this feature was broken in 8.1.1. Prob  it is working again in 8.1.x
Probably the same approch will also work for JSF.


text:
Q: Jugglingdb how to use multiple databases I'm using jugglingdb as ORM for my nodejs project.
there is a central database with all users, and also every user have it's own database.
when I'm using models I just require them where I need.
The problem is that models should be connected for every user to different database and I don't want o include models in every route in order to inject request to it.
Can I somehow set a middleware or something?


text:
Q: Can't stop widget chart from rerendering in React We are making a crypto trading calculator and I am struggling with a React rerendering issue because my React knowledge is somewhat limited and I don't have lots of practice.
There are 10 calculator inputs on the page, one drop-down menu (implemented via React Select) for the selection of any crypto coin by the user, and one chart widget from TradingView implemented via https://www.npmjs.com/package/react-ts-tradingview-widgets.
The idea is that the user selects the coin of their preference via the drop-down menu, triggering the TradingView chart rerendering to show the chart of the coin that the user chose.
Everything works well, however the chart is rerendering every time that any state changes on the page. And with 10 inputs for calculations it happens very often, sometimes a couple of times per second.
So I'd like the chart to rerender only upon the selection of a new coin by the user, which is represented by state symbol, which is defaulted to BTC upon mounting.
const [symbol, setSymbol] = useState('BTCUSDT');
Here's the TradingView widget chart

              <AdvancedRealTimeChart theme="dark" symbol={symbol} interval="60" autosize </AdvancedRealTimeChart>

I was wondering if it's possible to use useEffect hook in order to make it rerender only upon symbol state change. Maybe something like this?
  useEffect(() => {
    const widgetChart =

              <AdvancedRealTimeChart theme="dark" symbol={symbol} interval="60" autosize </AdvancedRealTimeChart>

  }, [symbol])

And then placing {widgetChart} in the JSX?
Or maybe by creating a function and then running it inside useEffect and placing it in JSX?
function returnWidget() {
    return (

              <AdvancedRealTimeChart theme="dark" symbol={symbol} interval="60" autosize></AdvancedRealTimeChart>

)
}

useEffect(() => {
    returnWidget()
  }, [symbol])

And I think I can use something like React.memo(). What would be the most modern and easiest way to do this? Thanks a lot everyone!

A: React re-render a component every time its state changes as well as re-render  children.
It is difficult to provide you code examples without having your code (maybe you could provide your code?).
You could wrap your expensive children (like chart) in React.memo, so it would not re-rendered until it's props changes. This way the parent still re-renders as often as it's state changes but the child will skip this re-render if it's props the same.
Let's say the code bellow: you can click on the button and MyWidget re-renders because someState changed. But MyWidget is not re-rendered because the data is not changed.

function MyWidget(props) {
   console.log("I was rendered");
   return
{JSON.stringify(props.data)}

}

const MyWidgetMemoized = React.memo(MyWidget);

function MyPage() {
   const [someState, setSomeState] = useState(0);
   const [data, setData] = useState({});

   return (
     <>
        <button onClick={()=>setSomeState(s => s+1)}>
             Counter {someState}
        </button>
        <MyWidgetMemoized data={data} />
     </>
   );
}

A: Finally managed to resolve this and I was on the right path before. It can be done using useEffect hook really easily just like I previously proposed.
useEffect(() => {
    const widgetChart =

              <AdvancedRealTimeChart theme="dark" symbol={symbol} interval="60" autosize </AdvancedRealTimeChart>

  }, [symbol])

All you need to do apart from that is to add state, set it to widgetChart inside the hook, and then simply place the {widgetChart} in the JSX where it should be displayed.
  const [chart, setChart] = useState(null);

  useEffect(() => {
    const widgetChart = (

        <AdvancedRealTimeChart theme="dark" symbol={symbol} interval="60" autosize />

    );
    setChart(widgetChart);
  }, [symbol]);


text:
Q: Regex escape escape characters in PHP So I have this regex that works on regex101.com
(?:[^\#\\S\\+]*)

It matches the first from first#second.
Whenever I try to use my regex with PHP's preg_replace I don't get the result I expect.
So far I tried it via preg_quote():
\(\?\:\[\^\\#\\S\\\+\]\*\)

And tried it with escaping the original \\ with 4 \'s:
\(\?\:\[\^\\#\\\\S\\\\\+\]\*\)

Still no success. Am I doing something fundamentaly wrong?
I'm just using:
preg_replace("/$regex/", "", $string);

All my other regexes that don't need so many escape chars work perfectly that way.

A: When you use (?:[^\#\\S\\+]*) in a preg_match in PHP, both in a single or double quoted string literal, the \\S is parsed as a non-whitespace pattern. [^\S] is equal to \s, i.e. it matches whitespace.
The preg_quote() function is only meant to be used to make any string a literal one for a regex, it just escapes all chars that are sepcial regex metacharacters / operators (like (, ), [, etc.), thus you should not use it here.
While you could use a regex to match 1+ chars other than whitespace and # from the start of a string like preg_match('~^[^#\s]+~', $s, $match), you can just explode your input string  with # and get the 0th item.


text:
Q: Need help understanding product of cycles I need to understand how product of cycles work. The textbook i am referring gives explanation only for simple products and just answer for bigger ones. i would be very thankful if someone can explain me how to work around products like this :
$(1532)(14)(35)$
some relevant link where i can read and understand will also work.
Aman

A: The idea here is to repeatedly evaluate until we get back to where we started. We can start with $1$ and see where that takes us. $(3\:5)$ leaves $1$ alone, then $(1\:4)$ sends $1$ to $4,$ and then $(1\:5\:3\:2)$ leaves $4$ alone. Thus, $(1\:5\:3\:2)(1\:4)(3\:5)$ sends $1$ to $4$.
Next, we evaluate at $4$. $(3\:5)$ leaves $4$ alone, then $(1\:4)$ sends $4$ to $1,$ and then $(1\:5\:3\:2)$ sends $1$ to $5.$ Thus, $(1\:5\:3\:2)(1\:4)(3\:5)$ sends $4$ to $5$.
Next, we evaluate at $5$. $(3\:5)$ sends $5$ to $3$, then $(1\:4)$ leaves $3$ alone, and then $(1\:5\:3\:2)$ sends $3$ to $2.$ Thus, $(1\:5\:3\:2)(1\:4)(3\:5)$ sends $5$ to $2$.
Next, we evaluate at $2$. $(3\:5)$ leaves $2$ alone, as does $(1\:4),$ and then $(1\:5\:3\:2)$ sends $2$ to $1.$ Thus, $(1\:5\:3\:2)(1\:4)(3\:5)$ sends $2$ to $1$, and so we're back where we started.
The only thing left to check is what happens to $3$, and you should be able to see that $3$ is sent to $5,$ then $5$ is left alone, then $5$ is sent to $3,$ and so $(1\:5\:3\:2)(1\:4)(3\:5)$ effectively leaves $3$ alone.
Thus, $$(1\:5\:3\:2)(1\:4)(3\:5)=(1\:4\:5\:2)(3)=(1\:4\:5\:2).$$
More generally, we'll do the same kind of thing until we have all the available numbers put into disjoint cycles.

Added: Babak's post reminds me that some textbooks do a left-to-right composition. My answer above assumes a right-to-left composition, so that $$(1\:3)(2\:3\:5)=(1\:3\:5\:2),$$ for example. If instead, you're using left-to-right composition, so that $$(1\:3)(2\:3\:5)=(1\:5\:2\:3),$$ then we'll take a similar approach to the above, but addressing the cycles in the opposite order. In particular, for example, $(1\:5\:3\:2)$ sends $1$ to $5,$ then $(1\:4)$ leaves $5$ alone, then $(3\:5)$ sends $5$ to $3$. Thus, $(1\:5\:3\:2)(1\:4)(3\:5)$ sends $1$ to $3.$ (And so on.)
You'll need to determine which convention your textbook is using.

A: The notation varies sometimes, but the way I find easiest to think of it is (using your example):
$$\begin{pmatrix}
1 & 2 & 3 & 4 & 5\\
5 & 1 & 2 & 4 & 3
\end{pmatrix}\circ
\begin{pmatrix}
1 & 2 & 3 & 4 & 5 \\
4 & 2 & 3 & 1 & 5 \end{pmatrix}
\circ
\begin{pmatrix}
1 & 2 & 3 & 4 & 5 \\
1 & 2 & 5 & 4 & 3
\end{pmatrix}.$$
The way you read the above is as a composition of functions hitting your permutation, right to left. So, the first permutation moves three to five and five to three, which is abbreviated $(35)$ or $(53)$ (either one). Then you move onto the next permutation. I find it easiest to think in my head (e.g.) "four goes to one and one goes to five, so four goes to five." For further reading and a better explanation, check http://people.math.sfu.ca/~jtmulhol/math302/notes/4-Permutations-CycleForm.pdf .

A: $$\begin{array}{}
I:(1\,5\,3\,2)&II:(1\,4)&III:(3\,5)\\ \hline
1\mapsto 5&1\mapsto 4&1\mapsto 1\\
2\mapsto 1&2\mapsto 2&2\mapsto 2\\
3\mapsto 2&3\mapsto 3&3\mapsto 5\\
4\mapsto 4&4\mapsto 1&4\mapsto 4\\
5\mapsto 3&5\mapsto 5&5\mapsto 3
\end{array}$$
$I\times II$: $(1\,5\,3\,2)(1\,4)$
$$\begin{align*}
&(1\overset{I}\longmapsto 5)(5\overset{II}\longmapsto 5)\implies(1\overset{I\times II}\longmapsto  5)\\
&(2\overset{I}\longmapsto 1)(1\overset{II}\longmapsto 4)\implies(2\overset{I\times II}\longmapsto  4)\\
&(3\overset{I}\longmapsto 2)(2\overset{II}\longmapsto 2)\implies(3\overset{I\times II}\longmapsto  2)\\
&(4\overset{I}\longmapsto 4)(4\overset{II}\longmapsto 1)\implies(4\overset{I\times II}\longmapsto  1)\\
&(5\overset{I}\longmapsto 3)(3\overset{II}\longmapsto 3)\implies(5\overset{I\times II}\longmapsto  3)\\
\end{align*}$$
$(I\times II)\times III$:
$$\begin{align*}
&(1\overset{I\times II}\longmapsto  5)(5\overset{III}\longmapsto  3)\implies(1\longmapsto  3)\\
&(2\overset{I\times II}\longmapsto  4)(4\overset{III}\longmapsto  4)\implies(2\longmapsto  4)\\
&(3\overset{I\times II}\longmapsto  2)(2\overset{III}\longmapsto  2)\implies(3\longmapsto  2)\\
&(4\overset{I\times II}\longmapsto  1)(1\overset{III}\longmapsto  1)\implies(4\longmapsto  1)\\
&(5\overset{I\times II}\longmapsto  3)(3\overset{III}\longmapsto  5)\implies(5\longmapsto  5)\\
\end{align*}$$
So it is: $$1\longrightarrow 3\\2\longrightarrow 4\\3\longrightarrow 2\\4\longrightarrow 1\\5\longrightarrow 5\\.......\\(1,3,2,4)$$

A: Note that different authors define multiplication of permutations differently; it's either left-to-right or right-to-left.  The distinction is whether we define $f \circ g$ as $x \mapsto f(g(x))$ or $x \mapsto g(f(x))$.  Check with your notes/books as to which you should use.
Left-to-right
We can draw the points and where they map to as follows:

Then we just follow the paths to find
\begin{align*}
1 & \mapsto 3 \\
2 & \mapsto 4 \\
3 & \mapsto 2 \\
4 & \mapsto 1 \\
5 & \mapsto 5. \\
\end{align*}
We can convert this to cycle notation $(1324)(5)$, or $(1324)$ for short.
Right-to-left
The drawing now looks like:

Again, we just follow the paths to find
\begin{align*}
1 & \mapsto 4 \\
2 & \mapsto 1 \\
3 & \mapsto 3 \\
4 & \mapsto 5 \\
5 & \mapsto 2. \\
\end{align*}
We can convert this to cycle notation $(1452)(5)$, or $(1452)$ for short.


text:
Q: I can't make my program to wait until GUI has finished gathering requested info (Java) I am quite new to Java and before I end up asking this question I searched and searched SO, but I don't seem to get my head around it.
As you will see I have a class that creates a GUI, asks for some input and stores that input in a returnable String[].
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class InputConsole {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static String[] details = new String[3];
public static JButton btn2013;
public static JButton btn2014;
public static JButton btn2015;
public static JButton btn2016;
public static JButton btnGo;
public static JTextField textField2;
public static JTextField textField4;

public static void addComponentsToPane(Container pane) {
    if (RIGHT_TO_LEFT) {
        pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    }

    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    if (shouldFill) {
        c.fill = GridBagConstraints.HORIZONTAL;
    }

    btn2013 = new JButton("ZMR 2013");
    btn2013.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            details[2] = "2013";
            btn2014.setEnabled(false);
            btn2015.setEnabled(false);
            btn2016.setEnabled(false);
            textField2.requestFocusInWindow();

        }
    });
    if (shouldWeightX) {
        c.weightx = 0.0;
    }
    c.fill = GridBagConstraints.HORIZONTAL;
    c.insets = new Insets(10, 0, 0, 0);
    c.gridx = 0;
    c.gridy = 0;
    pane.add(btn2013, c);

    btn2014 = new JButton("ZMR 2014");
    btn2014.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            details[2] = "2014";
            btn2013.setEnabled(false);
            btn2015.setEnabled(false);
            btn2016.setEnabled(false);
            textField2.requestFocusInWindow();
        }
    });
    c.fill = GridBagConstraints.HORIZONTAL;
    c.insets = new Insets(10, 10, 0, 0);
    c.weightx = 0.0;
    c.gridx = 1;
    c.gridy = 0;
    pane.add(btn2014, c);

    btn2015 = new JButton("ZMR 2015");
    btn2015.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            details[2] = "2015";
            btn2013.setEnabled(false);
            btn2014.setEnabled(false);
            btn2016.setEnabled(false);
            textField2.requestFocusInWindow();
        }
    });
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0.0;
    c.gridx = 2;
    c.gridy = 0;
    pane.add(btn2015, c);

    btn2016 = new JButton("ZMR 2016");
    btn2016.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            details[2] = "2016";
            btn2013.setEnabled(false);
            btn2014.setEnabled(false);
            btn2015.setEnabled(false);
            textField2.requestFocusInWindow();
        }
    });
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0.0;
    c.gridx = 3;
    c.gridy = 0;
    pane.add(btn2016, c);

    JLabel textField1 = new JLabel("What was your Bib number? : ");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 2;
    pane.add(textField1, c);

    textField2 = new JTextField(10);
    textField2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            details[0] = textField2.getText();
            textField4.requestFocusInWindow();

        }

    });

    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 2;
    c.gridy = 2;
    pane.add(textField2, c);

    JLabel textField3 = new JLabel("What is your email address : ");

    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 3;
    c.gridwidth = 2;
    pane.add(textField3, c);

    textField4 = new JTextField(15);
    textField4.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            details[1] = textField4.getText();
            btnGo.setEnabled(true);
            btnGo.requestFocusInWindow();

        }
    });
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 2;
    c.gridy = 3;
    pane.add(textField4, c);

    btnGo = new JButton("Go And Get Me My Diploma!");
    btnGo.setEnabled(false);
    btnGo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            JOptionPane.showMessageDialog(null, details[0] + " " + details[1] + " " + details[2]);
        }
    });
    c.fill = GridBagConstraints.HORIZONTAL;
    c.ipady = 0;
    c.weighty = 1.0;
    c.anchor = GridBagConstraints.PAGE_END;
    c.insets = new Insets(10, 0, 0, 0);
    c.gridx = 0;
    c.gridwidth = 4;
    c.gridy = 4;
    pane.add(btnGo, c);
}

private static void createAndShowGUI() {
    JFrame frame = new JFrame("Zagori Mountain Running Diploma Maker");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    addComponentsToPane(frame.getContentPane());

    frame.pack();
    frame.setSize(500, 250);
    frame.setVisible(true);
}

public String[] inputBib() {

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });

    return details;

}

But when I call this GUI in another class
public class CheckFiles {
InputConsole bibInput = new InputConsole();

String[] detailsInput = bibInput.inputBib();
private static Scanner scanner;

public String bibCorrected()  {

    String yearToCheck = null;
    {

        if (detailsInput[2] == "2016") {
            yearToCheck = "ZMR2016.txt";
        } else if (detailsInput[2] == "2015") {
            yearToCheck = "ZMR2015.txt";
        } else if (detailsInput[2] == "2014") {
            yearToCheck = "ZMR2014.txt";
        } else {
            yearToCheck = "ZMR2013.txt";

in order to obtain that String[], I get a java.lang.NullPointerException. I Know that I get this because the program does not wait for the GUI  to get all the input and files the returnable String[] as null. I think I know that I have to do something with wait() and notify() but I do not seem to understand exactly what.
Thank you in advance for any suggestions. (and very sorry for the long thread)

A: You could add a button on your GUI which will just call the bibCorrected() method. Currently you are showing and then returning so the array is empty and arg 2 is none existent therefor throwing an NPE. This would probably be the easiest way to resolve the issue.
Also, it's better to use String.equals(String) rather than ==. Read this StackOverflow post What is the difference between == vs equals() in Java?


text:
Q: How to reload json data in acitree I would like to know whether there is any possible way to refresh an aciTree instance from a json object received from the server.

*

*Let's assume I have an html input field.

*The user types something and clicks the submit button.

*This input is used to get a new version of the json tree model from the server through an ajax call.

That works fine.  However, when I type again a new value in the input field and submit the aciTree does not reflect the new values.  It still displays the old json object data.
Here is my code.
User Name: <input type="input" id="name"  name="name">
          <input type="submit" value="search" id="call"  >

Please let me know whether there is any way to achieve this.

A: $(_selector_).aciTree(_options_) call will init the tree view just once (using the provided options). Nothing will happen if you call it twice. To be able to init the tree view with other options, you'll need to destroy it first.
In your case, you need just to update the tree view ajax.url option. First unload the tree, then reload it from the new url.
To update one of the aciTree options at runtime, use the option method. Note that you can use the dot notation to reach deep level properties:
api.option('ajax.url', '_your_new_url_');

Then you can call unload/ajaxLoad (as in your example).

A:


text:
Q: How do I write a typeguard for a function that takes an argument that is an intersection of a Partial and object? I am using the Directus API with Typescript. With Typescript, its API calling functions return partial entities (eg. PartialItem<Book>), so I'm diligently checking the existence of required properties before passing the data onward.
However, I'm still getting Typescript type errors which are unrelated to Directus specifically but perhaps with how I'm handling the partial type.
Here's a simplified example with pure Typescript (and on TS Playground):
interface Book {
    id: string;
    title?: string;
    author?: string;
    pages?: number;
}

class Library {
    static books: Book[] = [];
    static addBook(data: Partial<Book> & {id: string}) {
        this.books.push(data);
    }
}

function fetchBooks(): Promise<Partial<Book>[]> {
    return new Promise((resolve)=>{
        setTimeout(()=>{
            resolve([
                {id: "1234",title:"Nineteen Eighty-Four"},
                {id: "2345", title: "The Great Gatsby", author: "F. Scott Fitzgerald"}
            ])
        },1000)
    })
}

function bookLoadingFunction() {
    fetchBooks().then(books=>{
        books.map(b=>{
            if(!b.id){
                // Handle the fact that the API is missing ID
            }else{
                Library.addBook(b); // * COMPILE ERROR HERE *
            }
        })
    })
}

Even after checking, the compiler doesn't appear to be able to infer that b.id is defined. And I get the following error:
Argument of type 'Partial<Book>' is not assignable to parameter of type 'Partial<Book> & { id: string; }'.
  Type 'Partial<Book>' is not assignable to type '{ id: string; }'.
    Types of property 'id' are incompatible.
      Type 'string | undefined' is not assignable to type 'string'.
        Type 'undefined' is not assignable to type 'string'.

Is this a limitation of the compiler, or does there exist an edge case where b.id could indeed still be undefined? And is there a way to keep the compiler happy without losing type safety?
I know the following would make the errors go away, but it's far from ideal:
Library.addBook(b as Partial<Book> & {id: string});

Thanks.

A: You were expecting that by checking the id property of a Partial<Book> object for truthiness, you would get the compiler narrow the object from Partial<Book> to Partial<Book> & {id: string}.  Unfortunately this is not how narrowing works in TypeScript.  See microsoft/TypeScript#16976 for a (longstanding) open feature request to support this sort of thing.
Currently if you check the value of a property like b.id, it will only narrow the type of the property b.id itself, and not the type of the containing object b... well, unless b is of a discriminated union type and id is its discriminant property.  But Partial<Book> is not a union at all, let alone a discriminated one.  Oh well.

Here are the workarounds I can think of.  One is to reassemble your object from the narrowed property and the rest of the object, via something like object spreading:
if (!b.id) { } else {
    const obj = { ...b, id: b.id };
    /* const obj: {
        id: string;
        title?: string | undefined;
        author?: string | undefined;
        pages?: number | undefined;
    } */
    Library.addBook({ ...b, id: b.id }); // okay
}

You can see that obj is seen to be of a type equivalent to Partial<Book> & {id: string} (a.k.a. Book).  And therefore you can call Library.addBook(obj) without error.  So you've given up on narrowing b, and are instead building a new version of b of an already-narrowed type.

If you don't want to create a new object which is essentially equivalent to the old one, you could give up on checking if (!b.id) {} and instead write a user-defined type function that takes b as an input and returns a type predicate saying that b can be narrowed depending on whether the result is true or false.  For example:
function hasId<T extends { id?: any }>(
  x: T
): x is T & Required<Pick<T, "id">> {
    return x.id !== undefined
}

The hasId() function accepts a parameter x which is known to have an id property (or at least an optional one), and returns the type predicate x is T & Required<Pick<T, "id">>.  You can see it in action:
if (!hasId(b)) { } else {
    b // b: Partial<Book> & Required<Pick<Partial<Book>, "id">>
    Library.addBook(b); // okay
}

In the else clause, hasId(b) has returned true, meaning that b has been narrowed to Partial<Book> & Required<Pick<Partial<Book>, "id">>.  That's also equivalent to Book (the type Required<Pick<Partial<Book>, "id">> is ugly, written in terms of the Required<T>, Pick<T, K> and Partial<T> utility types, but if you go through it you'll see it is equivalent to {id: string}).
So here you've decided to tell the compiler how to narrow b, since it doesn't know how to do so itself.

Playground link to code


text:
Q: Broadcast receiver for internet connection does not work I am trying to create an application that tracks internet connection. When internet connectivity status changes, it should make a toast. For this, I am supposed to use Broadcast Receiver. So far, I've written (found) this code (following code only includes parts related to this job)
ConnectivityReceiver mConnectivityReceiver;
IntentFilter mConnectivityIntentFilter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    ....
    mConnectivityIntentFilter = new IntentFilter();
    mConnectivityIntentFilter.addAction(Intent.ACTION_MANAGE_NETWORK_USAGE);

    mConnectivityReceiver = new ConnectivityReceiver();
    ....
}

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mConnectivityReceiver, mConnectivityIntentFilter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mConnectivityReceiver);
}

public class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.d("onreceive", "success");

        ConnectivityManager connMgr =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean isWifiConn = false;
        boolean isMobileConn = false;
        for (Network network : connMgr.getAllNetworks()) {
            NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                isWifiConn |= networkInfo.isConnected();
            }
            if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                isMobileConn |= networkInfo.isConnected();
            }
        }

        if (isMobileConn || isWifiConn) {
            Toast.makeText(getApplicationContext(), "Internet connected", Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(getApplicationContext(), "Internet connection lost, may cause some functions to not work properly", Toast.LENGTH_LONG).show();
        }
    }
}

I have these two permissions in manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

I tried on both emulator (Android 8.0) and device (Android 5.1), my code doesn't work. It doesn't make a toast and it doesn't even create the log.
What am I doing wrong?
Thanks in advance!

A: I'm guessing a bit, but I think you need the intent-filter in your manifest as well (see this answer).

A: Try out this if you just want to do something simple when the connectivity changes, there is a much easier solution.
Create BroadCast Receiver inside your activity :
private BroadcastReceiver networkStateReceiver=new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = manager.getActiveNetworkInfo();
        doSomethingOnNetworkChange(ni);
    }
};

Then in onResume and onPause do the registration:
@Override
public void onResume() {
    super.onResume();
    registerReceiver(networkStateReceiver, new
    IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}

@Override
public void onPause() {
    unregisterReceiver(networkStateReceiver);
    super.onPause();
}


text:
Q: Undefined index in the Slim Framework I have an error in my code that does not identify the desphoto element which is a way to find a photo.

This is the code where the desphoto is called  the code I passed is the error that happens in the cache directory of my view-cache, only my question is because it is like value1 and not just value.
Look at its value in the view-cache: <?php $counter1=-1; if( isset($products) && ( is_array($products) || $products instanceof Traversable ) && sizeof($products) ) foreach( $products as $key1 => $value1 ){ $counter1++; ?>

A: If you have copy-pasted that code, you'll want to fix the syntax and see what's going on there. The closing brace for the foreach is missing.
Additionally, I have changed sizeof to count as sizeof is an alias and may be deprecated in the future, so best to not rely on it.
I've also removed the foreach  as it seems it was doing the same operation. Keep it if you're doing more.
<?php
$counter1=-1;
if(
    isset($products) && (
        is_array($products) ||
        $products instanceof Traversable
    ) &&
    count($products)
)
    $counter1+=count($products);
?>


text:
Q: How to handle empty space on enter key press in flex? I am trying to create a pattern like below, for ,when enter button is pressed twice, the program should terminate, but if user enters something in the line, the program shouldn't  terminate.
[\n\n]  {
if( strcmp(yytext,"?")){
            return 0;
         }
}

I try to check with strcmp for yytex is null space, but what should ı put inside " " ?

A: [\n\n] doesn't match two consecutive line breaks. It's a character class matching a single character that's either a line break or ... a line break. It's equivalent to just \n - duplicate elements in a character class have no effect.
To match two consecutive line breaks, what you want is \n\n without the bracket.
As for strcmp, there is absolutely no reason to check the contents of yytext here. Using the pattern [\n\n], yytext can only ever be equal to "\n" and using \n\n, it can only ever be equal to "\n\n". Either way there's no reason to compare it to anything when you already know what its value is going to be.

A: This is the solution for this situation guys
^\n               yyterminate();


text:
Q: HTML javascript, dragging method in canvas I made a square grid using HTML canvas and I am implementing a drag mechanism, such that the user can draw only rectangles by dragging over the grid.
In the below solution, the user can draw non-rectangle shapes, depending on how the user drags.
An additional question : The grid can be of any size and the drag operation is laggy for large rectangles. Any performance improvement suggestions for that ?

Here are my code of html and javascript

function getSquare(canvas, evt) {

    var rect = canvas.getBoundingClientRect();
    return {
        x: 1 + (evt.clientX - rect.left) - (evt.clientX - rect.left)%10,
        y: 1 + (evt.clientY - rect.top) - (evt.clientY - rect.top)%10
    };
}

function emptySquare(context) {
    context.rect(0, 0, canvas.width, canvas.height);
    context.fillStyle = "#ffffff"
    context.fill();
    context.strokeStyle = "#ddd";
    context.stroke();
}
function range(start, end) {
    var ans = [];
    if (end > start) {
        for (let i = start; i <= end; i += 10) {
            ans.push(i);
        }
    } else {
        emptySquare(context);
        for (let i = start; i >= end; i -= 10) {
            ans.push(i);
    }}
    return ans;
}
function drawBoard(context) {
    for (var x = 0.5; x < 20001; x += 10) {
      context.moveTo(x, 0);
      context.lineTo(x,20000);
    }

    for (var y = 0.5; y < 20001; y += 10) {
      context.moveTo(0, y);
      context.lineTo(20000, y);
    }

    context.strokeStyle = "#ddd";
    context.stroke();
}

function fillSquare(context, x, y){
    context.fillStyle = "#70B7B5";
    context.fillRect(x,y,9,9);
}

var canvas = document.getElementById('myBoard');
var context = canvas.getContext('2d');
var A;
drawBoard(context);
var isDrag= false;
// drawBoard(context);

canvas.addEventListener('mousedown', function(evt) {
    var mousePos = getSquare(canvas, evt);
    isDrag=true;
    fillSquare(context, mousePos.x, mousePos.y);

    previousPos = mousePos;

}, false);

canvas.addEventListener('mousemove', function(evt) {
    if (isDrag) {

        var mousePos = getSquare(canvas, evt);
        var x_dist = range(previousPos.x, mousePos.x);
        var y_dist = range(previousPos.y, mousePos.y);

        for (x in x_dist) {
            for (y in y_dist) {
                fillSquare(context, x_dist[x], y_dist[y]);
                }
            }
    }
}, false);

canvas.addEventListener('mouseup', function(evt) {
    if (isDrag){
        isDrag = false;
    }

}, false);
var canvas = document.getElementById('myBoard');
var context = canvas.getContext('2d');

// drawBoard(context);

var isDrag=false;

canvas.addEventListener('mousedown', function(evt) {
    var mousePos = getSquare(canvas, evt);
    isDrag=true;
    fillSquare(context, mousePos.x, mousePos.y);

    previousPos = mousePos;

}, false);

canvas.addEventListener('mousemove', function(evt) {
    if (isDrag) {

        var mousePos = getSquare(canvas, evt);
        var x_dist = range(previousPos.x, mousePos.x);
        var y_dist = range(previousPos.y, mousePos.y);

        for (x in x_dist) {
            for (y in y_dist) {
                fillSquare(context, x_dist[x], y_dist[y]);
                }
            }
    }
}, false);

canvas.addEventListener('mouseup', function(evt) {
    if (isDrag){
        isDrag = false;
    }

}, false);

  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="./assets/css/style.css">

    <meta charset="utf-8">

      t
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            Home
            About Us
            Mk

          Login

간판 구입

                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

                    <form action="" method="POST" enctype="multipart/form-data">

미리보기

광고 이미지 선택 or 드래그해 옮겨 오세요.

                                <input type="file" name="img_logo" class="dropzone">

                            닉네임/이름
                            <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="닉네임/이름">
                            연락처
                            <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="핸드폰 번호">
                            구매희망 면적
                            <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="ex) 10 x 10 OR 100x100 ">

                    </form>

                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">닫기</button>
                <button type="submit" class="btn btn-dark">적용하기</button>

        <canvas id="myBoard" width="1440" height="1200"></canvas>

© 2021 Nune Project

A: The issue is being seen because range function is not clearing the squares when end > start. Clearing the squares in both the cases resolves the issue.
Here's the snippet that fixes the issue.
function range(start, end) {
  var ans = [];
  emptySquare(context);
  if (end > start) {
    for (let i = start; i <= end; i += 10) {
        ans.push(i);
    }
  } else {
    for (let i = start; i >= end; i -= 10) {
        ans.push(i);
    }
  }
  return ans;
}

The Lag Issue
The callback function attached to mousemove clears and draws squares on every invocation - a time consuming operation. Given that JavaScript is single threaded and this function is called at a very high rate, it might be the cause of the lag.
Debouncing the mousemove callback can help reducing the lag.

A: Another approach to solve the lag issue is to make two canvases: one for the background grid lines and the other one for drawing the green rectangles.

  <canvas id="bg" width="1440" height="1200"></canvas>
  <canvas id="myBoard" width="1440" height="1200"></canvas>

Set the #bg canvas so that #myBoard is in front of it:
#bg {
  position: absolute;
  z-index: -1;
}

Then draw the grid lines on the #bg canvas:
const bg = document.getElementById('bg')
const bgContext = bg.getContext('2d')
drawBoard(bgContext)

Finally, move the emptySquare(context) function into the mousemove event callback and edit it as follows:
function emptySquare(context) {
  context.clearRect(0, 0, canvas.width, canvas.height)
}

So it will only clear the #myBoard canvas while #bg stays the same without needing to redraw it each time.
Example:

const bg = document.getElementById('bg')
const bgContext = bg.getContext('2d')
drawBoard(bgContext)

function getSquare(canvas, evt) {
  var rect = canvas.getBoundingClientRect()
  return {
    x: 1 + (evt.clientX - rect.left) - ((evt.clientX - rect.left) % 10),
    y: 1 + (evt.clientY - rect.top) - ((evt.clientY - rect.top) % 10),
  }
}

function emptySquare(context) {
  context.clearRect(0, 0, canvas.width, canvas.height)
}

function range(start, end) {
  var ans = []
  if (end > start) {
    for (let i = start; i <= end; i += 10) {
      ans.push(i)
    }
  } else {

    for (let i = start; i >= end; i -= 10) {
      ans.push(i)
    }
  }
  return ans
}

function drawBoard(context) {
  for (var x = 0.5; x < 20001; x += 10) {
    context.moveTo(x, 0)
    context.lineTo(x, 20000)
  }

  for (var y = 0.5; y < 20001; y += 10) {
    context.moveTo(0, y)
    context.lineTo(20000, y)
  }

  context.strokeStyle = '#ddd'
  context.stroke()
}

function fillSquare(context, x, y) {
  context.fillStyle = '#70B7B5'
  context.fillRect(x, y, 9, 9)
}

var canvas = document.getElementById('myBoard')
var context = canvas.getContext('2d')
var isDrag = false

canvas.addEventListener('mousedown', function(evt) {
  var mousePos = getSquare(canvas, evt)
  isDrag = true
  fillSquare(context, mousePos.x, mousePos.y)
  previousPos = mousePos
}, false)

canvas.addEventListener('mousemove', function(evt) {
  if (isDrag) {
    var mousePos = getSquare(canvas, evt)
    var x_dist = range(previousPos.x, mousePos.x)
    var y_dist = range(previousPos.y, mousePos.y)

    emptySquare(context)

    for (x in x_dist) {
      for (y in y_dist) {
        fillSquare(context, x_dist[x], y_dist[y])
      }
    }
  }
}, false)

canvas.addEventListener('mouseup', function(evt) {
  if (isDrag) {
    isDrag = false
  }
}, false)
#bg {
  position: absolute;
  z-index: -1;
}

  <canvas id="bg" width="1440" height="1200"></canvas>
  <canvas id="myBoard" width="1440" height="1200"></canvas>


text:
Q: Using Absolute Navigation is not resetting the stack and is forcing modal navigation I have an application with a Loginscreen, and a Mainpage
When I initialize my application I set the Navigation to "NavigationPage/LoginPage". When I log into the application I reset the stack with absolute navigation using the route "/NavigationPage/MainPage". All of my pages have a label bound to the current navigation Uri and when I reset the stack after logging in and navigate to the mainpage my Uri looks like this
/NavigationPage/LoginPage/MainPage?useModalNavigation=true
I've read that if you have duplicate pages on top of one another this can cause the navigation to become modal by default. But I'm resetting the stack and even resetting the NavigationPage. This doesn't cause any immediate issues, but I have found that in deeper parts of my application's navigation stack, some navigation isn't working and this seems to be the cause
Does anyone know why this is happening?
My code
App.xaml.cs
protected override async void OnInitialized()
{
     InitializeComponent();

     await NavigationService.NavigateAsync("NavigationPage/LoginPage");
}

LoginPageViewModel.cs
public ICommand LoginCommand { get; }
public LoginPageViewModel(INavigationService navigationService) : base(navigationService)
{
     LoginCommand = new Command(Login);
     NavUri = NavigationService.GetNavigationUriPath();
}

private async void Login()
{
     await NavigationService.NavigateAsync("/NavigationPage/MainPage");
}

MainPageViewModel.cs
public MainPageViewModel(INavigationService navigationService) : base(navigationService)
{
     Title = "Main Page";
     NavUri = NavigationService.GetNavigationUriPath(); // current URI on the mainpage is /NavigationPage/LoginPage/MainPage?useModalNavigation=true

     NavigateToPageACommand = new Command(NavigateToPageA);
}

I'm using;
Xamarin Forms 4.6.0.726
Prism.Dryloc 7.2.0.1422

A: Appears to be just a temporary value that occurs during OnNavigatingFrom. While the stack is being reset the Navigation appears to be Modal, however it is actually not. Discovered this by adding INavigationAware to my ViewModelBase and viewing the result of GetNavigationUriPath in the OnNavigatedTo and OnNavigatingFrom Methods.


text:
Q: Django - Add block inside an included html In Django, can we add block content in a included html page? Is it feasible?
base.html
{% block title %}

This is title base.html

{% endblock title %}

{% include "head.html" %}

head.html
{% block subtitle %}

This is subtitle head.html

{% endblock subtitle %}

index.html
{% extends 'base.html' %}

{% block title %}

This is title index.html

{% endblock title %}

{% block subtitle %}

This is subtitle index.html

{% endblock subtitle %}

Final result

This is title dashboard.html

This is subtitle head.html

Meaning, that when we are rendering index.html, it will not find the subtitle block on head.html
Thanks!

A: As stated in the documentation:

The include tag should be considered as an implementation of
"render this subtemplate and include the HTML", not as "parse this
subtemplate and include its contents as if it were part of the
parent". This means that there is no shared state between included
templates – each include is a completely independent rendering
process.
Blocks are evaluated before they are included. This means that a
template that includes blocks from another will contain blocks that
have already been evaluated and rendered - not blocks that can be
overridden by, for example, an extending template.

In simpler words as you notice, what you try is not possible.
How to overcome this? Simply bring the blocks to the parent template:
base.html
{% block title %}

This is title base.html

{% endblock title %}
{% block subtitle %}
    {% include "head.html" %}
{% endblock subtitle %}

head.html

This is subtitle head.html

index.html
{% extends 'base.html' %}

{% block title %}

This is title index.html

{% endblock title %}

{% block subtitle %}

This is subtitle index.html

{% endblock subtitle %}


text:
Q: Explicit call to a value constructor after dereferencing an iterator to std::vector >   std::vector<std::uniform_real_distribution<double> > distribution_pos(10);
  for(auto it = distribution_pos.begin(); it != distribution_pos.end(); it++)
  {
     it->std::uniform_real_distribution<double>(0.0,1.0);
  }

I want to essentially declare a vector (size 10) of std::uniform_real_distribution<double> objects. And then I want to loop through this vector and call the value constructor for the object (the 0.0 and 1.0 numbers should change for each pass of the loop, but I omitted that here for succinctness). The above code does not appear to do what I want. Is it possible to make an explicit call to the value constructor after already declaring distribution_pos?

A: No, you can not as std::vector's constructor default constructs values and pushes them, so they cannot be constructed again.
To circumvent this, rather than creating a vector that is that size, reserve(10) (Which doesn't construct anything, just reserves memory) and then you can emplace_back the values, which will construct an object with the given arguments.
std::vector<std::uniform_real_distribution<double> > distribution_pos;
distribution_pos.reserve(10);

for (std::size_t i = 0; i < 10; ++i) {
    distribution_pos.emplace_back(0.0, 1.0);
}

A:
I want to loop through this vector and call the value constructor for
  the object

The object has already been default constructed with (0.0, 1.0) and you can't call the constructor again. You can however assign a new distribution by dereferencing your iterator and assigning to it:
    *it = std::uniform_real_distribution<double>(0.0,1.0);

Or using a range based for loop:
for(auto &dist : distribution_pos) {
    dist = std::uniform_real_distribution<double>(0.0,1.0);
}

If you really would like to keep the original distribution (perhaps to keep its internal state), you can replace its parameter object:
for(auto &dist : distribution_pos) {
    // get the current parameters
    auto params = dist.param();
    // create new and replace the old parameters
    dist.param(
        std::move(
            std::uniform_real_distribution<double>::param_type(
                params.a(), params.b()
            )
        )
    );
}