text:
Q: GCD and mutable objects I have a singleton data manager object that manages the connection to a web service, processes the data and then updates a mutable dictionary with the objects.  All requests for this dictionary are via this singleton instance that I have created.  Now and again I will get conflicts as I am obviously editing a mutable object from many threads and so get the occasional EXC_BAD_ACCESS.
I could implement @synchronized methods or use NSLock but as I am already making extensive use of Grand Central Dispatch I was wondering if there is anything I can do there by forcing them all down one thread synchronously?  I also am not sure if the above methods would work and how they would be implemented.
Example code below.  The exception can occur in the getObjectArray method as I could be adding to it/updating sub object/deleting in the translateToObjectFromDict method.
NSMutableDictionary *staticDictionary;

-(NSArray *)getObjectArray{

    NSArray *returnArray = [[[NSArray alloc]init]autorelease];
    returnArray = [self.staticDictionary allValues];
    return returnArray;
}

-(void)translateToObjectFromDict:(NSDictionary *)sourceDictionary{

    dispatch_group_t taskGroup = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(0,0);

    dispatch_group_async(taskGroup,queue,^(){

    for (id key in sourceDictionary) {
        NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
        for (id key in subDictionary) {

            NSArray *theObjData = [subDictionary objectForKey:key];
            if ([theObjData count] == 12) {

               theObj *temptheObj = [[PINKtheObj alloc] initWith......
                    NSString *unihex = temptheObj.unihex;

                    if ([self.staticDictionary objectForKey:unihex]){
                        PINKtheObj *localtheObj = [self.staticDictionary objectForKey:unihex];
                        if (temptheObj.time > localtheObj.time) {
                            [localtheObj updatetheObjWith.......
                        [temptheObj release];
                    }else{
                        [self.staticDictionary setObject:temptheObj forKey:unihex];
                    }
            }

        }
    }
    });

    dispatch_group_notify(taskGroup, queue, ^{
        NSDictionary *getMainDict = [self.mainDictionary objectForKey:@"theObjs"];

        for (id key in self.staticDictionary) {
            if (![getMainDict objectForKey:key]){
                [self.removeArray addObject:[self.staticDictionary objectForKey:key]];
            }
        }

        [[NSNotificationCenter defaultCenter]postNotificationName:@"updated" object:nil];
    });
    dispatch_release(taskGroup);

}

A: I think you should supply all your calls (objectForKey:, setObject:ForKey:, etc.) to your staticDictionary in your own serial queue. Create it when singleton initializes and use everywhere.
In your header file create ivar.
dispatch_queue_t queueDict;

In .m file just add to init
queueDict = dispatch_queue_create("com.yourid.yoursingleton.queueDict ", NULL);

When you want to access or put data into dictionary just make
dispatch_async(queueDict, ^(){
[staticDict setObject:obj forKey:key]; //example
}

You can use dispatch_sync if you want your task to wait for returned value.
__block id returnValue;
dispatch_sync(queueDict, ^(){
returnValue = [statictDict objectForKey:key]; //example
}
obj = returnValue;

A: Encapsulate each request for access to the dictionary in an NSBlockOperation or NSInvocation object, then add the operation to an NSOperationQueue, setting the maximum number of concurrent operations to 1:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:1];
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"Doing something...");
    }];

    [queue addOperation:operation];

If there is a consistent pattern of access, such as are inherent to implementations employing the Producer-Consumer design pattern, you can create a reusable NSBlockOperation object, segregating each call to access the dictionary in their own execution block:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"Doing something...");
    }];

    //you can add more blocks
    [operation addExecutionBlock:^{
        NSLog(@"Another block");
    }];

    [operation setCompletionBlock:^{
        NSLog(@"Doing something once the operation has finished...");
    }];

    [queue addOperation:operation];

An operation queue provides its own threads in which to run its operations, so there's no need to create your own. Since operation queues use GCD, operations are always executed on a separate thread, their respective designations as asynchronous and synchronous notwithstanding.
This should simplify your code, particularly by eliminating your dispatch queue-related code. What a mess!
Finally, create a global accessor method by adding the dictionary to AppDelegate that:

*

*Enforces a singleton

*Performs initialization only after a method or class references the dictionary for the first time

*Works only on a mutable copy, creating a new, mutable dictionary afterwards to replace the previous one

Here's another option Apple suggests in its developer documentation (I copied this directly from the Concurrency Programming Guide):

Using Dispatch Semaphores to Regulate the Use of Finite Resources If
  the tasks you are submitting to dispatch queues access some finite
  resource, you may want to use a dispatch semaphore to regulate the
  number of tasks simultaneously accessing that resource. A dispatch
  semaphore works like a regular semaphore with one exception. When
  resources are available, it takes less time to acquire a dispatch
  semaphore than it does to acquire a traditional system semaphore. This
  is because Grand Central Dispatch does not call down into the kernel
  for this particular case. The only time it calls down into the kernel is
  when the resource is not available and the system needs to park your
  thread until the semaphore is signaled. The semantics for using a
  dispatch semaphore are as follows:
  1. When you create the semaphore (using the dispatch_semaphore_create function), you can specify a positive integer indicating the number of
  resources available.
  2. In each task, call dispatch_semaphore_waitto wait on the semaphore.
  3. When the wait call returns, acquire the resource and do your work.
  4. When you are done with the resource, release it and signal the semaphore by calling the dispatch_semaphore_signal function. For an
  example of how these steps work, consider the use of file descriptors
  on the system. Each application is given a limited number of file
  descriptors to use. If you have a task that processes large numbers of
  files, you do not want to open so many files at one time that you run
  out of file descriptors. Instead, you can use a semaphore to limit the
  number of file descriptors in use at any one time by your
  file-processing code. The basic pieces of code you would incorporate
  into your tasks is as follows:  // Create the semaphore, specifying
  the initial pool size dispatch_semaphore_t fd_sema =
  dispatch_semaphore_create(getdtablesize() / 2);   // Wait for a free
  file descriptor dispatch_semaphore_wait(fd_sema,
  DISPATCH_TIME_FOREVER); fd = open("/etc/services", O_RDONLY);   //
  Release the file descriptor when done close(fd);
  dispatch_semaphore_signal(fd_sema); When you create the semaphore, you
  specify the number of available resources. This value becomes the
  initial count variable for the semaphore. Each time you wait on the
  semaphore, the dispatch_semaphore_wait function decrements that count
  variable by 1. If the resulting value is negative, the function tells
  the kernel to block your thread. On the other end, the
  dispatch_semaphore_signalfunction increments the count variable by 1
  to indicate that a resource has been freed up. If there are tasks
  blocked and waiting for a resource, one of them is subsequently
  unblocked and allowed to do its work.


text:
Q: Адаптивность на форме Qt Creator Такой вопрос, я добавляю динамически на форму следующие компоненты:
struct sbj_window_data{
    QGroupBox *sbj;
    QLabel *sbj_time,*sbj_locate,*sbj_type,*sbj_name,*sbj_week;
};
QVector<sbj_window_data*> dyn_container;

Я записываю их в структуру, и ее помещаю в вектор. sbj_locate должен быть справа в Group box, и для этого я добавил resizeEvent, который пробегается по вектору, и выставляет нужный Label справа в GroupBox.
void MainWindow::resizeEvent(QResizeEvent*){
for(int i=0;i<dyn_container.size();i++){
    dyn_container[i]->sbj_locate->move(dyn_container[i]->sbj->width()-10-dyn_container[i]->sbj_locate->width(),10);
}

}
Но при этот Event применяется только для тех Label которые расположены в текущей вкладке, при переключении в других вкладках все изменяется только при изменении окна. Поэтому я добавил следующий сигнал, который при переходе на другую вкладку выполняет то же что и resizeEvent();
QObject::connect(my_tab_widget, SIGNAL(currentChanged(int)), this, SLOT(tabSelected()));

void MainWindow::tabSelected(){
for(int i=0;i<dyn_container.size();i++){
    dyn_container[i]->sbj_locate->move(dyn_container[i]->sbj->width()-10-dyn_container[i]->sbj_locate->width(),10);
}

}
Все работает, но терзают сомнения что это не правильно. Подскажите пожалуйста корректен ли данный код, и если нет, то как лучше сделать?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trouble by including a static library in makefile I have some troubles by including a static library in our handwritten makefile.
We want include the lib: STL_lib.a which is in the directory: Library/STM32_Safety_STL/Lib
So I wrote this line into the makefile:
...
LDFLAGS_END += -Wl,--gc-sections -static -Wl,--start-group -lc -lm -lSTL_Lib -Wl,--end-group --specs=nosys.specs
...
LDLIBS := Library/STM32_Safety_STL/Lib
...
$$(BUILD_DIR)/$1.elf : $$(OBJECTS) | $$(BUILD_DIR)
@echo ' '
$$(LD) \
    $$(DEFS) \
    -T $$(LDSCRIPTS) \
    -L $$(LDLIBS) \
    $$(LDFLAGS) \
    $$(LDFLAGS_END) \
    $$(MAP_FILE) \
    -o $$(@) $$(OBJECTS)
...

When I call the makefile, I get this error:

arm-none-eabi-gcc.exe  -DSTM32L4R5xx -DUSE_HAL_DRIVER -DDEBUG -T HAL/CubeMX/STM32L4R5VGTX_FLASH.ld -L Library/STM32_Safety_STL/Lib -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 -Wl,--gc-sections -static -Wl,--start-group -lc -lm -lSTL_Lib -Wl,--end-group --specs=nosys.specs -Wl,-Map="./Develop/Debug/MCU1_Develop.map" -o ./Develop/Debug/MCU1_Develop.elf
c:\st\stm32cubeide_1.8.0\stm32cubeide\plugins\com.st.stm32cube.ide.mcu.externaltools.gnu-tools-for-stm32.9-2020-q2-update.win32_2.0.0.202105311346\tools\arm-none-eabi\bin\ld.exe: cannot find -lSTL_Lib
collect2.exe: error: ld returned 1 exit status

Can anyone give me a hint? :)
Thank you

A: The key part of that error message is:

cannot find -lSTL_Lib

Since you have specified static linking, -lSTL_Lib instructs the linker to search for a file named libSTL_Lib.a in the library search path and link it.  If the library of interest is indeed named as you describe:

We want include the lib: STL_lib.a which is in the directory: Library/STM32_Safety_STL/Lib

... then you cannot designate it to the linker via a standard -l option.  The form of the name is incorrect for that.
There is more than one alternative, but perhaps simplest would be to just give a full path to the library instead: Library/STM32_Safety_STL/Lib/STL_lib.a.  In that case, you might not need the -L Library/STM32_Safety_STL/Lib option.


text:
Q: Possibility of binding multiple PyGame windows Is there any way to bind two windows from seprate processes together using Python/Pygame? By binding I mean in two possible ways:

*

*A large window that contains two smaller windows

*Two separate windows which appear side to side (perhaps using OS environment variables?)

A: You might try running two separate programs. I just ran two of my pygame programs separately, they work fine. Run one using the other, maybe? Or, if that doesn't work, put use two surfaces as screens, and draw one into the other.

A: Interprocess communication is probably the simplest.  The issue though is that SDL is fundamentally not set up for multiple windows.
Probably the best long-term solution is to set up with wxPython, and then use PyGame inside of it.  This will let you have all manner of windows with PyGame renderers.


text:
Q: Is Objective C Apple specific? Is Objective C an Apple language or can you run Objective C on other platforms like linux?

A: Objective-C is not an OS X/iOS specific language, eg. the GCC has its own, non Apple, ObjC runtime that also works on Linux (not sure about LLVM, but I guess they have their own runtime too).
However, the complete library (Cocoa, UIkit, etc) are Apple only. You will have to write your own NSObject and all subclasses if you want to use them (or use the GNUStep library for this).

A: You can run it on Linux using GNUStep and GCC as the compiler. By the way you will not be able to use a full Cocoa environment as a framework. Have a look at this compatibility list of AppKit

A: While it's that the language can be compiled and run on multiple other platforms (as others have said), in practice it's almost exclusively used for Mac OS X and iOS development.

A: Also checkout Cocotron.


text:
Q: Can I disallow an application from making sounds in Windows? I am forced to use Lotus Notes at work. I can disable most of the sounds it makes through it's horrifically bad preferences management, but there are a few sounds that appear to be impossible to disable.
That or they are buried. Due to the fact that I can't find a global "Lotus does not make a peep" option anywhere I think I'm forced to more drastic measures.
Is there a way to tell Windows 7 to not allow an application access to the sound subsystem? Conversely, technically Notes is a java application, so maybe I can force the JVM it uses to send all sounds to the void.
Or do I just have to suffer with the abomination of a mail client?
(Of note, every single 'event' in Lotus is set to not play sounds, so there are some events that play sounds that aren't events. Or something.)

A: I don't know that every application in will show up in that list as in the other answer. If not, create a very short, but silent wave file (you might be able to download one from somewhere too). Try to figure out where the file is located, which is making the sounds you don't like, and replace the unwanted file (rename it .old) with a renamed copy of your silent wave file.
It may take a little hunting, but you should be able to find them. Older programs like this usually have their own wave files in their own install sub-folders.
Of course, make sure it is not just in the Sounds Control Panel applet, where you can just disable it. I put this last since it sounds like you probably did check there.

A: On Windows 7, if you click on the volume icon, there is a link to "Mixer" where you can mute individual applications. It should stop once you mute java.


text:
Q: R;Too slow to overate loops for million vectors I'm managing with a data table. I have 13 * 2598893  data table, and I'm trying to make new column filled with character calculated based on another column.
 So i made a function, and applied it to 'for in' loops, with those millions of rows. And it takes forever! I waited for some minutes, and I could not distinguish it from system down.
I tried it for just 10 rows, and the loops and function works well fastly. But when I extend it to other rows, it takes forever, again.
str(eco)
'data.frame':   2598893 obs. of  13 variables:

made function like this
check<-function(x){
  if(x<=15){
    return(1)
  }
  else{
    return(0)
  }
}

And applied loops like this.
for(x in c(1:nrow(eco))){eco[x,13]<-check(eco[x,4])}

And it continues and continues to work.
How can I shorten this work? Or is this just the limit of R that I should endure?

A: You should probably try to vectorize your operations (NB: for loops can often times be avoided in R). In addition, you could check out the data.table package to further improve efficiency:
library(data.table)

set.seed(1)

## create data.table
eco <- as.data.table(matrix(sample(1:100, 13 * 2598893, replace = TRUE), ncol = 13))

## update column
system.time(
    set(eco, j = 13L, value = 1 * (eco[[4]] <= 15))
)
#>    user  system elapsed
#>   0.018   0.016   0.033

eco
#>          V1 V2  V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13
#>       1: 68 74  55 62 82 51 42 18 16  12  50  73   0
#>       2: 39 97  53 61 21 25 79 71 85  19  54  30   0
#>       3:  1 89  62 42  5 90 33 77 31   1  59  26   0
#>       4: 34 22  27  4 36 74 65 45 46  67  74  34   1
#>       5: 87 57  88  4 42 26  9 13 64  32  16  15   1
#>      ---
#> 2598889: 91 59  78 28 98 98 13 87 88  46  66  85   0
#> 2598890: 82 60  87 60 49 25 10  9 97  78  61  91   0
#> 2598891: 19  2 100 75 66 88 12 46 94  32  69  56   0
#> 2598892: 18 47  22 87 23 79 56 99 13  29  15  46   0
#> 2598893: 47 30   8  8  9 80 49 78 20  43  86  11   1


text:
Q: NodeJS: What's the difference between a Duplex stream and a Transform stream? The Stream docs state that Duplex Streams "are streams that implement both the Readable and Writable interfaces" and Transform Streams "are Duplex streams where the output is in some way computed from the input." Unfortunately, the docs do not describe what Transform streams provide above and beyond Duplex streams.
Are there any differences between the two? When would you use one over the other?

A: If you read the API for stream implementors section of the docs, they state that some possible use cases for Duplex and Transform streams are "Reading and writing" and "Operate on written data, then read the result" respectively.
Simply put the Transform stream lets you implement the _transform method that takes some input and returns the output after some operation has been done on the data, and can be used for things like compressing or hashing, whereas the Duplex stream can be used for things like a TCP socket connection where you just send and receive data.

A: According to the docs:

Duplex - streams that are both Readable and Writable (for example, net.Socket).
Transform - Duplex streams that can modify or transform the data as it is written and read (for example, zlib.createDeflate()).

So to put it simply:

*

*A duplex stream can be read from and written to, but there's not necessarily any connection between the input and output.

*A transform stream can also be read from and written to, but the output will always be the result of a transformation on its input. Transform streams are Duplex streams where the output is in some way related to the input.

A: A Duplex stream can be thought of a readable stream with a writable stream. Both are independent and each have separate internal buffer. The reads and writes events happen independently.

                             Duplex Stream
                          ------------------|
                    Read  <-----               External Source
            You           ------------------|
                    Write ----->               External Sink
                          ------------------|
            You don't get what you write. It is sent to another source.

A Transform stream is a duplex where the read and write takes place in a causal way. The end points of the duplex stream are linked via some transform. Read requires write to have occurred.

                                 Transform Stream
                           --------------|--------------
            You     Write  ---->                   ---->  Read  You
                           --------------|--------------
            You write something, it is transformed, then you read something.

A: The difference is just syntactic sugar. Transform streams are full duplex streams but rather than implementing _write and _read methods, you are asked to implement just the _transform method. You can read more about streams on the excellent substack's streams guide or from Isaacs's readable-stream repo.


text:
Q: REST: query param containing an url How to process query params that will contain values that are urls?
For example if my endpoint is /endpoint/urls/{urls} and the query param value urls will contain a url. How should I tell the server that the value of  {urls} must be escaped and treated as a string instead of a real url ?
As an example :

/endpoint/urls/http://www.google.com

A: First of all, the example provided in your question is not a query parameter.
It's a path parameter.
To send a URL as a query parameter, you must use a key/value pair (key=value) and the value must be URL encoded:
/endpoint?url=http%3A%2F%2Fwww.google.com

To URL encode a value (path or query parameter) in Java, you can use:
String valueUrlEncoded = URLEncoder.encode(value, "UTF-8")


text:
Q: Setting Windows Mobile device system time from computer? I'm trying to sync the system date and time of a device to the desktop it's docked to, I'm working through compact framework (C#).
My goal is to detect when the last time the device was synced to a database on the desktop machine was.
How can I do this?

A: I am not sure what the final question is. If you ask, how to sync the time of the device with the PCs time when the device is dockked, then you can use the free ITSUtils and some registry change on your PC to automate time snycing:
The registry change is
REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnConnect]
"OnConnect"="\"c:\\windows\\system32\\cmd.exe\" /c d:\\OnConnect\\install.bat"

see also here and here and here
If you have access, you can also look at my post at experts-exchange.
Instead of install.bat you can use any bat or cmd file.The itsutils contain a PC app called psynctime. You just need to start psynctime in the bat/cmd file you created and linked in the registry. The device time is then synced to your PC's time. Enure that the bat file can access the itsutil files, either have the itsutils in a dir of your PATH environment or in the bat/cmd's directoty.
As an alternative you have to write a DLL and a activesync remote calling code to sync the time. So it is easier to use the psynctime tool.
Do you know that the device can use the internet using your PC's internet connection? See ActiveSync connection settings and look for "PC is connected to Work/Internet/Automatic". If set to Automatic or Internet your device should be able to access the internet passing thru the ActiveSync connection. Just try Internet Explorer Mobile on the device to test that. If it works for you, you can also use the SNTP service with the code provided by Mitch. But then you also have to add code that detects when the device is connected via ActiveSync.

A: Here's the one I have been using. I make my devices sync up the first time the database object is initiated.
#if PocketPC
[DllImport("coredll.dll")]
#else
[DllImport("kernel32.dll")]
#endif
private static extern bool SetLocalTime([In] ref SYSTEMTIME lpLocalTime);

...and yes, I use the same code for my Windows PCs as for my WinMobile PCs.
This NODATE variable is global to my entire project, and is defined as Jan. 1, 1900. Hopefully, nothing at this company happened on that date in the SQL Server!
Start with a structure:
/// <summary>
/// SYSTEMTIME structure with some useful methods
/// </summary>
public struct SYSTEMTIME {
  public short Year, Month, DayOfWeek, Day, Hour, Minute, Second, Millisecond;
  /// <summary>
  /// Convert form System.DateTime
  /// </summary>
  /// <param name="time">Creates System Time from this variable</param>
  public void FromDateTime(DateTime time) {
    Year = (short)time.Year;
    Month = (short)time.Month;
    DayOfWeek = (short)time.DayOfWeek;
    Day = (short)time.Day;
    Hour = (short)time.Hour;
    Minute = (short)time.Minute;
    Second = (short)time.Second;
    Millisecond = (short)time.Millisecond;
  }
  /// <summary>
  /// Convert to System.DateTime
  /// </summary>
  public DateTime ToDateTime() {
    return new DateTime(Year, Month, Day, Hour, Minute, Second, Millisecond);
  }
  /// <summary>
  /// STATIC: Convert to System.DateTime
  /// </summary>
  public static DateTime ToDateTime(SYSTEMTIME time) {
    return time.ToDateTime();
  }
}

Then just use that structure like I do in this method that makes the call (I sync with our SQL Server).
/// <summary>
/// Synchronize the Time on the SQL Server with the time on the device
/// </summary>
public static int SyncWithSqlTime() { // pass in SQL Time and set time on device
  SYSTEMTIME st = new SYSTEMTIME();
  DateTime sqlTime = Global.NODATE;
  using (SqlCommand cmd = new SqlCommand("SELECT GETDATE() AS CurrentDateTime;", new SqlConnection(DataSettings.DatabaseConnectionString))) {
    try {
      cmd.Connection.Open();
      SqlDataReader r = cmd.ExecuteReader();
      while (r.Read()) {
        if (!r.IsDBNull(0)) {
          sqlTime = (DateTime)r[0];
        }
      }
    } catch (Exception) {
      return -1;
    }
  }
  if (sqlTime != Global.NODATE) {
    st.FromDateTime(sqlTime); // Convert to SYSTEMTIME
    if (SetLocalTime(ref st)) { //Call Win32 API to set time
      return 1;
    }
  }
  return 0;
}

That last if condition at the bottom is where I set the time using SetLocalTime.
Hope this gets you somewhere,
~Joe

A: Why not synchronise both to international standard time using SNTP (Network Time Protocol):
C# SNTP Client
Then you can just check the database last updated time. [I've used the linked-to code on a mobile device]
That code is used like so (called every hour, or whatever refresh interval you require):
   SNTPClient client = new SNTPClient(sntpTimeServerString);
   client.Connect(5000, true);

   // Set system clock to timenow
   DateTime timenow = client.ToTime();

Update (based on OP's comments): Since you have no internet connection, I think you need to use something other than time to determine last sync. For instance, use a last sequence Id to determine if device's local database has changes compared to desktop.

A: Remote API 2 (RAPI2). =>
You lanch two rapi.CreateProcess, one for the date and one for the time.
rapi.CreateProcess("cmd", "/c date " + DateTime.Now.ToString("dd-MM-yyyy"));
rapi.CreateProcess("cmd", "/c time " + DateTime.Now.ToString("HH:mm:ss"));

It will open two windows command prompt to synchronise the mobile with the clock on your PC.


text:
Q: How to make a proper logging in nodejs I Have a service that uses wrapper class for Winston logger to log the HTTP calls, internal failers, and so on to be able to maintain the service on production
the behavior of logging is something like this
function getUser(req, res, next) {
  try {
    logger.info("user::api::getUser", "controller called");
    // do some stuff here, call the service related and return response
  } catch(err) {
     logger.error("user::api::getUser", err);
  }
}

and also this logger is called in all subsequent functions along with the app, such as services, db access layers, controllers, middlewares, and so on
Actually, I am disappointed about calling logger in each function I write which I feel like polluting the code and don't make single responsibility principle also makes the code violates closed to modification principle` since if I updated the logger API for example, then I have to go through all the functions that the logger used inside and update it to the new syntax which is not good
I thought about if I can use event-driven, I mean event emitters to emit events on each failure, call and the handlers of these events will write the appropriate log
for example something like this
function getUser(req, res, next) {
  try {
    eventEmitter("info", "controller called");
    // do some stuff here, call the service related and return response
  } catch(err) {
     eventEmitter.emit("error", err);
  }
}

and here is the listener
eventEmitter.on("error", (err) => {
  logger.error("error", err);
});

I see this syntax hides the implementation of calling the logger into one function instead of calling it in each part of the app, but still, the functions are polluted because I still have to call the event emitter inside them to emit logging event
I don't know if there is an intelligent way to implement logging without calling the logger in each part of the app like this !!
Also, I am wondering how giant companies handle these cases in their applications
I hope someone respond to me and guide me to the right direction


text:
Q: Why is assertEquals(double,double) deprecated in JUnit? I was wondering why assertEquals(double, double) is deprecated.
I used import static org.junit.Assert.assertEquals; and I used JUnit 4.11.
Below is my code:
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class AccountTest {

@Test
public void test() {
    Account checking = new Account(Account.CHECKING);
    checking.deposit(1000.0);
    checking.withdraw(100.0);
    assertEquals(900.0, checking.getBalance());
   }
}

checking.getBalance() returns a double value.
What could be wrong?

A: People explain but don't give samples... So here goes what worked for me:
@Test
public void WhenMakingDepositAccountBalanceIncreases() {
    Account account = new Account();
    account.makeDeposit(10.0);
    assertEquals("Account balance was not correct.", 10.0, account.getBalance(), 0);
}

The 0 in the end;

A: assertEquals(double, double) is deprecated because the 2 doubles may be the same but if they are calculated values, the processor may make them slightly different values.
If you try this, it will fail: assertEquals(.1 + .7, .8). This was tested using an Intel® processor.
Calling the deprecated method will trigger fail("Use assertEquals(expected, actual, delta) to compare floating-point numbers"); to be called.

A: Old question but this hasn't been said yet and might help someone.
You can use com.google.common.math.DoubleMath.fuzzyEquals(double a, double b, double tolerance) which allows you to specify how close the two doubles should be to each other.
I found it very handy for unit tests where I don't want to hardcode test result values with a lot of decimal places.

A: It's deprecated because of the double's precision problems.
If you note, there's another method assertEquals(double expected, double actual, double delta) which allows a delta precision loss.
JavaDoc:

Asserts that two doubles are equal to within a positive delta. If they are not, an AssertionError is thrown. If the expected value is infinity then the delta value is ignored.NaNs are considered equal: assertEquals(Double.NaN, Double.NaN, *) passes
...
delta - the maximum delta between expected and actual for which both numbers are still considered equal.


text:
Q: Not able to get python stdout logs in container to "oc logs" I have an openshift container running a cron job. This cron job runs some python code.
I have set up a logger to stream the logs to stdout and I expect to see these logs when I query "oc logs [pod] -c [container]", but I don't.
This is the defined logger:
import os
import logging.config

synthetic_home = os.environ.get('SYNTHETIC_HOME')
logPath = '{0}/logs/'.format(synthetic_home)
fileName = 'synthetic.log'

synthetic_log_name = os.environ.get('LOG_NAME')
if not synthetic_log_name:
    synthetic_log_name = 'synthetic-onlinevideoservices'

config = {
    'version': 1,
    'disable_existing_loggers': False,
    },

    'formatters': {
        'standard': {
            'format': '%(asctime)s, {0}, SYNTH_TEST, %(levelname)s, FCID=%(fcid)s, *%(test_name)s* %(message)s'.format(synthetic_log_name),
            #            'datefmt': '%Y-%m-%dT%H:%M:%S.%f%z',
        },
    },
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': '{0}/{1}'.format(logPath, fileName),
            'formatter': 'standard'
        },
        'stream': {
                'level': 'INFO',
                'class': 'logging.StreamHandler',
                'formatter': 'standard'
        }
    },
    'loggers': {
        'results': {
            'handlers': ['stream'],
            'level': 'INFO',
            'propagate': True

        }
    }
}

logging.config.dictConfig(config)

I am not sure if the fact that this code runs from a cron job is important or not here.
In any case, I need the INFO logs to be reflected in "oc logs" and they are not.
What am I doing wrong ?

A: Are you using a conda environment? If yes, you need to have these --no-capture-output AND --live-streaming flags in your entry point command.


text:
Q: UWP - Canvas - TextBoxes overlap even though math is correct In a canvas, I layout my controls myself through code. I use SetValue(Canvas.TopProperty),SetValue(Canvas.LeftProperty), Width and Height properties. I give a default height as 24 and 2 textboxes that should be rendered on top of each other seems overlapping. When I set the height to 30, this doesn't happen and textboxes render on top of each other correctly. I was thinking that maybe UWP assumes textbox height to be some minimum value more than 24 and extends it anyway. Does UWP assume a minimum textbox height or what might be happening in my case?

A: Yes, the TextBox has a MinHeight of 32 as defined by the default style via the TextControlThemeMinHeight ThemeResource.
You can easily find that by inspecting the application at runtime with the Live Visual Tree and Live Property Explorer in Visual Studio
*when you set the Height to 30, you don't notice overlapping because of the padding (10,3,6,5) and border thickness (2).


text:
Q: cross-platform method for determining file owner in Python I need to find the owner of files in a script running on Windows, Linux and Mac. os.stat returns the owner id, but on windows I can't use getpwuid to find the actual name of the owner. I need the name as a string.

A: It seems like you won't find a silver bullet (cross platform). For windows you can use the win32 module like shown here
import win32api
import win32con
import win32security

FILENAME = "temp.txt"
open (FILENAME, "w").close ()

print "I am", win32api.GetUserNameEx (win32con.NameSamCompatible)

sd = win32security.GetFileSecurity (FILENAME, win32security.OWNER_SECURITY_INFORMATION)
owner_sid = sd.GetSecurityDescriptorOwner ()
name, domain, type = win32security.LookupAccountSid (None, owner_sid)

print "File owned by %s\\%s" % (domain, name)


text:
Q: Proving That $R$ is an Equivalence Relation: Is This Solution Proof for Transitivity Incorrect? I have the following problem:

The solution proof for transitivity is as follows:

I suspect that this solution is incorrect. Specifically, I think that the very last part is incorrect.
My Solution
Let $((a, b), (c, d)), ((c, d), (e, f)) \in R$.
$\therefore (a, c), (c, e) \in R_1$ and $(b, d), (d, f) \in R_2$. (By the hypothesis.)
$\therefore (a, e) \in R_1$ and $(b, f) \in R_2$. (Since $R_1, R_2$ are equivalence relations.)
$\therefore ((a, b), (e, f)) \in R$ (By the hypothesis.)
$Q.E.D.$
I would greatly appreciate it if people could please take the time to review this and provide feedback. If I have made any errors, then I would appreciate clarification.

A: Your proof of transitivity is flawless. You have made it very clear at every point of the proof.


text:
Q: Numpy seterr doesn't detect overflow According to the documentation (https://numpy.org/doc/stable/reference/generated/numpy.seterr.html), numpy.seterr should be able to detect overflow and other numerical errors, but I don't understand why what I'm doing doesn't work. The following should raise an exception, but it doesn't.
import sys
import numpy as np

def main():
    np.seterr(all='raise')
    x = np.array([1, 2, 3, 4], dtype=np.uint8)
    for _ in range(9):
        print(x)
        x *= 2

if __name__ == '__main__':
    print(f'{sys.version=}')
    print(f'{np.version.full_version=}')
    main()

Outputs
sys.version='3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]'
np.version.full_version='1.19.3'
[1 2 3 4]
[2 4 6 8]
[ 4  8 12 16]
[ 8 16 24 32]
[16 32 48 64]
[ 32  64  96 128]
[ 64 128 192   0]
[128   0 128   0]
[0 0 0 0]

I've tried similar examples with raise, warn, print, as well as datatypes int8, uint8, int16, uint16, ..., uint64 and I can't get this thing to raise an error ever, what am I doing wrong? I'm using Windows 10 if that matters.

A: It's not you. overflow warning/error is detected with scalar objects like np.int8(100), but not arrays of the same dtype. That's usually not useful, but apparently developers consider the time penalty for overflow protection on core array operations to be too large.  It's been discussed in other SO and forums.
seterr can change how overflow is acted on - default is a warning.  But it can't force an error when there's no warning.

A: It is a known issue: it seems that overflows in numpy's operations are treated differently according to the size of the int type.
>>> import numpy as np
>>> np.seterr(all='raise')
{'divide': 'raise', 'over': 'raise', 'under': 'raise', 'invalid': 'raise'}
>>> np.int(320000) * np.int(320000)
102400000000
>>> np.int8(320000) * np.int8(320000)
0
>>> np.int16(320000) * np.int16(320000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FloatingPointError: overflow encountered in short_scalars
>>> np.int32(320000) * np.int32(320000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FloatingPointError: overflow encountered in long_scalars
>>> np.int64(320000) * np.int64(320000)
102400000000


text:
Q: black screen ios simulator , xcode 11.3 on vmware i have installed  xcode 11.3(11C504)on mac os catalina on vmware.
after run the program simulator load and then it is black screen.
it warns "This app could not be installed at this time " and when I do " Earase all content and setting.. " suddenly SpringBoard and MigrationPluginWrapper constantly crash.
this is screen shot of simulator
and my plist :
plist


text:
Q: My server goes down after gitlab pipeline runs port-forwarding command while i try to make requests to my server We are using gitlab-ee and kubernetes cluster on ubuntu 18.04 os. When the pipeline is running the port-forward command line, if a user sends a request to my service while port-forward command is active the port-forward command stops.
When I run the pipeline commands from my terminal manually , I don't get any errors.I think gitlab pipeline is broken.
Example, i am running the pipeline from my terminal manually at the same time i am making requests to my service while the pipeline is running the port-forwarding command the pipeline is working as it's supposed to be but when i try to do this with gitlab pipeline any request to the server while the port-forwaring command is executing the server goes down.
How can i solve this issue?
kind: Service
apiVersion: v1
metadata:
  name: project_name
  namespace: branch_name
  labels:
    app: project_name
spec:
  clusterIP: None
  ports:
    - name: tcp-port_number
      protocol: TCP
      port: port_number
      targetPort: port_number
  selector:
    app: project_name

kubectl port-forward -n xxx service/xxxx 80:80 --address=0.0.0.0

Hope the question is clear.
Thanks in advance.


text:
Q: Selnium element text value where the By object is actually being sought by text() Consider this code, please:
        By byCheckAll = By.XPath("//span[text()='Check all']");
        IWebElement thingy = BrowserWindow.Instance.Driver.FindElement(byCheckAll);

When I am troubleshooting an issue, I observe that the Text property of the thingy element is an empty string:
enter image description here
I am looking at why the element is not interactable, and notice this, so I wonder what element is even being found.
I don't see how seeking an element by text, not receiving an error, and having the text be empty can happen. Please explain. THANKS!
EDIT: It is challenging to identify how much code/information is relevant to a question. So I add this in response to the comments.
The method in question is this:
        public void CheckAll()
    {
        ClickButtonToDrop();
        By byRootDiv = By.XPath("//div[starts-with(@class, 'ui-multiselect-menu')]");
        var webElements = BrowserWindow.Instance.Driver.FindElements(byRootDiv);
        IWebElement rootElement = null;
        foreach (var webElement in webElements)
        {
            if (webElement.Displayed)
            {
                rootElement = webElement;
                BrowserWindow.Instance.HighlightElement(webElement);

            }

        }

        Element clickAllLink = new Element(rootElement, By.ClassName("ui-multiselect-all"));
        //By byCheckAll = By.XPath("//span[text()='Check All']/parent::div[@tag='a']"); // get the span, then the parent link
        By byCheckAll = By.XPath("//span[text()='Check all']"); // get the span, then the parent link
        IWebElement thingy = rootElement.FindElement(byCheckAll);

        //clickAllLink.Highlight();
        //clickAllLink.Click();

    }

rootElement is a div in which the IWebElement thingy lives.
The HTML of the highlighted DIV is

*Check all
*Uncheck allVisit Check-In

The same HTML as displayed in the Chrome developer tools with the highlighted div (highlight method in above code)
enter image description here
No error is thrown up to the point where thingy object is set which is where my breakpoint is which I have set a break point to achieve the information in the watch window screen shot.


text:
Q: Add HMRoom to HMHome is not working properly I have question regarding the HMRoom adding. When I am adding the HMRoom to HMHome it is added but after successful adding I am trying to load the HMHome rooms in a tableview. But it is not returning the rooms immediately. - (void)home:(HMHome *)home didAddRoom:(HMRoom *)room
 method also not getting called even though I set the delegate for HMHome but calling homeManagerDidUpdateHomes method after 30 seconds. Could any one suggest me to solve this issue.

A: You are calling the wrong method to add  Room to Home.
To add room to home you need to call,
- (void)addRoomWithName:(NSString *)roomName completionHandler:(void (^)(HMRoom *room, NSError *error))completion;

You can reload you table to get information of room you have added in completionHandler of addRoomWithName method. Which is called by object of HMHome in which you want to add a room.
The method you are calling,
- (void)home:(HMHome *)home didAddRoom:(HMRoom *)room toZone:(HMZone *)zone

is delegate method that is called when you add room to zone.
and make sure that you have set delegate of home properly.


text:
Q: Trigger on count of items Is there any way I can trigger an event when the number of items exceeds a limit in a collection? I need to periodically clear out test data for a public facing demo (I suppose I could do it on a timer, but it may need to be cleared faster).
I considered using an observeChanges but I feel that would involve a lot of overhead doing the count each time. Would setting up a dep trigger of some kind work? Or is there a sneakier solution?

A: Polling with a timer seems like the obvious solution, but if you want to be more precise you could try something like meteor-collection-hooks and use the before.insert callback.


text:
Q: Is a variable defined with "char *" a pointer or a variable of type char in c? I've been working hard to get more familiar with C this week. I've been reading C Primer Plus (5th Edition)  but I'm still having a bit of trouble with variables and pointers.
Here is my script that I'm using to test:
int main (int argc, char **argv) {

    char *myvariable=NULL;

    myvariable = strdup("apples");
    myvariable = strdup("value updated");

    printf("========== \n\n");
    printf("this is the thing   : %p \n", myvariable);
    printf("this is the thingval: %s \n", myvariable);

    setvariable(&myvariable);

    printf("after function - this is the thing   : %p \n", myvariable);
    printf("after function - this is the thingval: %s \n", myvariable);

    return 0;

}

int setvariable(char **myvariable) {

    *myvariable = strdup("value from function");
    return 1;

}

Output from running it gives me:
this is the thing   : 0x7fee9b4039c0
this is the thingval: value updated
after function - this is the thing   : 0x7fee9b4039d0
after function - this is the thingval: value from function

Questions
Does char *myvariable=NULL; mean that myvariable is a pointer or a variable? This answer says The form char *ptr = "string"; is just backwards compatibility for const char *ptr = "string";

*

*Is that true?

*Am I creating a constant character?

*Aren't those supposed to be immutable? If so why can I update the value?

With the function setvariable(char **myvariable) - is **myvariable a "pointer to a pointer" ?
Or is myvariable actually just a string (nul terminated array of characters) ?
This is some code that I've found (no documentation) so I have a lot of questions about it. The next one is why is myvariable defined this way - and would it not be better to set it up like one of these ways:
char myvariable[] = "apples";
char myvariable[6] = "apples";

I also don't understand why when setvariable is called it appears to be passing in the address of myvariable with & - wouldn't it be better to pass a pointer?
I've tried to do research on this before asking - but after two days progress has been slow and I'd like a little advice.
Clarification for Asking
The reason I'm asking is because form what I've read it looks like if something has a * after it, like char *myvariable then it should be a pointer.
However, I am having trouble creating a char that is not a pointer and assigning the myvariable pointer to point to it.

A:
Does char *myvariable=NULL; mean that myvariable is a pointer or a function?

myvariable is a pointer (ie a variable, since a pointer is a variable).

1) Is that true?

I don't think it is really backwards compatibility. However, a string litteral such as "string" behaves as a constant string.

2) Am I creating a constant character?

Trying to modify the characters of the string "string" is an undefined behavior. There is no const, because the type of an anonymous string is char[]. But programmers often advise to declare it as const, to prevent errors.

3) Aren't those supposed to be immutable? If so why can I update the value?

You can't modifiy *myvariable (as long as it is assigned to a string litteral), but you can modify the pointer myvariable.

With the function setvariable(char **myvariable) - is **myvariable a "pointer to a pointer" ?

Yes, it is.

Or is myvariable actually just a string (nul terminated array of characters) ?

*myvariable is a string and a pointer to char.
By the way, I guess you should read this answer.

A:
Does char *myvariable=NULL; mean that myvariable is a pointer or a variable?

myvariable is a variable of type "pointer to char".  It will be used to store the address of an object of type "char".

This answer says The form char *ptr = "string"; is just backwards compatibility for const char *ptr = "string";

Backwards compatibility from what?
The string literal expression "string" has type "7-element array of char" (6 characters plus 0 terminator).  In C, an expression of type "N-element array of T" will be converted to an expression of type "pointer to T" and it's value will be the address of the first element in the array, except when the array expression is the operand of the sizeof or unary & operator, or is a string literal being used to initialize another array in a declaration.
So when you write
char *ptr = "string";

the expression "string" is not the operand to a sizeof or unary & operator, nor is it being used to initialize an array in a declaration, so its type is converted from "7-element array of char" to "pointer to char", and the pointer value (address of the first element of the array) is copied to ptr.
One issue with C is that attempting to modify the contents of a string literal invokes undefined behavior.  Some platforms put string literals in read-only memory, some don't; some create multiple instances of the literals if multiple instances exist in the code, some only create a single instance on the literal. Therefore trying to modify the literal may work on some platforms, cause an access violation on others, result in unpredictable behavior on others, etc.  The C language standard explicitly leaves the behavior undefined, so that implementations are free to handle the situation any way they see fit.
As a safety measure, most people explicitly declare the pointer to be const char *:
const char *ptr = "string";

that way you cannot modify the string contents through ptr.  Note that C++ is different in the respect that string literals have type "array of const char", so those expressions will be converted to const char * anyway.

The reason I'm asking is because form what I've read it looks like if something has a * after it, like char *myvariable then it should be a pointer.

In C (and C++), declarations are based on the types of expressions; the form of the expression in a declaration matches the form of an expression in the code.
For example, if we have a pointer variable named p that points to an int, and we want to access that integer value, we dereference the pointer with the unary * operator:
x = *p;

The type of the expression *p is int, so the declaration of the variable p is
int *p;

The type of the variable p is "pointer to int".  The int-ness of p is given by the type specifier int; the pointer-ness of p is given by the declarator *p.  Note that the * is bound to the identifier, not the type specifier; even though you can write the declaration as
int* p;

it's interpreted as
int (*p);

A: By writing char *myvariable, int foo, double blah, or void (*funcptr)(void), you are declaring a variable with some type. The type of the variable specifies what is stored in that variable: a pointer, number, or structure.
So, char *myvariable is a variable (some reserved amount of memory) that contains a pointer value.

A: char* myvariable - char* is setting up a pointer to a memory location that holds an object of type char
myvariable is a variable used to reference that location.
To get at the value you have to de-reference using &myvariable
I did C++ over 10 years ago, not C, but I think thats reasonably accurate.

A: char c;  // allocates a variable with space to hold one character
char *p; // allocates a pointer that may point to a character

p = &c;  // sets variable p to point to the storage allocated for c

c = 'a';   // stores character 'a' in the storage allocated for c
*p = 'a';  // has exact same result as previous

char const *mesg = "abcd";
// allocates 5 characters ('a', 'b', 'c', 'd', '\0')
// also allocates a pointer that may point to a character
// also makes the pointer point to the literal string "abc"

char buf5[] = "abcd";
// Allocates 5 characters ('a', 'b', 'c', 'd', '\0')...
// the compiler figures out how many values need to go in the array.
// Variable buf5 is a reference to this array
char x5[] = { 'a', 'b', 'c', 'd', '\0' };
// has exact same result as previous

sizeof(buf5)  // evaluates to the value 5

int i5[5];
sizeof(i5)  // evaluates to: sizeof(int) * 5
sizeof(buf5)  // evaluates to: sizeof(char) * 5
// but sizeof(char) is always 1 (by definition!)

sizeof(p) // evaluates to size of a pointer (probably 4 or 8)
// size of pointer does not change no matter which string it points to

buf5[0] = 'A'; // now s3 holds: "Abcd"
*buf5 = 'A'; // has exact same result as previous

buf5[1] = 'B'; // now s3 holds: "ABcd"
*(buf5 + 1) = 'B'; // has exact same result as previous

You can easily overwrite the characters in the char array buf5 but you cannot increase the size of the storage allocated for it; you can only reuse the existing storage.
When you declare an array, you "own" the storage; C sets it up for you.  When you use a literal string, you might or might not be able to get away with writing to it, and it's best not to try.  The literal might be put somewhere special (like in ROM on an embedded system) and it may not even be possible to write to it, so any program that depends on writing to a literal is needlessly nonportable.
As for the notation...
In C when you are using a pointer, if you put a * in front of it you dereference the pointer.  This lets you examine what the pointer is pointing to, or modify it.
When you are declaring a pointer, in C you declare it using the same syntax, which is kind of tricky.  But here are some examples:
char c;  // c has the type char
char *p;  // when you dereference the pointer p, you get type char
// Assume p contains garbage right now; we have no idea where it might point

c = 'a'; // legal: assigning a char value to a char type
*p = 'a'; // legal just as above

p = &c;  // p now points to the storage for variable c

char **pp; // pp is a pointer to a pointer to char
// If you dereference pp twice you get a char
// If you dereference pp once you get a char *, a pointer to char
// Assume pp contains garbage right now; we have no idea where it might point

pp = &p;  // pp now points to the storage of p (which is a pointer pointing to c)

*p = 'a'; // dereference p to find the char to assign (variable c)
*(*pp) = 'a';  // dereference pp to find p, dereference p in turn to find char to assign
**pp = 'a';  // parentheses not required, same as previous line

In C, functions are always call by value: arguments to the function are copied.  So, to modify something from inside a function, you pass a pointer; the pointer is copied, but then the value of the pointer is used to find the variable you want to modify.
Confusingly, your example function wants to modify a pointer.  Thus, you declare that it takes a char **, and you take the address of the pointer when calling the function.


text:
Q: Is there the way to enum all internal docker interfaces? I need to extract all network interfaces according to container.
Now I just enum all networks:
$ sudo ls -p /sys/class/net | grep -v /

This command line results with:
eth01
lo
docker 0
veth1240b7e
veth1348577
veth2b45970
veth2c40276

And then I can use it in some configuration utilities:
$ foo_init $(sudo ls -p /sys/class/net | grep -v /)

But I cannot enum containers networks. Is there the way to gather info in format like:
veth1240b7e, my_container_1
veth1348577, my_container_2
veth2b45970, my_container_3
veth2c40276, my_container_4

A: You can list the used interfaces with command:
docker network inspect

If you know the network name you can use
docker network inspect <name of the network>

and you will get JSON file where you have container name:
 "Containers": {
            "90e1f3ec71caf82ae776a822222a110a3f175954e5bd4222fd142ac9428": {
                "Name": "container1",
                <snip>


text:
Q: Laravel form action is empty I am trying to debug a form that posts to a action="".
Once the submit button is pressed its validated by a javascript then submitted.
I am unable to figure out where it calculates the Convenience Fee.
I need to figure out a way to track what is going on so I can debug this blank action form.
I have tried edited the blade templates where the data is displayed.
I have checked the controllers.
I do not know where else to go cause there is no way I know of to track what it is doing. The local dev box I have is working correctly but the main site is displaying default values that the dev box isn't. This offsets the total in the page because its adding a Convenience Fee that should be 0. I have checked the files on both the main server and the dev box and they are identical. The page changes and becomes completely different after the submit button is pressed. I hope I have enough details.
--- abc.blade.php file where the data is displayed if the customer has any value greater than 0. The customer is set to 0 in the database ---
 @if($cart_details['convenience_param'] != '$')

0) style="display: block;" @else style="display: none;" @endif>Convenience Fee({{$cart_details['convenience_param']}})${{ helper::twoDecimalPrice($cart_details['convenience_amount']) }}

                @else

0) style="display: block;" @else style="display: none;"  @endif>Convenience Fee${{ helper::twoDecimalPrice($cart_details['convenience_amount']) }}

                @endif

--- page where you submit your order ---
<form autocomplete="on" role="form" id="adminOrder" method="POST" action="" class="row"> ......
</form>

  <button onclick="validateForm()" class="btn btn-primary">Submit</button>

--- Java script at bottom of page that validates all the fields ---
function validateForm()
  {
    var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
    var address = $("#address").val();
    var date = $("#date").val();
    var restaurant_id = $("#restaurant_id").val();
    var customer_id = $("#customer_id").val();
    var time = $("#time").val();
    var zipCode = $("#zip_code").val();

    if(restaurant_id.trim().length == ''){
      notify('error','Please select restaurant');
    }else if(customer_id.trim().length == ''){
      notify('error','Please select customer');
    }else if(zipCode.trim().length == ''){
      notify('error','Please input zip code');
    }else if(!numberRegex.test(zipCode)){
      notify('error','Please input valid zip code');
    }else if(zipCode.trim().length !=5){
      notify('error','zipcode must be 5 chracters');
    }else if(!jQuery.isNumeric(zipCode)){
      notify('error','zipcode must be numeric chracters');
    }else if(date.trim().length == ''){
      notify('error','Please input date');
    }else if(time.trim().length == ''){
      notify('error','Please input time');
    }else{
       $('#adminOrder').submit();
       //alert("ok");
    }
  }

</script>

There are no displayed type errors.
The page should not display any Convenience Fees at all.
It does show them and calculates it into the total.

A: Apologies: I found the problem. The people before me had 2 files that are similar. One of them is being used by my dev box and the other is used by the main web server. :/
I really hate it when people do not follow standards.
The files are what controls the calculations and is where the invisible things are kept.
I am still hoping to understand how the blank action works.


text:
Q: Editor in Visual Studio does not recognize reference to constant with ${} in url in node.js I am following instructions from hubspot in writing a simple script in node.js that calls there API using an API key. The example also makes use of express and axios. I am using VS code.
When I reference the api key saved as a constant, the editor does not recognize it as a reference to the earlier saved constant.
const express = require('express');
const axios = require('axios');

const app = express ();

const API_KEY_TEST_PORTAL = "066e6549-7853-4914-92b0-9ad61966be4c"

app.get('/contacts', async (req, res) => {
    const contacts = 'https://api.hubapi.com/contacts/v1/lists/all/contacts/recent?hapikey=${API_KEY_TEST_PORTAL}';

You can find screenshots of the example and my own code below. The only difference I find between the two is that my '$' sign is larger than the example, not sure what that means. When I copy out the ${API_KEY_TEST_PORTAL} into another section of the script the editor does recognize the connection to the constant const API_KEY_TEST_PORTAL = "066e6549-7853-4914-92b0-9ad61966be4c"
Can anyone let me know what I'm doing wrong?
Screenshot of the instruction
Screenshot of my VS editor

A: The ${something} syntax is known as string interpolation or template literals. You use backticks, not quotation marks, to delimit strings for interpolation.
Use this sort of thing.
   const val = `https://what/ever/recent?hapikey=${API_KEY_TEST_PORTAL}`;


text:
Q: Align long text at the right and bottom of the imageview android I have an activity in my android app in which I want to show complete blog. Blog has 2 things which are image and the description and the latter gets very long at times depending what the user writes. Both image and description are coming from the server. Now I want to design my activity like the attached image and I don't know if this can be done from xml or java.

I tried using RelativeLayout in my activity like below but it does not cover the space below the ImageView.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    tools:context=".PostDetailsActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/postImg"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:src="@drawable/logo" />

        <TextView
            android:layout_toRightOf="@id/postImg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/test" />

    </RelativeLayout>

</ScrollView>

A: In the picture, you are having 2 text boxes. In the layout, you are having only 1. How this could possibly be working? Android views are rectangular. You can't shape them in random ways or shape the text in a random way.
Your title is just wrong. You are saying:
Align long text at the right and bottom of the imageview android
But actually, it should be:
"How to align a text inside a TextView in a random shape."
Just try to figure out new design with 2 TextViews. See what can fit in the first TextView and put the rest of the text in the other TextView. Maybe you can make them look like only one.


text:
Q: Deploying Master Branch Code from Bitbucket on Heroku I currently have a merged, master branch with the code on Bitbucket. My two developers recently pushed two commits and then went off into the sunset, leaving me to deploy their code.

*

*I went to Heroku, and typed $ Heroku Login into the Terminal.

*Then put in my credentials and was approved

*cloned the most recent code into my local machine

*did $ cd  code_name_here

*deployed my changes off the terminal by typing $ git push Heroku master.

I then went to the domain to check the changes but the changes from my developers most recent commits did not show up.
So, I went back to Bitbucket, checked that all the commits were on the master branch, did the deploy again and saw that the all the most recent changes were already pushed.
Does anybody know what could be going on here?


text:
Q: I want to get the latitude and longitude of the plurality of address Google Geocoding API, either would not be able to send plurality of addresses in a single request?
I tried the following code.
GeoApiContext context = getContext();
context.setApiKey("");
context.setEnterpriseCredentials("gme-***", "***");

GeocodingApiRequest req = GeocodingApi.geocode(context, "Tokyo Japan, Osaka Japan");
req.language("ja");
GeocodingResult[] results = req.awaitIgnoreError();
for (GeocodingResult result : results) {
    System.out.println(result.geometry.location.lat);
    System.out.println(result.geometry.location.lng);
}

I want to reduce the request.


text:
Q: How to install Codepro plugin in Eclipse Kepler Now I am using Eclipse Kepler Version: 3.9.1.201308190730, but i don't how to configure "CodePro AnalytiX" plugin in Eclipse Kepler. Is it possible to configure "CodePro AnalytiX"  in my current Eclipse Kepler?
And is "CodePro AnalytiX" plugin the correct tool for testing code perfomance? Otherwise suggest any other tool for code testing.

A: -Open Eclipse Kepler
-Help -> install new software
-enter this URL:
http://dl.google.com/eclipse/inst/codepro/latest/3.6
-Enter

*

*If you found any other good tool for persistance tests, please let me know :)

Enjoy!

A: All the url's specified in this page are no longer valid.
Eclipse version Installation instructions
Direct plugin link
Eclipse 4.6 (Neon)  Plugin for Eclipse 4.6 (Neon)   https://dl.google.com/eclipse/plugin/4.6
Eclipse 4.5 (Mars)  Plugin for Eclipse 4.5 (Mars)   https://dl.google.com/eclipse/plugin/4.5
Eclipse 4.4 (Luna)  Plugin for Eclipse 4.4 (Luna)   https://dl.google.com/eclipse/plugin/4.4
If you are looking for older versions of the plugin, click here.
If you are having trouble installing from the update sites (due to firewall issues, for instance), you can install the Google Plugin for Eclipse by downloading and installing an archive of the update site.

A: Yes Its compatible for eclipse version: Luna Service Release 2 (4.4.2)


text:
Q: Need explanation on a problem involving natural function Consider a positive integer $n$ and the function
$f:\mathbb{N}\to \mathbb{N}$ ($\mathbb N$ includes $0$) by
$$f(x) = \begin{cases}   \frac{x}{2}
 & \text{if } x \text{ is even} \\   \frac{x-1}{2} + 2^{n-1} & \text{if } x \text{ is odd} \end{cases} $$
Determine the set
$$   A = \{ x\in \mathbb{N} \mid \underbrace{\left( f\circ f\circ ....\circ f \right)}_{n\ f\text{'s}}\left( x \right)=x \}.   $$
(Romania NMO 2013)
The solution starts by stating that $f(x)<x, \quad\forall x\ge 2^n-1$. This was easy enough to understand. However, they continue by saying this implies that $A\subset\{0,1,\dots,2^n-1\}$. Why is that?
Please help me understand! Thanks in advance!

A: Note first that the inequality $f(x) < x$ only holds for $x \geq 2^n$ since $f(2^n - 1) = 2^n -1$.
If there is an element $x \in A$ with $x \geq 2^n$, then we can choose such an $x$ minimally, i.e. such that every $y \in A$ with $y < x$ satisfies $y \leq 2^n - 1$. Now we have $f^n(x) = x$ and hence $$f^n(f(x)) = f^{n+1}(x) = f(f^n(x)) = f(x),$$ so $f(x) \in A$ and the minimality of $x$ together with $f(x) < x$ implies $f(x) \leq 2^n - 1$.
Now check that this implies $f^k(f(x)) \leq 2^n-1$ for all $k \in \mathbb{N}$ (as hinted at in Daniel's comment) and in particular $x = f^n(x) = f^{n-1}(f(x)) \leq 2^n-1$, contradicting the initial choice of $x$.

A: Hint:
Letting all divisions be integer and splitting the cases after the low order bits of $x$, we can expand the function iterates for, say, $n=4$, and the pattern becomes obvious.
$$f(x)=\begin{cases}\frac x2&\text{ if } x \text{ is even}\\\frac{x}2+8&\text{ if } x \text{ is odd}\end{cases}$$
$$f(f(x))=\begin{cases}\frac x4&\\\frac{x}4+4\\\frac{x}4+8\\\frac{x}4+12\end{cases}$$
$$f(f(f(x)))=\begin{cases}
\frac x8&\\\frac{x}8+2\\\frac{x}8+4\\\frac{x}8+6\\
\frac x8+8&\\\frac{x}8+10\\\frac{x}8+12\\\frac{x}8+14\end{cases}$$
$$f(f(f(f(x))))=\begin{cases}
\frac x{16}&\\\frac{x}{16}+1\\\frac{x}{16}+2\\\frac{x}{16}+3\\
\frac x{16}+4&\\\frac{x}{16}+5\\\frac{x}{16}+6\\\frac{x}{16}+7\\
\frac x{16}+8&\\\frac{x}{16}+9\\\frac{x}{16}+10\\\frac{x}{16}+11\\
\frac x{16}+12&\\\frac{x}{16}+13\\\frac{x}{16}+14\\\frac{x}{16}+15\end{cases}$$

A: Stating $f(x) < x,\forall x > 2^n-1$ can be seen as the base step for an induction argument.
We can finish by induction proving :
if  $\underbrace{\left( f\circ f\circ ....\circ f \right)}_{k\ f\text{'s}}\left( x \right) <  x,\forall x > 2^n-1$ then $\underbrace{\left( f\circ f\circ ....\circ f \right)}_{k+1\ f\text{'s}}\left( x \right) <x,\forall x > 2^n-1$.
First of all  put  $\underbrace{\left( f\circ f\circ ....\circ f \right)}_{k\ f\text{'s}}\left( x \right) = t_1$ and $\underbrace{\left( f\circ f\circ ....\circ f \right)}_{k+1\ f\text{'s}}\left( x \right) = t_2$ , now:

*

*if $t_1$ is even then $t_2 = \frac{t_1}{2} <  t_1< x$.

*if $t_1$ is odd, then $t_2 = \frac{t_1-1}{2}+2^{n-1}$, then we have to show:$$\frac{t_1-1}{2}+2^{n-1} < x \iff t_1 <x+x-(2^n-1)$$but we know that $t_1<x$ and that $x-(2^n-1)>0$, so $t_1 <x+x-(2^n-1)$ is true.
So clearly $A$ is a subset of $\{1,2,...,2^n-1\}$.


text:
Q: How to POST to Rails with cURL? I need to upload external directory references (json file) to my users data. It's a good opportunity to learn how to create an API and use cURL, but I still meet at least one issue.
I start with a single element, but I plan to pass a json data file at the end of the story. Typical elements to load look like this:

{"name": "Test", "id": "35", "external_id": "X-001"}

I went through the cURL manual and several StackOverflow posts to finally build this API:
Created a dedicated route in routes.rb
match '/API/user_directory', to: "users#set_external_reference", via: :post

Added a method to the users controller
def set_external_reference
  puts "Loaded parameters:"
  puts params
  if target_user = User.find(params[:id])
    target_user.update_attributes(external_directory_id: params[:external_id])
    render json: {"Response": "OK"}, status: 200
  else
    render json: {"Response": "not OK"}, status: 500
  end
end

Workaround Devise authentication requirement and CanCanCan authorisation in the users controller
class UsersController < ApplicationController
# Check for active session
  before_action :authenticate_user! unless ->{:action == 'set_external_reference'}
  load_and_authorize_resource except: :set_external_reference

Workaround CSRF in the application controller
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception unless -> { request.format.json? }

I'd be glad to hear from you if this is a good approach, or if it exposes the web site to security threards.
But the issue raises when I try to run the cURL request:
curl --noproxy localhost -d "{"name": "Test", "id": "35", "external_id": "X-001"}" -H "Accept: application/json" -H "Content-type: application/json" http://localhost/API/user_directory > error.html

The following error is raised when trying to parse request parameters:

ActionDispatch::Http::Parameters::ParseError in UsersController#set_external_reference
767: unexpected token at '{name: Test, id: 35, external_id: X-001}'

At this point, I can't find a clue to this issue. Can you provide some help?
Thanks a lot!

A: I recommend that you avoid the JSON syntax problems and escaping needed for the shell by putting the JSON input into a file.  If the file is named params.json then use -d @params.json to pass it from a file.
As for authentication, I'm not sure this is a good idea either but you might find a session key and pass it in the cookie header.  If you are using database sessions (which is a good idea) then it will be the value in the column for the session in your database.  If not then use dev tools and get your session from the browser.


text:
Q: Capture simultaneous pressed keys with JavaScript I want to execute a function when space and right are pressed simultaneous. I tried to achieve this with the following code, but it does not work.
function onKeyDown( event ) {

    if ( scope.enabled === false ) { return; }
    if ( scope.noKeys === true ) { return; }
    if ( scope.noPan === true ) { return; }

    var needUpdate = false;

    switch ( event.keyCode ) {

        case scope.keys.UP:

            camera.position.z -= 1;
            break;
        case scope.keys.BOTTOM:

            camera.position.z += 1;
            break;
        case scope.keys.LEFT:

            camera.rotation.y += 0.1;
            break;
        case scope.keys.RIGHT:
            camera.rotation.y -= 0.1;
            break;
        case scope.keys.espace:
            camera.position.y += 50;
            if(camera.position.y > 50){
                camera.position.y -= 1;
            }
            break;
         case scope.keys.espace && scope.keys.RIGHT:
             alert("right and space");
            break;
    }


text:
Q: Calculate the densitiy of the random variable $X$
Given is $U \sim R(0,1)$ and $X=g(U) = -\frac{1}{\lambda} \ln(U),
\space \space \lambda > 0$
What's the density of random variable $X$?

$X \sim R(a,b)$ in general mean equal distribution.
Density for eual distribution is defined: $$P(a \leq X \leq b) = \int_{a}^{b} f(x) dx = \frac{1}{b-a} \int_{a}^{b} dx = 1$$
Then in this example, we have $$P(0 \leq X \leq 1) = \int_{0}^{1} g(U) dU = \int_{0}^{1} -\frac{1}{\lambda} \ln(U) \space\space dU = -\frac{1}{\lambda}\int_{0}^{1} \ln(U) \space dU = -\frac{1}{\lambda} \left[U \cdot \ln(U)-U\right]_{0}^{1}= $$
But now you see there will be problem with $\ln(0)$ when I insert intervals for calculate it. No defined calculation..
What is mistake? I don't see it :(

A: Use CDF transformation method.
$$P(X\le x) = P(-\frac{1}{\lambda}.\ln U \le x)$$
$$= P(\ln U \ge -\lambda x)$$
$$= P(U \ge e^{-\lambda x})$$
$$ F_{X}(x) = \int_{e^{-\lambda x}}^{1} dU = 1-e^{-\lambda x}$$
$$ f(x) = \frac{d}{dx} (1-e^{-\lambda x})$$
$$f(x) = \lambda.e^{-\lambda x}$$
Hence X is $exp(\lambda)$.


text:
Q: Blocking wayback machine via .htaccess Found following piece on one of stacks that is supposed to block waybackmachine's crawler.
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (archive.org_bot) [NC]
RewriteRule .* - [R=403,L]

I have also read that "RewriteEngine On" is supposed to be used only once in the file. Original htaccess looks like this
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

and with my edits, it now looks like this
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTP_USER_AGENT} (archive.org_bot) [NC]
RewriteRule .* - [R=403,L]

RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

I decided to test it. Created account on WBM, took a snap shot and it worked. So, apparently, the redirect didn't work. Not sure, what exactly did I do wrong?

A: Add this bad bots block rule (with archive.org bot):
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_USER_AGENT} (360Spider|acapbot|acoonbot|ahrefs|alexibot|archive.org|asterias|attackbot|backdorbot|becomebot|binlar|blackwidow|blekkobot|blexbot|blowfish|bullseye|bunnys|butterfly|careerbot|casper|checkpriv|cheesebot|cherrypick|chinaclaw|choppy|clshttp|cmsworld|copernic|copyrightcheck|cosmos|crescent|cy_cho|datacha|demon|diavol|discobot|dittospyder|dotbot|dotnetdotcom|dumbot|emailcollector|emailsiphon|emailwolf|exabot|extract|eyenetie|feedfinder|flaming|flashget|flicky|foobot|g00g1e|getright|gigabot|go-ahead-got|gozilla|grabnet|grafula|harvest|heritrix|httrack|icarus6j|jetbot|jetcar|jikespider|kmccrew|leechftp|libweb|linkextractor|linkscan|linkwalker|loader|miner|mj12bot|majestic|mechanize|morfeus|moveoverbot|netmechanic|netspider|nicerspro|nikto|ninja|nutch|octopus|pagegrabber|planetwork|postrank|proximic|purebot|pycurl|python|queryn|queryseeker|radian6|radiation|realdownload|rogerbot|scooter|seekerspider|semalt|seznambot|siclab|sindice|sistrix|sitebot|siteexplorer|sitesnagger|skygrid|smartdownload|snoopy|sosospider|spankbot|spbot|sqlmap|stackrambler|stripper|sucker|surftbot|sux0r|suzukacz|suzuran|takeout|teleport|telesoft|true_robots|turingos|turnit|vampire|vikspider|voideye|webleacher|webreaper|webstripper|webvac|webviewer|webwhacker|winhttp|wwwoffle|woxbot|xaldon|xxxyy|yamanalab|yioopbot|youda|zeus|zmeu|zune|zyborg) [NC]
RewriteRule . - [F,L]


text:
Q: deegree service ExtendedCapabilities XML validation error I would like to publish INSPIRE compliant WFS service using deegree 3.14.15. deegree is installed using binaries on Ubuntu 20.04 LTS.
I am unable to setup extended capabilities for the WFS service. After uncommenting the proposed extended capabilities section in the example metadata https://schemas.deegree.org/services/metadata/3.4.0/example.xml file I receive a XML validation error.

Error near line -1, column -1: Premature end of file.

I think that something is wrong with namespaces. I have experimented with different contents of ExtendedCapabilities. Following content returns above-mentioned error
<ExtendedCapabilities protocolVersions="2.0.0">
    <inspire_dls:ExtendedCapabilities xmlns:inspire_dls="http://inspire.ec.europa.eu/schemas/inspire_dls/1.0"/> </ExtendedCapabilities>

However, if I change the inspire_dls namespace to any other value, validation works e.g.
<ExtendedCapabilities protocolVersions="2.0.0">
    <inspire_dls:ExtendedCapabilities xmlns:inspire_dls="http://anyothernamespace.com"/> </ExtendedCapabilities>

How can I deal with the problem?

A: It doesn't work. First of all, INSPIRE application schema https://inspire.ec.europa.eu/schemas/inspire_dls/1.0/inspire_dls.xsd sets the namespace as

xmlns:inspire_dls="http://inspire.ec.europa.eu/schemas/inspire_dls/1.0"

Secondly, even if I change the schema location to https://inspire.ec.europa.eu/schemas/inspire_dls/1.0/ I am unable to save the service metadata config file, I receive an error

Unable to activate resource: Unable to build resource
OWSMetadataProviderProvider:lcv_metadata: Unable to read service
metadata config: null

A: That error may have different root causes. Please try the following:

*

*Check if all deegree configuration files pointing to a INSPIRE schema files do use https as a protocol. Check the issue for more information: https://github.com/deegree/deegree3/issues/1064

*Upgrade to deegree v3.4.16 containing PR https://github.com/deegree/deegree3/pull/1131

*Apply the following environment variable to the runtime environment, the Apache Tomcat instance for example by setting: javax.xml.transform.TransformerFactory=net.sf.saxon.TransformerFactoryImpl. See issue https://github.com/deegree/deegree3/issues/1110 for more information.

*Don't forget to restart Tomcat so that the settings of step 3 are applied.


text:
Q: how to resolve Python regex error "error bad escape \m at position 37", when passing from 3.5.4 to 3.6.8 I have a python piece of code that was working on 3.5.4 but now is broken on 3.6.8.  It looks like related to how regex are managed by python.  Found some thread, but I don't understand how to fix my problem.
Do I need to change the string given to regex r'^\s*#\s*include\s+"%s"' % str(moc_cpp[0])?
Stacktrace :
error: bad escape \m at position 37:
  File "c:\python\python3.6.8\lib\site-packages\SCons\Builder.py", line 353:
    target, source = e(target, source, env)
  File "C:\SVN\3rdParty\devTool\site_scons\site_tools\qt5\__init__.py", line 373:
    cpp, cpp_contents, out_sources)
  File "C:\SVN\3rdParty\devTool\site_scons\site_tools\qt5\__init__.py", line 229:
    if cpp and re.search(inc_moc_cpp, cpp_contents, re.M):
  File "c:\python\python3.6.8\lib\re.py", line 182:
    return _compile(pattern, flags).search(string)
  File "c:\python\python3.6.8\lib\re.py", line 301:
    p = sre_compile.compile(pattern, flags)
  File "c:\python\python3.6.8\lib\sre_compile.py", line 562:
    p = sre_parse.parse(p, flags)
  File "c:\python\python3.6.8\lib\sre_parse.py", line 855:
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
  File "c:\python\python3.6.8\lib\sre_parse.py", line 416:
    not nested and not items))
  File "c:\python\python3.6.8\lib\sre_parse.py", line 502:
    code = _escape(source, this, state)
  File "c:\python\python3.6.8\lib\sre_parse.py", line 401:
    raise source.error("bad escape %s" % escape, len(escape))

Code:
        inc_moc_cpp = _contents_regex(r'^\s*#\s*include\s+"%s"' % str(moc_cpp[0]))
        if cpp and re.search(inc_moc_cpp, cpp_contents, re.M):

def _contents_regex(e):
    # get_contents() of scons nodes returns a binary buffer, so we convert the regexes also to binary here
    # this won't work for specific encodings like UTF-16, but most of the time we will be fine here.
    # note that the regexes used here are always pure ascii, so we don't have an issue here.
    if sys.version_info.major >= 3:
        e = e.encode('ascii')
    return e

A: moc_cpp[0] probably contains an invalid escape sequence. If you intend to match it literally rather than as a regexp, you should escape it before substituting into the regexp.
inc_moc_cpp = _contents_regex(r'^\s*#\s*include\s+"%s"' % re.escape(str(moc_cpp[0])))


text:
Q: Dropdown menu positioning and styling How do I make it so that the hover effects are full width of the dropdown and so that the text changes  colour on hovering on the li not the a.
So it should be a black dropdown menu, when each link is hovered on the background of the li should change to rgba(255,255,255, 0.1) and the text should change to rgba(102,245,66, 0.8) the li and a sections shouldn't overflow the normal dropdown section (I tried overflow: hidden)

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #1c1c1c;
  min-width: 240px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  padding: 12px 16px;
  z-index: 1;
  height: 300px;
  position: absolute;
  right: 0;
  top: 100;
}

ul {
  list-style: none;
  overflow: hidden;
}

li {
  font-size: 1em;
  text-align: center;
  padding-top: .5em;
  height: 75px;
  width: 240px;
  overflow: hidden;
}

a {
  color: #fff;
  text-decoration: none;
  font-size: 2rem;
  font-family: $main-font;
  width: 240px;
}

a:hover {
  color: rgba(102, 245, 66, 0.8);
}

li:hover {
  background: rgba(255, 255, 255, .2);
  color: #8FC3A1;
  width: 240px;
  cursor: pointer;
}

.dropdown:hover .dropdown-content {
  display: block;
}

  Just hover on it

Home

About

Line Up

Contact

A: I think you are looking for this i m not pretty much sure, please do let me know if it fulfills you requirement, the solution is change color of a when we hover li

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #1c1c1c;
  min-width: 240px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  padding: 0;
  z-index: 1;
  height: 300px;
  position: absolute;
  right: 0;
      left: 0;
}

ul {
  list-style: none;
  overflow: hidden;
  margin: 0;
    padding: 0;
}

li {
    font-size: 1em;
    text-align: center;
    margin-bottom: 10px;
}

li:hover {
  background: rgba(255,255,255, 0.1);
  color: #8FC3A1;
  cursor: pointer;
}
li:hover a{
  color: rgba(102,245,66, 0.8)
}

a {
  color: #fff;
  text-decoration: none;
  font-size: 2rem;
  font-family: $main-font;
  width: 240px;
}
.dropdown:hover .dropdown-content {
  display: block;
}

  fa-bar dropdown

Home

About

Line Up

Contact


text:
Q: Finding every "string" on a page and replacing it with another I'm making a Find and Replace chrome extension for on webpages, here's the find and replace code I have so far;
var elements = document.getElementsByTagName("*");
var find = "e";
var replace = "A";

for (var i = 0; i < elements.length; ++i) {
    if (elements[i].childNodes[0] !== undefined && elements[i].childNodes[0].nodeType === 3) {
        for (curText = elements[i].childNodes[0].nodeValue; curText !== curText.replace(find, replace); curText = curText.replace(find, replace)) {
            elements[i].childNodes[0].nodeValue = curText;
        }
    }
}

the only problem is it doesn't replace every "e" in every location. There are e's leftover in links and in places like div and span tags on the inside. I get the feeling I'm not looping through all the elements correctly, I'm not detecting strings correct, and that I'm not replacing the found strings correct. How could I fix this problem?
EDIT: Alright, now, this is the current code. It works for the most part, the only problem is it doesn't work all over the page. You can open the JavaScript console and try it at
http://www.roblox.com/games/?SortFilter=default&TimeFilter=0&GenreFilter=1
The words on the side bar doesn't get changed.
var elements = document.getElementsByTagName("*");
var find = "e";
var replace = "A";

for (var i = 0; i < elements.length; ++i) {
    if (elements[i].childNodes[0] !== undefined && elements[i].childNodes[0].nodeType === 3) {
          elements[i].childNodes[0].nodeValue = elements[i].childNodes[0].nodeValue.replace(new RegExp(find, "g"), replace)
    }
}

EDIT: Okay, new code now! undefined appears in the console, and nothing gets changed, I found this on a google search, it was from a stack overflow question. Find all text nodes in HTML page
Code:
var find = "e";
var replace = "A";

function textNodesUnder(el){
  var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
  while(n=walk.nextNode()) a.push(n);
  return a;
}

var nodes = textNodesUnder(document.body);
for (var i = 0; i < elements.length; ++i) {
    if (nodes[i].childNodes[0] !== undefined && elements[i].childNodes[0].nodeType === 3) {
          nodes[i].childNodes[0].nodeValue = nodes[i].childNodes[0].nodeValue.replace(new RegExp(find, "g"), replace)
    }
}

I have yet to test but it seems as I made a big mistake of leaving my childNodes precious code in the new one, without it, it should work.

A: String.replace replaces only the first instance. Try this:
  curText.replace(new RegExp(find, "g"), replace)

This is the regex version with "g" meaning global (all occurrance) replacement.


text:
Q: Assigning Datasource to a region I was wondering if there is an existing control that I could use to achieve what I am trying.
Basically, I have a html table that I display my header information.
It looks something like this:

        Job ID	10
        Client	Tom

        Comments	Comments are here

I am wondering if there is an existing control that I can use as a container.  Then I can assign the datasource to that control
and leverage the field values as such.
<asp:Somecontrol runat="server" ID="someid">

        Job ID	<%# Eval("Id") %>
        Client	<%# Eval("Client.Name") %>

        Comments	<%# Eval("Comments") %>

</asp:Somecontrol>

private void BindHeader()
{
 SomeObjectType data = DAL.SomeMethod();
 someid.Datasource = data;
 someid.DataBind();
}

Is there anything out there to do this?  I want to be able to control the layout of the fields within the container.
Thanks.

A: Actually what i was after was the FormView control.
I had never used this control previously, but this is the exact control for what i wanted to do.
It allows to to mark a region, assign a datasource and bind items as desired.
   <asp:FormView ID="FormView1" runat="server" DataSourceID="ObjectDataSource2" Visible="false">
                    <ItemTemplate>

                                ClientId
                                <asp:Label ID="ClientId" runat="server" Text='<%# Eval("ClientId") %>' />

                                ClientCode
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("ClientCode") %>' />

                                Name
                                <asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("Name") %>' />

                                BillingContactName
                                <asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("BillingContactName") %>' />

Thanks AI W for your input.  Repeater is also suitable but for binding "a" record, FormView is ideal i think.  Thanks.

A: Use the GridView control. You can attach CSS classes to many properties in Design mode for controlling the layout.

A: for asp.net 2.0
<asp:Repeater runat="server" id="someid">
        <ItemTemplate>

            Job ID	<%# Eval("Id") %>
            Client	<%# Eval("Client.Name") %>

            Comments	<%# Eval("Comments") %>

        </ItemTemplate>
</asp:Repeater>

you can use the  control in asp.net 3.5, but i won't attempt the syntax off the cuff since I don't get to use 3.5 on a daily basis.


text:
Q: Date range betwen now and end of the day and next day and end of the next day I'm trying to make a DatePicker with a choice between today and tomorrow. Two buttons to switch Date Range.
How to make today range? i. e. Now -> End of the day
How to make tomorrow range? i. e. Start of the next day -> End of the next day
what i've tried, but it's not correct
 var todayRange: ClosedRange<Date> {
    let calendar = Calendar.current
    var endComponents = DateComponents()
    endComponents.day = 1

    let endDate = calendar.date(byAdding: endComponents, to: Date.now)!
    return Date.now ... endDate
}

var tommorowRange: ClosedRange<Date> {
    let calendar = Calendar.current
    var startComponents = DateComponents()
    startComponents.day = 2
    var endComponents = DateComponents()
    endComponents.day = 1

    let startDate = calendar.date(byAdding: startComponents, to: Date.now)!
    let endDate = calendar.date(byAdding: endComponents, to: startDate)!
    return startDate ... endDate
}

A: You're close.
I would suggest:

*

*Get the start of day for today

*Add 1 day

*Subtract 0.001 seconds.

That will give you the end of today.
Here is some sample code.
let today = Date.now
let startOfToday = Calendar.current.startOfDay(for: today)
let oneDay = DateComponents(day: 1)
guard let tomorrow = Calendar.current.date(byAdding: oneDay, to: startOfToday) else { fatalError() }

let endOfToday = tomorrow.advanced(by: -0.001)
let endOfTodayString = DateFormatter.localizedString(from: endOfToday, dateStyle: .medium, timeStyle: .medium)
print("End of today = " + endOfTodayString)

guard let endOfTomorrow = Calendar.current.date(byAdding: oneDay, to: endOfToday) else { fatalError() }
let endOfTomorrowString = DateFormatter.localizedString(from: endOfToday, dateStyle: .medium, timeStyle: .medium)
print("End of tomorrow = " + endOfTomorrowString)

In my locale (US), on October 7th, that generates:

End of today = Oct 7, 2022 at 11:59:59 PM
End of tomorrow = Oct 7, 2022 at 11:59:59 PM


text:
Q: Call functino/sub in Microsoft Excel Objects -> This Workbook VBE hierarchy I had no luck finding a way to call a function which is saved in the ThisWorkbook component of the VBE tree. I tried
Dim vbComponentName As String
vbComponentName = "ThisWorkbook"
Dim wb As Workbook
Dim vbcomp As VBComponent
Set wb = ThisWorkbook
For Each vbcomp In wb.VBProject.VBComponents
    If vbcomp.Name = vbComponentName Then
        Debug.Print "command: " & wb.Name & "!" & vbcomp.Name & ".Open"
        Application.Run (wb.Name & "!" & vbcomp.Name & ".Open")
    End If
Next

which prints:
Long Name File_v.18.xlsm!ThisWorkbook.Open

But it does not work. It compiles but gives me an error:
Cannot run the macro "XYX".
The macro may not be available in this workbook or all macros may be disable.

Any hints will be appreciated!

A: It seems that your problem is with the file's name having spaces, that's why you tried to put those parentheses. I did a similar test and it worked but instead of using parenthese I did it this way:
   Application.Run "'" & wb.name & "'" & "!" & vbcomp.name & ".mySub"


text:
Q: custom post types category break I've created a new custom post type and displayed all those posts on an archive page. Everything is working fine till now. But when I try to add a new category to the built in posts, the archive custom post type page breaks and I get a 404 error. Does anybody got this problem until now? What am I doing wrong or what can be wrong here?
This is all the code:
function my_custom_post_people() {
$labels = array(
    'name'               => _x( 'Our People', 'post type general name' ),
    'singular_name'      => _x( 'Lawyer', 'post type singular name' ),
    'add_new'            => _x( 'Add New', 'our-people' ),
    'add_new_item'       => __( 'Add New Lawyer' ),
    'edit_item'          => __( 'Edit Lawyer' ),
    'new_item'           => __( 'New Lawyer' ),
    'all_items'          => __( 'All Lawyers' ),
    'view_item'          => __( 'View Lawyer' ),
    'search_items'       => __( 'Search Lawyer' ),
    'not_found'          => __( 'No lawyer found' ),
    'not_found_in_trash' => __( 'No lawyer found in the Trash' ),
    'parent_item_colon'  => '',
    'menu_name'          => 'Our Lawyers'
);

$args = array(
    'labels'        => $labels,
    'description'   => 'Holds our lawyers and lawyer specific data',
    'public'        => true,
    'menu_position' => 5,
    'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments','custom-fields', 'page-attributes' ),
    'has_archive'   => true,
    'hierarchical' => false,
    'taxonomies'   => array('people_category', 'post_tag')
);
register_post_type( 'our-people', $args );

}
add_action( 'init', 'my_custom_post_people' );
function my_taxonomies_people() {
$labels = array(
    'name'              => _x( 'Lawyer Categories', 'taxonomy general name' ),
    'singular_name'     => _x( 'Lawyer Category', 'taxonomy singular name' ),
    'search_items'      => __( 'Search Lawyer Categories' ),
    'all_items'         => __( 'All Lawyer Categories' ),
    'parent_item'       => __( 'Parent Lawyer Category' ),
    'parent_item_colon' => __( 'Parent Lawyer Category:' ),
    'edit_item'         => __( 'Edit Lawyer Category' ),
    'update_item'       => __( 'Update Lawyer Category' ),
    'add_new_item'      => __( 'Add New Lawyer Category' ),
    'new_item_name'     => __( 'New Lawyer Category' ),
    'menu_name'         => __( 'Lawyer Categories' ),
);

$args = array(
    'labels' => $labels,
    'hierarchical' => true,
);

register_taxonomy( 'people_category', 'our-people', $args );

}
add_action( 'init', 'my_taxonomies_people', 0 );
Thanks


text:
Q: Probot : Octokit baseUrl overriding Am trying to create a new GitHub(probot) application by going through documentation as mentioned here https://probot.github.io/docs/development/ .
I can get the events from the repository come across but have issues performing any operations with the Github Api client in the context(https://probot.github.io/api/latest/Context.html). From the console i see the default @octokit client is pointing to http://api.github.com instead of the enterprise URL in my case. Is there anything extra that needs to be done to change this URL.
I feel hesitant to create a new client with the correct URL in the robot.on method as we should use the authenticated client i.e available on the context. Am i missing anything here?
22:01:15.370Z DEBUG github: GitHub request: GET /app/installations - 404 Not Found
  params: {
    "per_page": 100,
    "baseUrl": "https://api.github.com",
    "request": {
      "timeout": 0
    }
  }
22:01:15.371Z ERROR probot: {"message":"Integration not found","documentation_url":"https://developer.github.com/v3"}

A: After reading a bit more of documentation (https://probot.github.io/docs/github-api/#github-enterprise) - this could be achieved by setting the property GHE_HOST

A: I had a similar issue while using an enterprise GitHub account and was able to resolve it by setting GHE_HOST. See below link for more details:
GitHub ERROR probot: Integration not found, documentation_url

A: Setting the below property in the .env file of my probot resolved the issue.
GHE_HOST=<<my GitHub enterprise url>>


text:
Q: android studio set proxy I set the proxy like the picture[it seems connection successfully][2]But I cannot update or download SDK
please tell me why,thanks

A: Even though you have set the proxy, sometimes SDK sites are not accessible from with in an organisation, try connecting to the open Internet (outside your organisation network/intranet) and then try updating your SDK.


text:
Q: Best and efficient way to extract a First word from string without space when only a "GOOD" string is available in string? What is the best and efficient way to extract a First word from string without space when only a "GOOD" string is available in std::string
Example
std::string temp = "  THIS IS MY STACK OVER FLOW SECOND QUESTION IS IT GOOD"
Output:THIS
My below logic fails when only "GOOD GOOD GOOD GOOD" is available
#define SerachGOOD "GOOD"
#define SerachBAD "BAD "
#define firstpos 0
using namespace std;
void   removeSpaces(std::string & input)
{
        input.erase(std::remove(input.begin(),input.end(),' '),input.end());
        cout<<input<<endl;
}

void GetFirstiWord_IF_GOOD(std::string temp)
{
        if (temp.find(SerachGOOD)  != std::string::npos)
        {
                std::string FirstWord = temp.substr(firstpos, temp.find(SerachGOOD));

                removeSpaces(FirstWord);

                cout<<FirstWord<<endl;
        }
}

A: Your code is not trying to extract the first word at all.  It is simply removing all spaces from the input and then returning the remaining input as-is.
Thus, this input:
" THIS IS MY STACK OVER FLOW SECOND QUESTION IS IT GOOD"

Would output this:
"THISISMYSTACKOVERFLOWSECONDQUESTIONISITGOOD"

Which is not what you want.
Try something more like this instead:
#include <iostream>
#include <string>

#define SearchGOOD "GOOD"

void GetFirstWord_IF_GOOD(const std::string &temp)
{
    if (temp.find(SearchGOOD) != std::string::npos)
    {
        std::string::size_type start_pos = temp.find_first_not_of(" \t");

        std::string::size_type end_pos = temp.find_first_of(" \t", start_pos + 1);
        if (end_pos == std::string::npos)
            end_pos = temp.size();

        std::string FirstWord = temp.substr(start_pos, end_pos - start_pos);

        std::cout << FirstWord << std::endl;
    }
}

Or simpler, just let the STL do the parsing for you:
#include <iostream>
#include <string>
#include <sstream>

#define SearchGOOD "GOOD"

void GetFirstWord_IF_GOOD(const std::string &temp)
{
    if (temp.find(SearchGOOD) != std::string::npos)
    {
        std::string FirstWord;

        std::istringstream iss(temp);
        iss >> FirstWord;

        std::cout << FirstWord << std::endl;
    }
}

A: Use a std::stringstream to read the first word from the string.
std::string GetFirstiWord_IF_GOOD(std::string temp)
{
    std::string FirstWord;

    if (temp.find(SerachGOOD)  != std::string::npos)
    {
        std::stringstream ss(temp);
        ss >> FirstWord;
    }
    return FirstWord;
}

DEMO

A: I noticed a slight anomaly with your first string in that you have a leading space, that will throw off a simple parse (and in the case of your second example would appear to work correctly, but on a different string would have a completely different outcome).
e.g.: "THIS IS MY STACK OVER FLOW SECOND QUESTION IS IT GOOD"
vs: " THIS IS MY STACK OVER FLOW SECOND QUESTION IS IT GOOD"
To get around this issue, adding in an initial offset to the first word, then simply take everything up to the first space.  So, find, position, and split.
void GetFirstiWord_IF_GOOD(std::string temp)
{
    while (isspace(temp[0])) {
        temp.erase(0,1);
    }
    if (temp.find(SearchGOOD) != std::string::npos)
    {
        temp = temp.substr(0, temp.find_first_of(' '));
        cout << temp << endl;
    }
}

I think your remove string function is causing your false success in the first string, but I am having troubles running your code on my system.  If you drop the code above into your existing code it should work as you are expecting.