text:
Q: How to sort this specific string array by using the following set of rules(?): Yes, I'm a newbie and my uncle has challenged me to use the function:
void sortStrings(char str[], const char* delim){...}

to sort the given char array str in a way that every char from delim that shows up in str will separate a group of chars in str thus making them the words you need to sort by hex value. In the process I also need to replace those word separating chars from delim with ';'.
The rules are: I may only use the library <stdio.h> and I can't use malloc/realloc.
Apparently this should be done with an O notation of n^2 (n being the amount of words in str, not chars)
and here's an example of an input and output:
input:
char str[] = "aaa*test,hello.world*abcd.zzz";
sortDelim(str, ",.*")
output: str is now: "aaa;abcd;hello;test;world;zzz"
Well, I've managed it now eventually, the bubble sort thing kinda helped so tyvm for that :)
note: I'll leave this thread here in case anyone wants to take this challenge on himself? It ain't easy I promise :P If you think I should delete it or add the finished code then just ask(Please don't deduct my rep even more ><)

A: You are off to a good start.  After your second for loop you have

*

*replaced all delimiters with semicolon

*you know how many words there are, size

*you know how many letters each word has, letters
One observation is that you have allocated letters to be 1000 entries.  That seems like enough, but is it really?  How do you know how many words there are in str?  You don't.  And you can't use malloc to allocate dynamically, so perhaps you need to look for an algorithm that doesn't require that lookup table?  You need an algorithm that works in place
http://en.wikipedia.org/wiki/In-place_algorithm
What's next?  You need to sort the words.  There are many sorting algorithms.  You want something simple, and are allowed complexity O(n^2).  Here's a list of sorting algorithms:
http://en.wikipedia.org/wiki/Sorting_algorithm
Notice that in the table, under 'other notes' it tells you that some algorithms are "Tiny code size", that sounds good.  Sort the table first by 'other notes' then by 'Average' complexity (click on the triangle in the column header).  You now have two algorithms that use a method 'exchanging' (that means in place), with Tiny code size and average complexity O(n^2), these wikipedia links explain how they work, and include pseudocode to get you started:

*

*Bubble sort

*Gnome sort
Take your pick and try your hand at it.
Hint: you probably want a subroutine that exchanges (swaps) two consecutive words if the first word compares greater than the second word.  This can be done in place.
Suppose you have
abcd;aaa

The first word is greater than the second word, you need to detect that, and swap the words so you end up with
aaa;abcd

Here's a diagram that will give you the general idea.


text:
Q: Simultaneously run POST in Python I am trying to upload 100,000 data points to a web service backend. If I run it one at a time, it will take ~12 hours. They support 20 API calls simultaneously. How can I run this POST concurrently so I can speed up the import?
def AddPushTokens():

 import requests
 import csv
 import json

 count=0
 tokenList=[]

 apikey="12345"
 restkey="12345"
 URL="https://api.web.com/1/install/"
 headers={'content-type': 'application/json','Application-Id': apikey,'REST-API-Key':restkey}

 with open('/Users/name/Desktop/push-new.csv','rU') as csvfile:
      deviceTokens=csv.reader(csvfile, delimiter=',')

      for token in deviceTokens:

       deviceToken=token[0].replace("/","")
       deviceType="ios"
       pushToken="pushtoken_"+deviceToken
       payload={"deviceType": deviceType,"deviceToken":deviceToken,"channels":["",pushToken]}
       r = requests.post(URL, data=json.dumps(payload), headers=headers)

       count=count+1
       print "Count: " + str(count)
       print r.content

Edit: I am trying to use concurrent.futures. Where I am confused is how do I set this up so it pulls the token from the CSV and passes it to load_url? Also, I want to make sure that it goes through the first 20 runs the requests, then picks up at 21 and runs the next set of 20.
import concurrent.futures
import requests

URLS = ['https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/',
     'https://api.web.com/1/installations/']

apikey="12345"
restkey="12345"
URL="https://api.web.com/1/installations/"
headers={'content-type': 'application/json','X-web-Application-Id': apikey,'X-web-REST-API-Key':restkey}

     with open('/Users/name/Desktop/push-new.csv','rU') as csvfile:
     deviceTokens=csv.reader(csvfile, delimiter=',')

     for token in deviceTokens:

          deviceToken=token[0].replace("/","")
          deviceType="ios"
          pushToken="pushtoken_"+deviceToken
          payload={"deviceType": deviceType,"deviceToken":deviceToken,"channels":["",pushToken]}
          r = requests.post(URL, data=json.dumps(payload), headers=headers)

# Retrieve a single page and report the url and contents
def load_url(token):

     URL='https://api.web.com/1/installations/'

     deviceToken=token[0].replace("/","")
     deviceType="ios"
     pushToken="pushtoken_"+deviceToken
     payload={"deviceType": deviceType,"deviceToken":deviceToken,"channels":["",pushToken]}
     r = requests.post(URL, data=json.dumps(payload), headers=headers)

     count=count+1
     print "Count: " + str(count)
     print r.content

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

Edit: Updated based on Comments Below
import concurrent.futures
import requests
import csv
import json

apikey="ldy0eSCqPz9PsyOLAt35M2b0XrfDZT1NBW69Z7Bw"
restkey="587XASjEYdQwH2UHruA1yeZfT0oX7uAUJ8kWTmE3"
URL="https://api.parse.com/1/installations/"
headers={'content-type': 'application/json','X-Parse-Application-Id': apikey,'X-Parse-REST-API-Key':restkey}

with open('/Users/jgurwin/Desktop/push/push-new.csv','rU') as csvfile:
     deviceTokens=csv.reader(csvfile, delimiter=',')

     for device in deviceTokens:

        token=device[0].replace("/","")

        # Retrieve a single page and report the url and contents

        def load_url(token):

          count=0
          deviceType="ios"
          pushToken="pushtoken_"+token
          payload={"deviceType": deviceType,"deviceToken":token,"channels":["",pushToken]}
          r = requests.post(URL, data=json.dumps(payload), headers=headers)

          count=count+1
          print "Count: " + str(count)
          print r.content

        # We can use a with statement to ensure threads are cleaned up promptly
          with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
              # Start the load operations and mark each future with its URL
              future_to_token = {executor.submit(load_url, token, 60): token for token in deviceTokens}
              for future in concurrent.futures.as_completed(future_to_url):
                  url = future_to_url[future]
                  try:
                      data = future.result()
                  except Exception as exc:
                      print('%r generated an exception: %s' % (url, exc))
                  else:
                      print('%r page is %d bytes' % (url, len(data)))

A: The easy way to do this is with threads. The nearly-as-easy way is with gevent or a similar library (and grequests even ties gevent and requests together so you don't have to figure out how to do so). The hard way is building an event loop (or, better, using something like Twisted or Tulip) and multiplexing the requests yourself.
Let's do it the easy way.
You don't want to run 100000 threads at once. Besides the fact that it would take hundreds of GB of stack space, and your CPU would spend more time context-switching than running actual code, the service only supports 20 connections at once. So, you want 20 threads.
So, how do you run 100000 tasks on 20 threads? With a thread pool executor (or a bare thread pool).
The concurrent.futures docs have an example which is almost identical to what you want to do, except doing GETs instead of POSTs and using urllib instead of requests. Just change the load_url function to something like this:
def load_url(token):
    deviceToken=token[0].replace("/","")
    # … your original code here …
    r = requests.post(URL, data=json.dumps(payload), headers=headers)
    return r.content

… and the example will work as-is.
Since you're using Python 2.x, you don't have the concurrent.futures module in the stdlib; you'll need the backport, futures.

In Python (at least CPython), only one thread at a time can do any CPU work. If your tasks spend a lot more time downloading over the network (I/O work) than building requests and parsing responses (CPU work), that's not a problem. But if that isn't true, you'll want to use processes instead of threads. Which only requires replacing the ThreadPoolExecutor in the example with a ProcessPoolExecutor.

If you want to do this entirely in the 2.7 stdlib, it's nearly as trivial with the thread and process pools built into the multiprocessing. See Using a pool of workers and the Process Pools API, then see multiprocessing.dummy if you want to use threads instead of processes.

A: Could be overkill, but you may like to have a look at Celery.
Tutorial
tasks.py could be:
from celery import Celery
import requests

app = Celery('tasks', broker='amqp://guest@localhost//')

apikey="12345"
restkey="12345"

URL="https://api.web.com/1/install/"
headers={'content-type': 'application/json','Application-Id': apikey,'REST-API-Key':restkey}

f = open('upload_data.log', 'a+')
@app.task
def upload_data(data, count):
    r = requests.post(URL, data=data, headers=headers)
    f.write("Count: %d\n%s\n\n" % (count, r.content)

Start celery task with:
$ celery -A tasks worker --loglevel=info -c 20

Then in another script:
import tasks
def AddPushTokens():

    import csv
    import json

    count=0
    tokenList=[]

    with open('/Users/name/Desktop/push-new.csv','rU') as csvfile:
        deviceTokens=csv.reader(csvfile, delimiter=',')

        for token in deviceTokens:
            deviceToken=token[0].replace("/","")
            deviceType="ios"
            pushToken="pushtoken_"+deviceToken
            payload={"deviceType": deviceType,"deviceToken":deviceToken,"channels":["",pushToken]}
   r = tasks.upload_data.delay(json.dumps(payload), count)

   count=count+1

NOTE: Above code is sample. You may have to modify it for your requirement.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Physics2D.OverlapBox() не работает. Что делать? Я пишу скрипт передвижения в юнити 2д, и решил вместо Physics2D.OverlapCircle() использовать Physics2D.OverlapBox(), но он не работает.
Gizmos отрисовывает всё правильно, слой проверил, считывается только одна точка в центре квадрата.
вот аргументы:
(feetPos.position(позиция у ног персонажа), checkFieldSize(размеры квадрата), 0(без понятия для чего это), whatIsGround(слой земли))
что я делаю не так?


text:
Q: How do i start a github java program? I would like to start the program from this repository:
https://github.com/SaifurRahmanMohsin/Personal-Diary
but when I dowload or clone it there is no Install file or no command in the readme file to compile it.
How do I use it?

A: GitHub is just a version control hosting service, so it's not a problem related to github but the project itself.
Launcher.java have a main function, you need to run it to launch the project

A: this project is not maven project, I think it will be best if you open it in eclipse and execute the Launcher (it has the main method for the execution)

A: The repository includes a .project file for Eclipse. If you use this IDE you can import the project directly.
File -> Import -> General -> Existing project into workspace. Then select the Personal Diary folder which contains the .project file.
You can also compile manually using javac.


text:
Q: Opposite of preserve_most calling-convention attribute? I'm a beginner and working on compilers and would like to apply one attribute to remove MOVAPS instruction from the assembly.
Is there any attribute in C++ which performs the opposite function of clang's preserve_most?


text:
Q: How do I correctly stop a Media Player in a CountDown Timer when the activity is Paused? I can successfully cancel the Countdown Timer before it finishes when the activity is paused. However, the media player implemented in the OnTick method of the canceled timer doesn't stop for  5-8 seconds. What would be the correct way to disable the sound of the media player in the CountDown Timer when the activity is paused?
private Button soundOn;
private Button soundOff;

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

   SharedPreferences savedSoundToggle = getSharedPreferences(PREFS_SOUNDTOGGLE, 0);
    final SharedPreferences.Editor soundEditor = savedSoundToggle.edit();

    nSound = savedSoundToggle.getInt("SoundOnorOff", 0);

    if(nSound == 1){
        soundOff.setEnabled(false);
        soundOff.setVisibility(View.INVISIBLE);
        soundOn.setEnabled(true);
        soundOn.setVisibility(View.VISIBLE);
    }
    else if( nSound == 0){
        soundOn.setEnabled(false);
        soundOn.setVisibility(View.INVISIBLE);
        soundOff.setEnabled(true);
        soundOff.setVisibility(View.VISIBLE);
    }

}

public void OneGame(){

  final MediaPlayer intro = MediaPlayer.create(getApplicationContext(), R.raw.minicycleaudio);
  final MediaPlayer go = MediaPlayer.create(getApplicationContext(), R.raw.flashgoaudio);

  getReadyTimer = new CountDownTimer(6000, 1000) {

        public void onTick(long millisUntilFinished) {

            getReadyTimeText.setText("" + millisUntilFinished / 1000);

            if(soundOn.isEnabled()){
                intro.start();
            }
            if(soundOff.isEnabled()){
                if(intro.isPlaying()){
                    intro.pause();
                }
            }
         }

          public void onFinish() {

            if(intro.isPlaying()) {
                intro.stop();
                intro.release();
            }
             if(soundOn.isEnabled()) {
                go.start();
            }

@Override
public void onPause() {

  super.onPause();
  getReadyTimer.cancel();

  }
}

I'm almost 100% positive that the Countdown timer becomes canceled when the activity is paused because the media player in the onFinish() function is never called. Why does the media player in the onTick method keep playing?

A: I figured it out: To cancel a media player in a CountDown Timer, when the activity is paused... you must declare the MediaPlayer as static, not final.
static  MediaPlayer intro;

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_level_one);
    getReadyTimeText = (TextView) findViewById(R.id.levelonetimerText);

 public void OneGame(){
    intro = MediaPlayer.create(getApplicationContext(), R.raw.minicycleaudio);

}


text:
Q: clonehd takes 2 hours for a 100GB disk. Expected? I have a VirtualBox image using VDI and flexible size. Right now the physical DVI file 94GB. The host is an Ubuntu server and the guest is a CentOS 6.4 with ext4 partition. The host is using a sata normal disk of 1TB.
Disk read speed is:
 sudo hdparm -tT /dev/sda

 /dev/sda:
 Timing cached reads:   23330 MB in  2.00 seconds = 11679.09 MB/sec
 Timing buffered disk reads: 420 MB in  3.01 seconds = 139.49 MB/sec

Disk write speed:
 sudo dd if=/dev/zero of=output bs=8k count=128k; sudo rm -f output
 131072+0 records in
 131072+0 records out
 1073741824 bytes (1.1 GB) copied, 4.91353 s, 219 MB/s

So... I guess copying a 100GB should take much less. In fact, a simple cp takes a lot less. In my example, it takes 30 minutes, compared to the 2 hours of clonehd.
I know that clonehd also does a compact so that might be a big difference. Now..say that I want to compact only once explicitly and then just clone. Is there another faster alternative?  I read somewhere that what I can do is a simple cp and then change the UUID of the created cloned image. Has anyone did this? Is it safe? Since I am doing this for backups...I need the process to be safe.
Note that I already cleaned free space in guest Cent OS using dd or zerofree. But this is not the topic of this thread.
Actually, I would not have that much problem if I could run the clonehd while still running the VM, but I read this is not possible/recommended since the cloned/copied vdi files could be corrupted if it was concurrently modified.
Thanks in advance,

A: You wrote that "the host is using a sata normal disk of 1TB". This leads me to believe that you are talking about a rotational HDD, possibly even a desktop-grade drive (like a 7200 rpm SATA instead of a 10k or 15k rpm SAS drive, let alone SSDs).
Keep in mind that 7200 rpm drives commonly top out at about 100-120 MB/s. This puts an upper bound on what you should expect to get, when not relying on caching. (Note that the dd command in the question most likely relies heavily on caching, and thus gives an inaccurate picture of the I/O performance. You can add conv=sync to force using synchronous I/O. Also as pointed out in the comments, by reading from /dev/zero, you are eliminating one side of the equation.)
It's quite possible that, since your VM's disk image file is thinly provisioned, that it's fragmented on disk. Depending on how heavily fragmented it is, you may even be IOPS-bound. 7200 rpm drives have a theoretical maximum capability of 120 IOPS.
A single way (read or write) 100 GB at 110 MB/s will take about 900 seconds. Double that because you are both reading and writing, and you are looking at 1800-2000 seconds, or half an hour.
When adding fragmentation to this, two hours certainly sounds like it would be in the ballpark.


text:
Q: Ruby: Run loop if variable set I'm executing a command with in ruby using open3, and Im setting a timeout using the safe_timeout gem (because of known issues with timeout reported here)
The code I have is very simple:
SafeTimeout.timeout(t) do
  stdout, stdeerr, status = Open3.capture3(cmd)
  @output = stdout
  @result = status.exitstatus
  @pid = status.pid
  @timeout = t
end

The caveat here is that I only want to run this within the timeout block if t is defined.
Obviously I can use an if statement but then I'd have duplicate stuff and it doesn't feel very "ruby-like" to me.
Is there a nice way to do something like:
if t
  timeout.do
    command
  end
else
  command_without_timeout
end

?

A: You can use a Proc - the reified version of a Ruby code block. Put your command in the proc, and then either pass the proc to the timeout method (using the & operator to pass it as a block instead of a normal parameter) or else just call it directly.  Example:
block = proc do
  # this is the code I want to run
  # with or without the timeout
  stdout, stdeerr, status = Open3.capture3(cmd)
  @output = stdout
  @result = status.exitstatus
  @pid = status.pid
  @timeout = t
end

if t then
  SafeTimeout.timeout(t, &block)
else
  block.call
end


text:
Q: Is there a java api which I can use for a permutation of numbers to find out canonical form of its equivalence classes? Is there a java api which I can use for a permutation of numbers to find out canonical form of its equivalence classes ?
It is required for all possible guesses for Mastermind.
As per the document .
EDIT :Let me explain by example what I am looking for
Example : In order to solve the game of in minimum steps we have to give our guesses and based on the response decide the next guess .
Lets say for 4 pegs and 6 colors ( total combination = 1296  , repeat allowed ) .
For the initial try we only need to consider one possible guess lets say 0011 and the response we get is 1 Black and 0 White.(1,0).
Now, We check 0011 against all the 1296 numbers and keep all those which return (1,0). Thus, our solution is somewhere inside this reduced sample set.
Now for the second query using equivalence transformations as mentioned in the document possible codes are reduced for second try.
Now, I want to know if there an any existing java api which I can use for a given set of permutations ( reduced set after (0,1) on 1296 ) and get equivalence transformations on my inputs ?
Thanks In Advance.

A: Consider using sorting to find the equivalence classes.
By sorting 1010 and 1001 you each time get 0011.


text:
Q: Simple HTML table issue I'm coding in PHP and I code for simple HTML table. In that table the columns are editable and there is input type=number used to restrict from negative value entry in column names: Carton, Width, Depth, Height and Act columns.
But it's not working, creating problem with input type="number" and min="0" inside the html table.
Here is the link: http://sea.studioscue.in/test.php

A: just check the validity.valid property. This will be true if and only if the input falls within the range.
just add oninput="validity.valid||(value='');" to your input field.
<input type="number" oninput="validity.valid||(value='');" class="carton" min="0" value="" name="carton" maxlength="5" style="width:100px">


text:
Q: "Object doesn't support property or method" - jQuery Nokia Lumia I keep getting "Object doesn't support property or method" for basic jQuery such as "before". I'm trying to simply add a couple of DIV tags before an element. This works with iPhone, Android and responsive design view in Firefox but this particular phone in question, Nokia Lumia 520 keeps reporting "Object doesn't support property or method". Client suspects it's jQuery version which is version 1.4.3 (I know it's old but clients CMS isn't as simple as changing the jQuery version, it requires major upgrades on their side).
One thing I have noticed is that it does work if I setTimeout() for 4 seconds. So this made me think maybe the element isn't available or maybe the DOM is loaded differently on Windows phone. So I've tried various things such as $('#myelement').length, $(window).load(), waitUntilExists() (http://javascriptisawesome.blogspot.co.uk/2011/07/faster-than-jquerydocumentready-wait.html), even coding my own timer to check if the element exists every X milliseconds but still getting the error. $('#myelement').length always reports the element exists but I can't use for example $('#myelement').before('

');. Any help much appreciated!
EDIT: Example code:
function initRWD(m){
    var t = setTimeout(function(){
        if($(m).length){
            $(m).before('

Hello

');
            clearTimeout(t);
        } else
            initRWD(m);
    },500);
}

$(document).ready(function(){
    //setTimeout(function(){
    initRWD('#myelement');
    //},4000);
});

A: I had one last go and figured it out! I added &&'before' in $(m) to the "if" statement as an additional check to see if the 'before' function/property/method exists also.


text:
Q: Handling old data in new app versions in ANDROID...! Handling old data in new app versions,
e.g.: in Internal or External storage's data, if I changed some App's generated folder's name then data would we copied into new folder.
For databases you can use the built in SQLiteOpenHelper class it has the onUpgrade method.
Is there any to do for Internal or External storage's data ???
thanks...!

A: Its not that easy to do that as with SQLite.
You need to do many things

*

*Have an Preference to store the Current Version.

*Have One method or class for each Version.

*Implement your own Application Class for updating

Your Method or Class for each Version
Here you need to modified the data in either storage to the latest version.
Own Application
In your own Application class you need to check whether Current Version (stored in preference) is the latest version.
If not then you need to call corresponding method or class which do the conversion.
Hope this gives you an idea.


text:
Q: What are the most commonly used data backup methods for Mac OS X Yosemite version? Please tell me in detail about that. I need some reliable solution for my Mac OS X.

A: The most common solution by far would be Time Machine, which comes included with Mac OS X. Just by an external drive of (say) twice the size of your Mac's drive, plug it in, and Mac OS X will probably just ask if you want to start using it for Time Machine automatically.
If you're smart, you'll buy two drives, set them both up as Time Machine backups, and then rotate them between backing up your system, and being stored elsewhere.


text:
Q: Trying to use PyCryptodome AES ECB decryption with offsets As a bit of context to this I am converting a java file to python and am on the last operation. I'm at about 200 LOC so it makes it that much more edge of the seat...
Anyways, in java the operation is:
Cipher cipher = Cipher.getInstance("AES/ecb/nopadding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keys[i], "AES"));

//doFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
cipher.doFinal(save, saveOffset, 16, save, saveOffset);

In python I have this:
from Crypto.Cipher import AES
cipher = AES.new(bytes(keys[i]), AES.MODE_ECB)
cipher.decrypt(?????)

This is taken from the package under decrypt():
:Parameters:
  ciphertext : bytes/bytearray/memoryview
    The piece of data to decrypt.
    The length must be multiple of the cipher block length.
:Keywords:
  output : bytearray/memoryview
    The location where the plaintext must be written to.
    If ``None``, the plaintext is returned.
:Return:
  If ``output`` is ``None``, the plaintext is returned as ``bytes``.
  Otherwise, ``None``.

As you can see .decrypt() doesn't really have an input for offsets, but I was wondering if there was some way around this?
This is why I decided to post on SO, would I be able to send:
temp_bytes = save[offset]
temp_decrypt = cipher.decrypt(temp_bytes)
save[offset] = temp_decrypt

Or when decrypting does it use the whole file as context and i will get the wrong output? I would love to just do it and test it but the output is just gibberish that i will have to write another program to parse (another java to python project).

A: What ended up working was:
save[saveOffset:saveOffset+16] = cipher.decrypt(save[saveOffset:saveOffset+16])

Did not expect it to work so easily


text:
Q: Use lambda function in new switch c# 8.0 to return value I want to use new switch in my code, that for method result make log and return IActionResult.
I try to do something like this:
var response = (this._coreRepository.Write(value.Content, data.Id.ToString())); \\return bool
return response switch
{
   true => () =>
   {
      this._log.LogInformation("Write is complited");
      return Ok();
   },
   false => () =>
   {
      this._log.LogInformation("Error in writing");
      return BadRequest();
   },
   _     => () =>
   {
      throw new Exception("Unexpected error");
   }
};

But compiler says to me cannot convert lambda expression to type 'IActionResult' because it is not a delegate type.
How can I fix it?

A: The problem is that your switch expression returns a lambda expression but the containing method expects IActionResult. To fix the problem you should rewrite the return statement to immediately invoke result of the switch expression:
var response = (this._coreRepository.Write(value.Content, data.Id.ToString()));

return (response switch
{
   // Here we cast lambda expression to Func<IActionResult> so that compiler
   // can define the type of the switch expression as Func<IActionResult>.
   true => (Func<IActionResult>) (() =>
   {
      this._log.LogInformation("Write is complited");
      return Ok();
   }),
   false => () =>
   {
      this._log.LogInformation("Error in writing");
      return BadRequest();
   },
   _     => () =>
   {
      throw new Exception("Unexpected error");
   }
})(); // () - here we invoke Func<IActionResult>, the result of the switch expression.

If I were you I would rewrite this code the next way to make it easier to read:
var response = (this._coreRepository.Write(value.Content, data.Id.ToString()));

// Now additional braces or casts are not required.
Func<IActionResult> func = response switch
{
   true => () =>
   {
      this._log.LogInformation("Write is complited");
      return Ok();
   },
   false => () =>
   {
      this._log.LogInformation("Error in writing");
      return BadRequest();
   },
   _     => () =>
   {
      throw new Exception("Unexpected error");
   }
}

return func();


text:
Q: Any format date/time conversion to epoch I have written a program that gets SSL certificate expiration date/time using libcurl. But, the problem is that they are being returned in two different format when I run my program on two different operating systems.
Windows: 2031-04-13 23:59:59 GMT
CentOS7: Mar 14 23:59:59 2023 GMT
I don't know if the format would be different again if ran on another OS.
I want to get time since epoch in seconds till that date /time for both of them. Libcurl provides a function to handle the CentOS7 format CURL_GETDATE, and for Windows version I am using boost/date_time . I was wondering if there is something that exist that can do this job i.e. provide date/time in any format!!, and it returns time since epoch in seconds till mentioned date. Or some sort of generic implementation to achieve that?
I found this and this while searching, which is what I am looking for, but this code doesn't work, throwing exception:
Exception thrown at 0x00007FFFB0254FD9 in BoostHttp.exe: Microsoft C++ exception: boost::wrapexcept<boost::gregorian::bad_month> at memory location 0x000000FB1FAFD1F8.
Exception thrown at 0x00007FFFB0254FD9 in BoostHttp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFFB0254FD9 in BoostHttp.exe: Microsoft C++ exception: boost::wrapexcept<boost::gregorian::bad_month> at memory location 0x000000FB1FAFD1F8.
Exception thrown at 0x00007FFFB0254FD9 in BoostHttp.exe: Microsoft C++ exception: boost::wrapexcept<boost::gregorian::bad_month> at memory location 0x000000FB1FAFD1F8.
Exception thrown at 0x00007FFFB0254FD9 in BoostHttp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFFB0254FD9 in BoostHttp.exe: Microsoft C++ exception: boost::wrapexcept<boost::gregorian::bad_month> at memory location 0x000000FB1FAFD1F8.
Exception thrown at 0x00007FFFB0254FD9 in BoostHttp.exe: Microsoft C++ exception: boost::wrapexcept<boost::gregorian::bad_month> at memory location 0x000000FB1FAFD1F8.
Exception thrown at 0x00007FFFB0254FD9 in BoostHttp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFFB0254FD9 in BoostHttp.exe: Microsoft C++ exception: boost::wrapexcept<boost::gregorian::bad_month> at memory location 0x000000FB1FAFD1F8.
Exception thrown at 0x00007FFFB0254FD9 in BoostHttp.exe: Microsoft C++ exception: boost::wrapexcept<boost::gregorian::bad_month> at memory location 0x000000FB1FAFD1F8.
Exception thrown at 0x00007FFFB0254FD9 in BoostHttp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFFB0254FD9 in BoostHttp.exe: Microsoft C++ exception: boost::wrapexcept<boost::gregorian::bad_month> at memory location 0x000000FB1FAFD1F8.

 output:

 ptime is not-a-date-time
 seconds from epoch are 9223372036854
 ptime is not-a-date-time
 seconds from epoch are 9223372036854
 ptime is not-a-date-time
 seconds from epoch are 9223372036854
 ptime is not-a-date-time
 seconds from epoch are 9223372036854

Any help would be appreciated. Thanks


text:
Q: Perl removing words from file1 with file2 I am using a perl script to remove all stopwords in a text. The stop words are stored one by line. I am using Mac OSX command line and perl is installed correctly.
This script is not working properly and has a boundary problem.
#!/usr/bin/env perl -w
# usage: script.pl words text >newfile
use English;

# poor man's argument handler
open(WORDS, shift @ARGV) || die "failed to open words file: $!";
open(REPLACE, shift @ARGV) || die "failed to open replacement file: $!";

my @words;
# get all words into an array
while ($_=<WORDS>) {
  chop; # strip eol
  push @words, split; # break up words on line
}

# (optional)
# sort by length (makes sure smaller words don't trump bigger ones); ie, "then" vs "the"
@words=sort { length($b) <=> length($a) } @words;

# slurp text file into one variable.
undef $RS;
$text = <REPLACE>;

# now for each word, do a global search-and-replace; make sure only words are replaced; remove possible following space.
foreach $word (@words) {
     $text =~ s/\b\Q$word\E\s?//sg;
}

# output "fixed" text
print $text;

sample.txt
$ cat sample.txt
how about i decide to look at it afterwards what
across do you think is it a good idea to go out and about i
think id rather go up and above

stopwords.txt
I
a
about
an
are
as
at
be
by
com
for
from
how
in
is
it
..

Output:
$ ./remove.pl stopwords.txt sample.txt
i decide look fterwards cross do you think good idea go out d i
think id rather go up d bove

As you can see, it replaces afterwards using a as fterwards. Think its a regex problem. Please can somebody help me to patch this quickly? Thanks for all the help :J

A: Use word-boundary on both sides of your $word. Currently, you are only checking for it at the beginning.
You won't need the \s? condition with the \b in place:
$text =~ s/\b\Q$word\E\b//sg;

A: Your regex is not strict enough.
$text =~ s/\b\Q$word\E\s?//sg;

When $word is a, the command is effectively s/\ba\s?//sg. This means, remove all occurrences of a new word starting with a followed by zero or more whitespace. In afterwards, this will successfully match the first a.
You can make the match more stricter by ending word with another \b. Like
$text =~ s/\b\Q$word\E\b\s?//sg;


text:
Q: Is increment stackable? I.e x++++; or (x++)++; When me and my friend were preparing for exam, my friend said that x+++; is the same as x+=3;
It is not true but is x++++; same as x+=1; or is (x++)++;? Could I generalize it? I.e. x++++++++++++++; or ((((((x++)++)++)++)++)++)++; is equivalent to x+=7;
Maybe it's completely wrong and it is true for ++++++x; or ++(++(++x)); equivalent to x+=3;
Also it should generalize to --x; and x--;

A: The behavior of your program can be understood using the following rules from the standard.
From lex.pptoken#3.3:

Otherwise, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token, even if that would cause further lexical analysis to fail, except that a header-name is only formed within a #include directive.

And from lex.pptoken#5:

[ Example: The program fragment x+++++y is parsed as x ++ ++ + y, which, if x and y have integral types, violates a constraint on increment operators, even though the parse x ++ + ++ y might yield a correct expression.  — end example ]

is x++++; same as x+=1;

Using the statement quoted above, x++++ will be parsed as x++ ++.
But note that from increment/decrement operator's documentation:

The operand expr of a built-in postfix increment or decrement operator must be a modifiable (non-const) lvalue of non-boolean (since C++17) arithmetic type or pointer to completely-defined object type. The result is prvalue copy of the original value of the operand.

That means the result of x++ will a prvalue. Thus the next postfix increment ++ cannot be applied on that prvalue since it requires an lvalue. Hence, x++++ will not compile.
Similarly, you can use the above quoted statements to understand the behavior of other examples in your snippet.


text:
Q: Calculating Monthly Anomalies in Pandas Hello StackOverflow Community,
I have been interested in calculating anomalies for data in pandas 1.2.0 using Python 3.9.1 and Numpy 1.19.5, but have been struggling to figure out the most "Pythonic" and "pandas" way to complete this task (or any way for that matter). Below I have some created some dummy data and put it into a pandas DataFrame. In addition, I have tried to clearly outline my methodology for calculating monthly anomalies for the dummy data.
What I am trying to do is take "n" years of monthly values (in this example, 2 years of monthly data = 25 months) and calculate monthly averages for all years (for example group all the January values togeather and calculate the mean). I have been able to do this using pandas.
Next, I would like to take each monthly average and subtract it from all elements in my DataFrame that fall into that specific month (for example subtract each January value from the overall January mean value). In the code below you will see some lines of code that attempt to do this subtraction, but to no avail.
If anyone has any thought or tips on what may be a good way to approach this, I really appreciate your insight. If you require further clarification, let me know. Thanks for your time and thoughts.
-Marian
#Import packages
import numpy as np
import pandas as pd
#-------------------------------------------------------------
#Create a pandas dataframe with some data that will represent:
#Column of dates for two years, at monthly resolution
#Column of corresponding values for each date.

#Create two years worth of monthly dates
dates = pd.date_range(start='2018-01-01', end='2020-01-01', freq='MS')

#Create some random data that will act as our data that we want to compute the anomalies of
values = np.random.randint(0,100,size=25)

#Put our dates and values into a dataframe to demonsrate how we have tried to calculate our anomalies
df = pd.DataFrame({'Dates': dates, 'Values': values})
#-------------------------------------------------------------
#Anomalies will be computed by finding the mean value of each month over all years
#And then subtracting the mean value of each month by each element that is in that particular month

#Group our df according to the month of each entry and calculate monthly mean for each month
monthly_means = df.groupby(df['Dates'].dt.month).mean()
#-------------------------------------------------------------
#Now, how do we go about subtracting these grouped monthly means from each element that falls
#in the corresponding month.
#For example, if the monthly mean over 2 years for January is 20 and the value is 21 in January 2018, the anomaly would be +1 for January 2018

#Example lines of code I have tried, but have not worked

#ValueError:Unable to coerce to Series, length must be 1: given 12
#anomalies = socal_csv.groupby(socal_csv['Date'].dt.month) - monthly_means

#TypeError: unhashable type: "list"
#anomalies = socal_csv.groupby(socal_csv['Date'].dt.month).transform([np.subtract])

A: You can use pd.merge like this :
import numpy as np
import pandas as pd

dates = pd.date_range(start='2018-01-01', end='2020-01-01', freq='MS')

values = np.random.randint(0,100,size=25)

df = pd.DataFrame({'Dates': dates, 'Values': values})

monthly_means = df.groupby(df['Dates'].dt.month.mean()

df['month']=df['Dates'].dt.strftime("%m").astype(int)
df=df.merge(monthly_means.rename(columns={'Dates':'month','Values':'Mean'}),on='month',how='left')
df['Diff']=df['Mean']-df['Values']

output:
 df['Diff']
Out[19]:
0     33.333333
1     19.500000
2    -29.500000
3    -22.500000
4    -24.000000
5     -3.000000
6     10.000000
7      2.500000
8     14.500000
9    -17.500000
10    44.000000
11    31.000000
12   -11.666667
13   -19.500000
14    29.500000
15    22.500000
16    24.000000
17     3.000000
18   -10.000000
19    -2.500000
20   -14.500000
21    17.500000
22   -44.000000
23   -31.000000
24   -21.666667

You can use abs() if you want absolute difference

A: A one-line solution is:
df = pd.DataFrame({'Values': values}, index=dates)
df.groupby(df.index.month).transform(lambda x: x-x.mean())


text:
Q: SQL view for displaying a collection, with any associated related records by employee I am writing a training administration system and need to display a list of all training course types held in a table for each employee in a given team.
For each of those training courses I then want to look at a booking table and get the latest booking for that employee and course type combo. Even if no booking exists I still want to pull back each course type for each employee. (Albeit with nulls for the booking fields). Bookings join to employee on booking.empID to employee.id and booking links to coursetype on booking.courseId to courseType.id.
I want the result to be grouped by employee.
I have managed to get this working by creating a view model in MVC, BUT even on my test data with 8 employees, 10 course types and a handfull of bookings I am seeing load times of 6-7 seconds. I assume that my view model is wildly inefficient.
These are the classes I am using on my VM:
public class TeamMemberTraining()
{
   public int UserId { get; set; }
   public string UserName { get; set; }
   public IEnumerable<trainingSet> Trainingset { get; set; }
}

public class trainingSet()
{
   public int templateId { get; set; }
   public string templateName { get; set; }
   public TrainingCourseBooking LastBooking { get; set; }
   public TrainingCourseBooking FutureBooking { get; set; }
}

My dataset is build in my repository in the following way:
 public List<TeamMemberTraining> GetPersonalHistory(int id)
    {
        var teamMatrix = new List<TeamMemberTraining>();
        var teamMembers = GetProfileIdsByTeam(teamID); //Int list of employee id's
        foreach (var teamMemberin teamMembers)
        {
            var empMatrix = new TeamMemberTraining();
            var empRecord = _entities.employees.FirstOrDefault(x => x.Id == emp);
            empMatrix.trainingSet = GetPersonalHistory(emp);
            empMatrix.UserId = empRecord.Id;
            empMatrix.UserName = empRecord.forename + " " + empRecord.surname;
            teamMatrix.Add(empMatrix);
        }
}

 public IEnumerable<trainingSet> GetPersonalHistory(int id)
    {
        var matrix = new List<trainingSet>();
        var courses = (from a in _entities.courseTypes
            select a).ToList();
        var employee = (from a in _entities.employees
            where a.Id == id
            select a).FirstOrDefault();
        foreach (var course in courses)
        {
            var matrixItem = new trainingSet
            {
                templateId = course.Id,
                templateName = course.description,
             };
            var history = (from a in _entities.TrainingCourseBookings
                where a.templateId == courseType.Id && a.employeeId == id && a.certificateIssued
                orderby a.Id descending
                select a).FirstOrDefault();
            if (history != null)
            {
                matrixItem.LastBooking = history;
            }

            var future = (from a in _entities.TrainingCourseBookings
                where a.templateId == courseType.Id && a.employeeId == id && a.TrainingCourse.courseDate >= DateTime.Now
                orderby a.Id descending
                select a).FirstOrDefault();
            if (future != null)
            {
                matrixItem.FutureBooking = future;
            }

            matrix.Add(matrixItem);
       }

        return matrix;
    }

This gives me my list of all courses, by user, with bookings shown if they exist. It also gives me a whole load of slow loading times with all the nesting.
Can anyone offer me any better ways of achieving this?
Many many thanks

A: Try something like this.
   IEnumerable<TrainingSet> GetPersonalHistory(int id)
   {
        var employee = _entities.employees.FirstOrDefault(e => e.Id == id);
        var results =
            from course in _entities.courseTypes
            let applicableBookings =
                from booking in _entities.TrainingCourseBookings
                where booking.employeeOd == id
                where booking.templateId == course.courseType.Id
                orderby booking.Id descending
                select booking
            let history = applicableBookings.FirstOrDefault(b => b.certificateIssued)
            let future = applicableBookings.FirstOrDefault(b => b.TrainingCourse.courseData >= DateTime.Now)
            select new TrainingSet
            {
               TemplateId = course.Id,
               TemplateName = course.description,
               LastBooking = history,
               FutureBooking = future
            };
        return results.ToList();
    }


text:
Q: 504 when using PHP file_get_contents on Amazon EC2 I have an odd issue
We are in the midst of moving our site from on-premise servers (PHP 5.3) to Amazon EC2 cloud (PHP 7.0), both running apache
I have a php function that calls file_get_contents, which i then decode json for into a variable to do some processing
$klein->respond('POST', '/tracker/[i:id]', function ($request, $response, $service, $app) {
  $json = file_get_contents('test-url/eds.php?uid='.$request->param('id'));
  $result = json_decode($json);
...

On premises, this function works fine, In the Ec2 instance however, I am receiving a 504 gateway error.
here is the oddity, this works fine on the EC2 instance if I substitute the url for the on-premise site...no 504 error occurs
$json = file_get_contents('on-premise/eds.php?uid='.$request->param('id'));;

I tried replacing the file_get_contents with curl, and also had my ini_set to allow_url_fopen, neither remidied the situation, I'm beginning to think something larger is at play here
any help is greatly appreciated


text:
Q: assigning items of a list to the nodes of a graph I want to assign items of a list to the nodes of a graph one by one as attributes of those nodes. The code is as follows but it doesn't loop through the second "for". How can I fix this?
r = bernoulli.rvs(p=0.4, size=100)
G = nx.Graph(nx.powerlaw_cluster_graph(101, 1, 0.001))
nx.set_node_attributes(G, pol, 'politic')
r_list=r.tolist()

for i in G.nodes():
    for elem in r_list:
        G.nodes[i]['politic'] = elem

A: So if I get you right, I think you should do this
for i in G.nodes():
    for elem in r_list[:]:
        G.nodes[i]['politic'] = elem
        r_list.remove(elem)
        continue


text:
Q: LOAD DATA LOCAL INFILE from line after line i am trying to copy data from text file into db with "load data local infile".
the text example:
jack
|
hi
|-
ron
|
whats new
|-
jack
|
ok
|-
ron
|
bye
|-

the code i am trying:
include 'conect.php'; // conect to DB
$query = "LOAD DATA LOCAL INFILE 'messages2.txt'
INTO TABLE `conv`
FIELDS TERMINATED BY '|'
LINES TERMINATED BY '-'
(name, msg)";
mysql_query($query);
mysql_close();

its only copying the first name to the db.
what is the correct way to do this?
thanks alot.

A: The way I look at it is:
jack|hi|-
ron|whats new|-
jack|ok|-
ron|bye|-
So I would try:
FIELDS TERMINATED BY '|'
LINES TERMINATED BY '|-'

However, since you have carriage returns, you may need either \n or \r or \r\n:
FIELDS TERMINATED BY '|\n'
LINES TERMINATED BY '|-\n'


text:
Q: (Angular) Make global variables always change their values according to a service I have this problem, a button that has a data-binded label, something like:

<button>{{label}}</button>

I need it to change its values depending what is on the screen. And that is mostly easy, i just change the label value in my component.ts.
The problem is, after somes changes on the system, i need this to happen when i use other component. This button is always on screen, on MainComponent, but when acessing FooComponent (click clicking specific things on screen), i need its label to change.
To do that, i created a Main.service.ts, where i create the label variable, and just call its value in mainComponent.
This is the service:
@Injectable({
  providedIn: 'root'
})
export class MainService {

  constructor() { }

  label = "IntialFoo";

  foo01() {
    this.label = 'foo01';
  }

  foo02() {
    this.label= 'foo02';
  }

And the component:
export class MainComponent extends BaseService<any> implements OnInit {

  constructor(
    private mainService: MainService,
    ...
  ) {
    super(...);
  }

  ...
  label = this.mainService.label;

Now let's say i import my service in my fooComponent, i'd call the service's functions to change the label value, it works, in the service. And that is the problem, the button is not changing its values, and that's because the variable is not listing to the service, it just gets its value once, and then it does not change.
So, how can i make my label variable (in mainComponent) change in real-time its value according to the label in the service?

A: You can implement a private BehaviorSubject that will be exposed as a public Observable. Something like this:
import { Injectable } from '@angular/service';
import { Observable, BehaviorSubject } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class MainService {

    private label: BehaviorSubject<string> = new BehaviorSubject<string>('IntialFoo');
    label$: Observable<string> = this.label.asObservable();

    updateLabel(updatedLabel) {
        this.label.next(updatedLabel);
    }
}

You can then inject this service as a dependency in your Components and then use the label$ with an async pipe in your Template to avoid manually calling unsubscribe. Something like this:
export class MainComponent extends BaseService < any > implements OnInit {

  constructor(private mainService: MainService,...) {
    ...
  }

  ...

  label$ = this.mainService.label$;

}

And in the template:
<button>{{ label$ | async }}</button>

A: I would not extend the component with BaseService as the service should be a singleton.  I would have the service injected into any component that needs the label and the service to return as observable.  Please see code below...

    // Service
    @Injectable({
      providedIn: 'root'
    })
    export class MainService {

      constructor() { }
      getLabel(component:string): Observable<string> {
        return Observable.of(component);

      }
    }

    // Component:
    import { takeWhile, switchMap } from 'rxjs/operators';
    import { OnInit, OnDestroy, Input } from '@angular/core'

    export class MainComponent implements OnInit, OnDestroy {

          constructor(
            private mainService: MainService,
            ...
          ) {

          }
      @Input() passedInLbl:string;
      private label: string;
      private isActive: boolean;
      ngOnInit():void {
          this.isActive = true;
          mainService.getLabel(passedInLabel).pipe(
              switchMap(resp => {
                  this.label = resp;
              }),
              takeWhile(() => this.isActive)
          );
      }
      ngOnDestory(): void {
          this.isActive = false;
      }

    }


text:
Q: Limit of a Sequence $\lim_{n\to\infty} \frac{(-3)^n+10}{2^n-1}$ Find the limit of the following sequence: $\displaystyle\lim_{n\to\infty} \frac{(-3)^n+10}{2^n-1}$
I solved it the following way, and was wondering if what I did is correct:
$\displaystyle\lim_{n\to\infty} \frac{(-3)^n+10}{2^n-1} \geq \lim_{n\to\infty} \frac{(-3)^n}{2^n-1} \geq \lim_{n\to\infty} \frac{(-3)^n}{2^n} = \lim_{n\to\infty} (\frac{-3}{2})^n = \lim_{n\to\infty}(-1.5)^n$.
The limit does not exist, and the sequence diverges, as $(-1.5)^n =: q^n$: $q$ < 0 (the sequence alternates), and $|q|>1$ means that $\lim_{n\to\infty}q^n = \infty$ (i.e. no limit exists).

A: You can use the inequalities provided the limits exist!
But you can use the idea in a better way.
For even $n$, you have
$$
\frac{(-3)^n+10}{2^n-1}=\frac{3^n+10}{2^n-1}\ge\left(\frac{3}{2}\right)^{\!n}
$$
so the only possibility for the limit would be $\infty$.
On the other hand, for odd $n$, $n\ge 3$, we have
$$
\frac{(-3)^n+10}{2^n-1}=\frac{-3^n+10}{2^n-1}<0
$$
so the limit can't be $\infty$.

A: Hint: $a_{2n} \to +\infty, a_{2n+1} \to -\infty \to \text{ no limit exists}$


text:
Q: React Native: How to calculate custom native UITextView height dynamically I am working on an existing iOS-App in which I have added new features with React-Native.
Works great so far. Now I have to use an already developed custom native Swift UITextView subclass. The text is getting fetched from the API. So the size of the UITextView should be dynamic.
On React-Native side it looks like this:
import { requireNativeComponent } from 'react-native';

export const NativeTextView = requireNativeComponent('RNNativeTextView');

export default function FooView(props: FooViewProps) {
    return (
        <View
            style={{
                ...props.style,
                flexDirection: 'row',
                flexWrap: 'wrap',
                backgroundColor: 'red',
                margin: Dimensions.generalPadding * 2,
            }}
        >
            <NativeTextView
                text={props.viewModel.aboutMeText}
                textColorString={Colors.red}
                backgroundColor={Colors.black}
                style={{
                    ...regularTextStyle,
                    width: "100%",
                    flexDirection: 'row',
                }}    />
        </View>
    )
}

On the native iOS side:

@objc(RNNativeTextView)
class NativeTextView: UITextView {
   ... (native implementation)
}

import Foundation

@objc(RNNativeTextViewManager)
class RNNativeTextViewManager: RCTViewManager {

    override func view() -> UIView! {

        let textView = NativeTextView(frame: CGRect(x: 0, y: 0, width: .zero, height: .zero))
        return textView
  }
}

#import <React/RCTBridgeModule.h>
#import <React/RCTViewManager.h>

@interface RCT_EXTERN_MODULE(RNNativeTextViewManager, RCTViewManager)

RCT_EXPORT_VIEW_PROPERTY(text, NSString)
RCT_EXPORT_VIEW_PROPERTY(textColorString, NSString)

+ (BOOL)requiresMainQueueSetup { return YES; }

@end

Like this no TextView is shown at all. This is so because the height of the NativeTextView is 0. If I put a static fixed height to the style, the NativeTextView is getting rendered like expected. But what I want is a dynamic height which depends on the text length of course.
Tried to find a solution on the dev-documentation but found nothing really helpful. Missed I something? How would be a good and efficient way to calculate the height of this UITextView?


text:
Q: Android BottomNavigationView with Navigation Component issue I'm implementing BottomNavigationView integrated with Navigation Component, everything works perfectly, but I'm wondering how to make Fragments not being recreated while swiping between BottomNavigationView  icons.
It was possible with the usage of ViewPager by calling viewPager.setOffscreenPageLimit(n) where n is the number of fragments.
Is there any alternatives for viewPager.setOffscreenPageLimit(n) while using BottomNavigationView with Navigation Component


text:
Q: Flexible and fixed size. Make children pass size to parent? I am trying to make an interface that tries to do something very simple:
Prints a series of things in line and the last one is an scrollable (listview) that expands across all screen. It's making my life hell, however.
My problem is that the things it needs to print in line occupy don't adapt, I want them to "calculate and pass their size to the parent" so that the listview can be make to expand as much as possible WITHOUT eating the first elements on the screen or leaving them with unnecessary space.
Furthermore, the size of the firsts elements can change, they have a button that "dissects" into two.
This is more like my setup of widgets (and in parenthesis the class they are in):
Column(W1):
|Flexible(W1):
||Column(W2)  <= Actually, I created a listview now because some problems.
|||conditional column(WX*) (1 children or 2)
|Flexible(W1)
||Divider(W3)
||Flexible
|||Layoutparamsbuilder(W3)
||||listviewbuilder(W4)

*This was in another widget, but there is no reason for it. There are 3 elems to show in screen, the first option shows 1, and the other option disables that one and shows the other 2, they are part of a state(changes while looking at it). I created a new column for simplicity (adding them programatically to the W2 column could be kind of a mess, but if doing so solves the issue i will do it)
I think the mistake is in between W1 and W2. But removing the "flexible" out of W1 makes a mess. It doesn't print anything. I need W2 to show all his shit and then back off, but instead it occupies half the screen.
Now, being in a single line is not a necessity, and I tried a Grid, thinking that I would solve all my problems. Is seemed perfect, but not at all! That's the only reason why W2 is a column.
Sorry for the long post. I made a shitty painting in pain showing ""my interface"":
Also, I have another tiny, unimportant question: The listview is meant for showing some sort of a "table" with several fields. An example: It shows (name, age, email). If the window expands horizontally, each field grows. Is there any widget that calculates this and, instead, adds a different field (name, age, email, phone) ? Tables not only don't do this, but they also don't scroll on their own, and my second option was to make a listview of listviews, making my real problem(the question) even worse xdddd.
Thank you very much, you are amazing people :).

I add the basic structure of the code code:
Padding(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Flexible( child : Widget1()),
          Expanded (child: Widget2())
          )],),

Widget1:
Container(
      decoration: BoxDecoration( border: Border.all(color: Colors.green)),
      child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
          child: Column(
            children: [
              Container(
                alignment: Alignment.topLeft,
                child: Text(   ),
              ),
              SizedBox(height: 5),
              Consumer>> (ListView(children: textfiel, row, row)
              ])
   Widger2:
Column(
          children : [
            Divider(), Row(), Divider(), Text(), Sizedbox(), Flexible(LayoutBuilder(Sizedbox(height: contrains.height, child: Listview(rows....)

A: if I understand you correctly, you need to use Expanded Widget and pass the ListView or whatever your Scrollable widget as a child.
Check out the links below:
https://api.flutter.dev/flutter/widgets/Expanded-class.html
https://www.youtube.com/watch?v=_rnZaagadyo
If you still have this problem, you can share your code to make the problem more clear.


text:
Q: Auto Send feature in Custom Keyboard Extension iOS Swift I've implemented Custom Keyboard Extension in my app, and have a UITableView in it. When I click on the cell of the UITableView which has a text label, I want the text to be able to Auto Send (some apps support AutoSend i.e. SnapChat, Tiktok, Safari).
I searched through UITextDocumentProxy, but wasn't able to achieve the above scenario.
Thanks in advance!

A: Some Auto Sending apps like SnapChat, Tiktok, Safari I have done through this function, when you want to send a text automatically after you want to send text
then call
textDocumentProxy?.return()

extension
extension UIKeyInput {
    func `return`() -> Void{
         insertText("\n")
    }
}


text:
Q: AjaxFileUpload OnClientUploadComplete & OnUploadComplete I'm working on an application and I have a AjaxFileUpload control.  I set OnClientUploadComplete  to a javascript function and OnUploadComplete to a method in my code behind(.cs).
In which order do these run?  Or do they run in parallel?
In my OnUploadComplete i'm moving images from a tmp folder to a CDN.  An in my OnClientUploadComplete i'm retrieving a new list of images, however, it doesn't seem to get the updated list unless i refresh the entire page.  That is why i'm assuming these methods run in parallel.
Is there a way to get the OnClientUploadComplete to run AFTER the OnUploadComplete is done?

A: You can use setTimeout() method in OnClientUploadComplete. So the method will be execute after completion of time provided in setTimeout() meanwhile OnUploadComplete will execute.


text:
Q: Install a Bootloader to Boot Another Partition I currently have an external hard drive that is partitioned to 3 parts:

*

*dev/sdb1 - Files

*dev/sdb2 - Kubuntu 11.10

*dev/sdb3 - linux-swap

I'm using GRUB on my built-in HDD in order to boot dev/sdb2. I might bring this external hard drive with me when I'm traveling. Is it possible for me to install a bootloader onto this drive to boot Kubuntu 11.10 so I don't have to carry my computer with me? If so, how? I appreciate any suggestions or answers.

A: Boot up your Kubuntu, and install grub in it (in /dev/sdb). Then go to /etc/fstab and edit the file so that all sdb's are sda.


text:
Q: How to use *.lib file in C# application? So I have some .lib file (generated like this one) How to use it from my C# WPF application?

A: When you want to use native libraries from C# you won't need a .lib file. The way this is handled in .NET is by using Platform Invoke (P/Invoke). I suggest you follow the tutorial on MSDN, it will get you started:

Platform Invoke Tutorial

If you want to generate a wrapper you might want to have a look at the P/Invoke Interop Assistant on CodePlex. Please note that this tool works on the original C/C++ code. Using a .dll file to create a wrapper is not feasible because native DLLs don't store the signature of the exported functions (as described in this thread) and a lib file will store the signature in a compiler specific way.


text:
Q: How to target the chrome browser for Mac only? Hi I have cross browser issue with chrome in mac,I have a css class to fix the issue but thing is how would i target it to chrome that to only in mac?
Many Thanks in Advance!!!

A: Use JavaScript something like below.
if (navigator.userAgent.match(/Macintosh/) && navigator.userAgent.match(/Chrome/))


text:
Q: Elasticsearch install localhost:9200 can't connect, and no log files to review Nevermind L and K, E is not functioning.
So what gives? What does it take to get a functioning elasticsearch install?
============= Installation hardware:
Raspberry Pi 3+
Raspbian GNU/Linux 9 (stretch)

============= Installed via apt:
sudo apt-get install elasticsearch

Setting up libelasticsearch1.7-java (1.7.5-1) ...
Setting up elasticsearch (1.7.5-1) ...

I went to change /etc/elasticsearch/elasticsearch.yml as the installation instructions say.
All the lines were commented so I uncommented 3 lines and added config info per the instructions:
network.host: 0.0.0.0
http.port: 9200
path.logs: /var/log/elasticsearch
path.data: /var/lib/elasticsearch

============= Elasticsearch is running as a service, according to the install:
$ sudo service elasticsearch status
● elasticsearch.service - LSB: Starts elasticsearch
Loaded: loaded (/etc/init.d/elasticsearch; generated; vendor preset: enabled)
Active: active (exited) since Tue 2019-05-21 02:53:17 PDT; 2min 52s ago
Docs: man:systemd-sysv-generator(8)
Process: 21421 ExecStop=/etc/init.d/elasticsearch stop (code=exited, status=0/SUCCESS)
Process: 21455 ExecStart=/etc/init.d/elasticsearch start (code=exited, status=0/SUCCESS)

May 21 02:53:17 xxxx systemd[1]: Starting LSB: Starts elasticsearch...
May 21 02:53:17 xxxx systemd[1]: Started LSB: Starts elasticsearch.

============= But it's not listed in the active connections:
$ sudo netstat -natp
[PRIVATE DATA]

=============  Testing the installation:
$ curl http://localhost:9200
curl: (7) Failed to connect to localhost port 9200: Connection refused

There are no log files:
$ sudo ls -l /var/{log,lib}/elasticsearch
/var/lib/elasticsearch:
total 0

/var/log/elasticsearch:
total 0

Without any logs, there's no way to track down anything. And setting the log.path did not create any log files.


text:
Q: array inside hidden element javascript I'm an absolute javascript noob and am using ASP.net, in my code behind aspx.cs file, I declared the body of the web document using html tags as seen below...
public void CreateForm(string passengerType, int passengerCount)
    {
        for (int i = 1; i <= passengerCount; i++)
        {
            Response.Write("
");
            Response.Write("
");
               ...
            Response.Write("<input id=MiddleName" + passengerType +i                + "type=text />	");
                ...
        }
    }

And when I try to call on the ID of an element, which is in id="MiddleName[passengerType][i]"
I can't find it, I need to get the value of that textbox and pass that into another page, Somebody suggested to me that I use javascript and try to store these elements inside a hidden element and add that to an array declared in javascript, I didn't get a single thing he said, any alternative suggestions?

A: Maybe:
Response.Write("<input id='MiddleName" + passengerType + i + "' type=text />	");

A: If you view source on your page you will probably see:
<input id=MiddleNameXYZ1>
<input id=MiddleNameXYZ2>
<input id=MiddleNameXYZ3>

In other words, your coding is not formatting to what you think it should be.

A: Check tho source of your generated documents to see what id is generated as the output of your code. Bear in mind that asp.net control are rendered with different ids then server side  ID. To get it in your javascript function you need to do something like that:
function getElement(){
    var myEl = document.getElementByID('<%=ControlID.ClientID%>')
}

where ControlID is serverside ID of you control.
In your particular case ControlID might not be avalaible however, therefore it might be neccesary to create a property in the page class which will contain the control you add - for instance:
class MyPage:Page{
    TextBox TextBoxName {get;set;}

    public void CreateForm(string passengerType, int passengerCount)
    {
        TextBoxName = new TextBox();
        this.Controls.Add(TextBoxName);
    }

}

I am aware that this code might not match your current implemantation, but in general it should work this way.

A: try below
public void CreateForm(string passengerType, int passengerCount)
{
    StringBuilder sb = new StringBuilder();
    sb.AppendLine("
");
    for (int i = 1; i <= passengerCount; i++)
    {
        sb.AppendLine("
");
        sb.AppendLine("<input id='MiddleName" + passengerType + i + "' type='text' />	");
    }
    sb.AppendLine("
");
    Response.Write(sb.ToString());
}

A: On server-side you can create a list of all created ids, and output them as value to an hidden field.
public void CreateForm(string passengerType, int passengerCount)
{
    /* List to hold id values */
    List<string> ids = new List<string>();

    for (int i = 1; i <= passengerCount; i++)
    {
        Response.Write("
");
        Response.Write("
");
        //   ...
        Response.Write("<input id=MiddleName" + passengerType +i+ "type=text />	");
        //    ...

        /* Add newly created input id to list */
        ids.Add("MiddleName" + passengerType +i);
    }

    /* Output the ids collection to hidden field value */
    Response.Write("<input type='hidden' id='hiddenElement' value='" + string.Join(",", ids.ToArray()) + "'></input>");
}

On client side javascript you can get all these ids from the hidden element, loop through them and get all created input elements
/* Get all ids from hidden element */
var ids = document.getElementById('hiddenElement').value.split(',');
/* Loop through all ids */
for (var i = 0; i < ids.length; i++) {
    var element = document.getElementById(ids[0]);
    // do something
}


text:
Q: R DBI issue with accessing list fields of a remote table I am trying to get the fields of a table in an Arctic database. For that I've been successful at creating a jdbcConnection object which is of class "JDBCConnection", but once I write the following code to get the fields of the AR_LOT table (dbListFields comes from DBI package),
dbListFields(jdbcConnection, name = Id(schema = "ARCTIC", table = "AR_LOT"))

I get the following error message.

Error in dbSendQuery(conn, paste("SELECT * FROM ", dbQuoteIdentifier(conn,  :
Unable to retrieve JDBC result set
JDBC ERROR: ORA-00933: SQL command not properly ended
Statement: SELECT * FROM  "ARCTIC"."AR_LOT" LIMIT 0

I also tried with RJDBC's function dbGetFields, but I'm also running into an error.

Error in .jcall(md, "Ljava/sql/ResultSet;", "getColumns", .jnull("java/lang/String"),  :
method getColumns with signature (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/sql/ResultSet; not found

The weird thing is that dbReadTable from DBI package works just fine.
Can anyone please help me understand these error messages a little more clearly? Thanks in advance


text:
Q: Can I use arrays of WinForm controls without VS getting its panties in a twist? I have a grid of labels. In order to access them in a programmatically sensible manner, I changed them from:
gridLabel1
gridLabel2
...
gridLabelN

To:
gridLabel[0]
gridLabel[1]
...
gridLabel[N-1]

But now the designer is complaining that

The variable 'gridLabel' is either undeclared or was never assigned.

Despite the fact that I also changed this:
private System.Windows.Forms.Label gridLabel1 = new System.Windows.Forms.Label;
private System.Windows.Forms.Label gridLabel2 = new System.Windows.Forms.Label;
...
private System.Windows.Forms.Label gridLabelN = new System.Windows.Forms.Label;

To:
private System.Windows.Forms.Label[] gridLabel = new System.Windows.Forms.Label[N];

What have I missed?

A: Don't mess around with generated code yourself. The designer.cs file is supposed to be managed by the forms-designer itself, not by the user. In particular, it's easy to test that the designer does not tolerate the procedure you appear to be following:

*

*Declaring a field of an array of controls to the designer file.

*Using this field to populate the form's control-collection by modifying the generated InitializeComponent method.

When I do so, I get the same error that you do.
The usual solution for this sort of requirement  is to use a programmatic technique to add a number of controls to a parent-control's control-collection. Ideally, create your own user-control that can hold a number of Labels (which it populates programmatically). Then, you can use this control on your form with full designer support.
EDIT:
For example (sketch only, without the user-control), add a FlowLayoutPanel to the form via the designer.
Then change the form's constructor to:
public MyForm()
{
    InitializeComponent();

    var labels = Enumerable.Range(0, 100)
                           .Select(i => new Label { Text = i.ToString() })
                           .ToArray();

    flowLayoutPanel1.Controls.AddRange(labels);
}

Obviously, such a solution may not be appropriate if you don't want the labels organized in a flow-layout.

A: Create the array of labels after the InitializeComponent call, and populate it with the designer generated instances, like so:
Label[] labels;

MyControl() {
  InitializeComponent();
  labels = new[] { label1, label2, label3 };
}

This will let you keep designer functionality and access them sequentially.

A: Are you trying to dynamicaly create labels? Or are you trying to access multiple static labels?
For first case, you are left with manual creation and manupulation outside the designer. Just like Ani proposes.
In second case, you can get controls based on name from Form.Controls collection. This name can contain index of the labels. Then you can crete either method or indexer to return specific label based on index.


text:
Q: How to add Firebase Cloud Messaging into android library module I'm trying integrate Firebase Cloud Messaging, specifically for android push notifications, into a my own library module so I can easily implement this into any app without having to touch Firebase. I have successfully integrated it initializing the Firebase Messaging SDK dynamically inside my library by using FirebaseOptions.Builder as well it generated a push token.
BTW I am initializing FirebaseApp in my library and calling it in the app MainActivity.java
But whenever I test sending my own push notification while the app is in the foreground I get
Default FirebaseApp is not initialized in this process. Make sure to call FirebaseApp.initializeApp(Context)

From the Error Output it seems to be calling FirebaseApp instance in the MessagingAnalytics class to log performance before it calls onMessageRecieved.
As well no notification shows up on the phone when sending a Notification while the app is in the background.
I want my library module to handle everything to do with Push Notifications, I have also created a MyMessagingService in the library module and added the appropriate Service in the manifest of the library module.
If anyone has done this before with FCM in a library or knows how to fix these crashes please let me know.
EDIT
I am building the FirebaseApp manually without google-service.json inside the module. Like this:
FirebaseApp.initializeApp(context, new FirebaseOptions.Builder().setApplicationId(applicationID).setApiKey(apiKey).setGcmSenderId(senderID).setProjectId(projectID).build());


text:
Q: Can I retrieve limited dataset from a CSV file in Azure Data Lake U-SQL? Can I filter data loaded from a CSV File using `U-SQL's EXTRACT? I know we can limit the data using the where condition in the select after the EXTRACT. But, I want to filter it during the use of the 'EXTRACT'
I have huge CSV file. I don't want to load all of it into the first dataset itself.
e.g.
I have lot of auto claims in the dataset. I want to filter it while I 'EXTRACT' it based on a date in the dataset.

A: The answer is yes. However only column pruning can be pushed into the extractors. Since there is no semantics assigned to the data before you extract it with the Csv extractor, filters will be applied on the generated rowset. There are many examples out there that show you how to do so. Here is an example from one of the hands-on-labs.

A: Yes you can filter data loaded from csv file. You can do something like this:
 @log =
     EXTRACT UserId          int,
             StartDate       DateTime,
             Location        string,
              ....
              ....
             Url             string
     FROM "/Samples/Data/Log.csv"
     USING Extractors.csv();

 @result =
     SELECT Location, Url, StartDate
     FROM @log
     WHERE StartDate >= DateTime.Parse("2017/01/6") AND StartDate <= DateTime.Parse("2018/06/08");

 OUTPUT @result
 TO "/output/cleanlog.csv"
 USING Outputters.Csv();


text:
Q: React JS min Script Link not working Using IntelliJ Idea and Created an index.htm file
I am just trying to include the below links and run the code on server end
Nothing is getting rendered on the screen :

    <title>Live Link</title>

This older versions link work, but new version links are not working.
https://stackoverflow.com/a/33963992/5078763

Getting below Error in Console.log:

    babel.min.js:5 Uncaught SyntaxError: Invalid regular expression: Range out of order in character class
    at new RegExp (<anonymous>)
    at Object.<anonymous> (babel.min.js:5)
    at t (babel.min.js:1)
    at Object.t.__esModule (babel.min.js:19)
    at t (babel.min.js:1)
    at Object.<anonymous> (babel.min.js:2)
    at t (babel.min.js:1)
    at Object.e.exports (babel.min.js:1)
    at t (babel.min.js:1)
    at Object.e.exports.version (babel.min.js:1)
(anonymous) @ babel.min.js:5
t @ babel.min.js:1
t.__esModule @ babel.min.js:19
t @ babel.min.js:1
(anonymous) @ babel.min.js:2
t @ babel.min.js:1
e.exports @ babel.min.js:1
t @ babel.min.js:1
e.exports.version @ babel.min.js:1
t @ babel.min.js:1
t.__esModule @ babel.min.js:16
t @ babel.min.js:1
t.__esModule @ babel.min.js:11
t @ babel.min.js:1
(anonymous) @ babel.min.js:2
t.__esModule @ babel.min.js:2
t @ babel.min.js:1
t.__esModule @ babel.min.js:10
t @ babel.min.js:1
t.__esModule @ babel.min.js:14
t @ babel.min.js:1
t.__esModule @ babel.min.js:1
t @ babel.min.js:1
(anonymous) @ babel.min.js:1
(anonymous) @ babel.min.js:1
(anonymous) @ babel.min.js:1
(anonymous) @ babel.min.js:1
raven.min.js:2

A: The minified babel.min.js contains utf-8 encoded strings. You can make your example work by putting a <meta charset="utf-8"> inside your .


text:
Q: MapBox navigation lags while removing trail route When progress changes I calculate the route again from user current location and current step end point then add the route again. So it's basically removing the previous route and adding again new trail removed route. This works fine but sometimes it lags and trail does not get removed for a  second. I think that can be optimised. Here is the code for it
class MapRouteProgressChangeListener(private val mapRoute: NavigationMapRoute) :
    ProgressChangeListener {
    private val executorService = Executors.newCachedThreadPool()
    private val handler = Handler(Looper.getMainLooper())
    override fun onProgressChange(location: Location, routeProgress: RouteProgress) {
        val directionsRoutes = mapRoute.retrieveDirectionsRoutes()
        val primaryRouteIndex = mapRoute.retrievePrimaryRouteIndex()
        executorService.execute {
            val newRoute = getNewRoute(routeProgress, location)
            handler.postDelayed({
                addNewRoute(newRoute, directionsRoutes, primaryRouteIndex)
                mapRoute.addUpcomingManeuverArrow(routeProgress)
            }, 1350)
        }
    }

    private fun addNewRoute(
        currentRoute: DirectionsRoute?, directionsRoutes: List<DirectionsRoute>,
        primaryRouteIndex: Int
    ) {
        if (isANewRoute(currentRoute, directionsRoutes, primaryRouteIndex)) {
            mapRoute.addRoute(currentRoute)
        }
    }

    private fun getNewRoute(progress: RouteProgress, loc: Location): DirectionsRoute {
        val step = progress.currentLegProgress().currentStep()
        if (step.geometry() == null) {
            return progress.directionsRoute()
        }
        val start = Point.fromLngLat(loc.longitude, loc.latitude)
        val points = PolylineUtils.decode(step.geometry()!!, 5)
        val end = points.last()
        if (start.latitude() == end.latitude() && start.longitude() == end.longitude()) {
            return progress.directionsRoute()
        }
        step.geometry()?.let {
            val newGeoMetre = getSlicedLine(it, start, end)
            val polyline = progress.directionsRoute()
            val newStep = polyline.legs()?.get(progress.legIndex())?.steps()?.get(
                progress.currentLegProgress()
                    .stepIndex()
            )?.toBuilder()?.geometry(newGeoMetre)?.build()
            val newRoute = updatePolyLine(polyline, start)
            newRoute?.let { route ->
                route.legs()?.get(progress.legIndex())?.steps()?.set(
                    progress.currentLegProgress().stepIndex(), newStep
                )
                return newRoute
            }
        }
        return progress.directionsRoute()
    }

    private fun updatePolyLine(polyline: DirectionsRoute?, start: Point): DirectionsRoute? {
        polyline?.geometry()?.let {
            val points = PolylineUtils.decode(
                it, 5
            )
            val newGeoRetry = getSlicedLine(start, points)
            return polyline.toBuilder().geometry(newGeoRetry).build()
        }
        return null
    }

    private fun getSlicedLine(polyline: String, start: Point, end: Point): String {
        val points = PolylineUtils.decode(polyline, 5)
        val finalLine = TurfMisc.lineSlice(start, end, LineString.fromLngLats(points))
        return finalLine.toPolyline(5)
    }

    private fun getSlicedLine(start: Point, points: List<Point>): String {
        val finalLine =
            TurfMisc.lineSlice(start, points.last(), LineString.fromLngLats(points))
        return finalLine.toPolyline(5)
    }

    private fun isANewRoute(
        currentRoute: DirectionsRoute?, directionsRoutes: List<DirectionsRoute>,
        primaryRouteIndex: Int
    ): Boolean {
        val noRoutes = directionsRoutes.isEmpty()
        return noRoutes || currentRoute != directionsRoutes[primaryRouteIndex]
    }
}


text:
Q: is there any guidance about how much traces should be available in released software which can still help in debugging majority of issues? I am trying to develop a brand new multitasking software. This software will have multiple components and they will/can talk each other to get system working. Before release of this software to end users, we will run many round of validation to ensure good quality. During validation cycle our developers will be mainly relying on collected logs to troubleshoot and diagnose the issues. Since our debugging capability and time to market will be heavily dependent on collected traces, we will like to have as much as information available to developer at first hand. On the other hand if we add a lot of traces it will slow down our software and can eat many precious resources like CPU cycles etc. we will like to keep tracing/logging optimum. To solve this problem we want to provide guidance to our developer on judiciously using different log levels  e.g. debug, info, warning, error etc.  Here no of traces in debug > info > warning > error. we will like to start our validation cycle for software using say "info" level and gradually go to "warning" and "error" as software matures. Developers tend to put as much as traces they can so that they have all the information available. But as we will have multi-component system, total number of traces becomes very high and unmanageable leading to big log size, s/w performance issue etc. We want to give a generic guidance like if you have total 100 logs/traces for your component then say  100 should be available in debug, 70 should be available in Info, g", 10 should be available in error etc. So that we get a good quality of trace in first hand as well we keep control on total log/trace size. Is there any guidance/standard available, which we should use?

A: You're unlikely to find any standard guides containing information about how to efficiently or effectively log. The fact is that every application has different requirements with regards to latency. There are some tricks you can employ to reduce your overhead. The points I'm mentioning here come from years of experience with highly concurrent software for which logging was a real bottleneck.
Define Semantics and Make Them Configurable
Your post only gets as deep as describing some sort of hierarchy of log message types. Your question seems to be about whether there are best practices for limiting the overhead of these types. There are not, and this is because everybody needs different information at different times.
Let's assume your hierarchy of DEBUG < INFO < WARNING < ERROR < FATAL. (I introduced FATAL because you need one.) There are some best practices. They are best practices because they are common sense, not because an authority said so.

*

*FATAL messages correspond to events that are going to terminate your software. You always log these, no matter what. This behavior hopefully obviously does not need to be configurable.

*ERROR messages are things that have prevented your software from making expected progress, and it is unlikely that someone would have noticed.

*WARNING messages correspond to unexpected events, possibly events that prevented something from happening, but it is likely someone would have noticed.
The distinction between visibility is the real difference between WARNING and ERROR. ERROR is higher priority specifically because it is not visible. WARNING has a higher probability of being brought to your attention.

*

*INFO messages are purely informational, but their utility is largely for users of the software (as opposed to developers). These messages may include information about module start-up, version informations, etc. They are useful for understanding how a system is configured and its runtime state. They generally shouldn't be introduced as part of common runtime behavior.

*DEBUG messages are also purely informational, but their utility is for developers. When DEBUG messages are enabled, you want to log everything, always.
If you treat this as a hierarchy, your configuration lets you specify the minimum log level. The alternative is to treat them as options (i.e. "I want to log ERROR and INFO"). Either way, it may be useful to have different settings for different levels. But regardless, make them configurable.
Regarding DEBUG messages, it can be beneficial to break these down further in modular software. If you're concerned about DEBUG traces at customer sites including too much information, break down DEBUG messages into a per-component thing. Allow configuring e.g. DEBUG.subsystemA, DEBUG.subsystemB, etc.
Use a Central Logger
At some point in your software, you need to actually put logs in a place. This should be done by a central service (library component, subsystem, whatever terminology makes sense for you) in your software.
Why centralize this? Many of the tricks you can employ to reduce the overhead of logging rely on being able to coordinate between multiple threads / tasks / whatever. It's easier to do this when log management is centralized. (Other approaches may end up requiring significant locking overhead, which sort of defeats the purpose.)
Reduce Memory Allocation
Naïve approaches to logging tend to be extremely difficult on memory. Ephemeral log entries are constantly being allocated and freed, strings are being created and concatenated all the time, etc. Memory allocation isn't cheap, so we should start there.

*

*Define a maximum length of a log line and pre-allocate your log buffers. Much of the overhead of a naive logging solution comes from allocating and freeing memory to store log entries. In fact, log entries tend to be pretty ephemeral. If you can define a maximum length of a log entry, you can preallocate them, and use a pool of them to reduce allocation overhead through reuse.

*Many languages have immutable strings, and operations like concatenation that are common in logging end up having high overhead due to extra allocation. Use string building interfaces that do not have the overhead of allocating new objects every time a string operation happens.

*Somewhat relatedly, many languages have format specifiers for constructing strings. Format specifiers have high cost because format strings must be parsed at runtime, every time. Instead of using format specifiers, attempt to use a string building interface directly to avoid format specifier overhead.
Rate Limit
When you've reduced the allocation overhead, you may still find that the overhead is prohibitive in some cases. If you've used a log entry pool, you will have an easy means to rate limit. If you have not (you should have, it's a good idea), you should consider rate limiting by itself.
With a log entry pool, when the pool is empty, you simply refuse to service new log entries. This effectively limits the rate. Otherwise, you'll need to define some kind of counter and use some kind of aging mechanism to determine the relevant immediate rate of messages you are logging.
Rate limiting should happen before format strings are parsed and before you had to do any allocations for things. Otherwise, you're paying additional overhead to not do anything.
Batch Log Items
Queue your log items in a batch. This should be what you're already doing if you've created a centralized logging service in your software. Batching increases log latency, but reduces the immediate I/O overhead when your output is to a disk.
Make your flush interval configurable. Make your batch size configurable.
Queue Items Asynchronously
If you're batching items, it's clearly already asynchronous, but just to spell it out: a log request for anything but a FATAL-level log item is a request that can wait a little bit to be logged. Much of the overhead of logging is due to I/O overhead, especially when the log destination is a disk or network endpoint.
Provide Output Options
Logs don't have to go to files. They can go to network endpoints, files, or shared memory regions. Allow your users to define where logs go, and provide them with utilities or libraries to receive log items over those formats.
Make Custom Trace Formats
Sometimes logging is too heavyweight for the task at hand. In some cases, custom trace formats can allow you to log where you were unable to before.
In our software at Fastly, threads take snapshots of their execution history and put them in a ring buffer that is exposed via tmpfs. These snapshots are strategically placed around locks and in a few key places in our main state machine.
The ring buffer is exposed to the software via a shared mapped memory region, and since it lives on a Linux tmpfs, all operations remain in-memory. These traces are always on, but require minimal overhead. By implementing it this way, we are able to get the level of debugging information in our production deployments that allows us to debug race conditions, deadlocks, and other problems.

The idea behind these sorts of optimizations is that it reduces the need for you to discard error messages in the first place. If you log appropriately and judiciously, and your logging infrastructure is properly designed, you will never be want for more information.

A: The standard practice is to make the logging level configurable at run time.  This is done by using a logging framework such as winston for javascript or an slf4j implementation for java.
Given that, I would let you developers work out on their own how much debug & trace information they need.  It's also usually pretty clear when an error needs to be logged.  So the only guidance / discussion we have is around how much info should be logged at the info level.  I would let the developers use their best judgement & then adjust as necessary, with the general guidance that stack traces for handled errors or data dumps should be done at debug or trace levels only.
When the system is deployed, the log level should be set to info or higher.  If an issue arises on a deployed system, the logging level can be increased temporarily to debug (or possibly higher) to allow the issue to be investigated.
Developers may run development systems with a debug or trace log level as the default.
During your validation cycle you can turn on debug logs as necessary to capture information.


text:
Q: Screen does not lock on suspend I have recently updated to 20.04 and now when I suspend, either waiting for a long time, closing the lid or manually suspending, the screen does not automatically lock. I've tried setting the 'lock on suspend' in the setting but nothing changed.
I am running lightdm with unity greeter, if that helps.

A: For anyone who has come looking for a solution to a similar problem, here's how I solved it.
Credit to pszafer here: https://bbs.archlinux.org/viewtopic.php?id=191797
So it turns out that indeed it is due to lightdm that ubuntu was disabling the automatic lock. To get around thata I wrote the following script that calls dm-tool to lock the screen, saved in the home directory:
#!/bin/sh
export XDG_SEAT_PATH="/org/freedesktop/DisplayManager/Seat0"
dm-tool lock

Note that you Seat0 might be different for you. You can check that by running
dm-tool list-seats
Then I put this script saved at /etc/systemd/system/dmlock.service:
[Unit]
Description=DM Lock before sleep
Before=sleep.target

[Service]
ExecStart=/home/path/to/previous/script

[Install]
WantedBy=sleep.target

Then you need to enable the service using
systemctl enable dmlock.service
You can also test if it is working with
systemctl start dmlock.service


text:
Q: R: It is possible to modify "[" and "[[" to introduce Python-like negative indexing? I want an easy way to access the last values of objects. I have implemented a function that allows for Python-like negative indexing (count-backwards-and-keep-only-those-elements instead of R's remove-those-elements-and-keep-all-other-elements). There are some questions about this, but no one attempted to do this:

*

*How to access the last value in a vector?

*Getting the last n elements of a vector. Is there a better way than using the length() function?
Basically, I want to redefine [ and [[, so that one can user a special operator (e.g. _) to use Python-like indexing. For instance, like this:
iris[1, ] #first row
iris[-1, ] #everything but first row
iris[_1, ] #last row, equivalent to tail(iris, 1)
iris[, _1] #last column, equivalent to iris[ncol(iris)]

Is it possible? I know it is possible to redefine e.g. + to introduce character concatenation like other languages have (see this answer).
In case it's not possible, here's my workaround function:
extract_last = function(x, margin_1, margin_2, drop = FALSE) {
  #check types
  if (!(is.vector(x) || is.matrix(x) || is.data.frame(x))) stop("x was an unsupported type (not a vector, matrix or data.frame)!")

  #vector
  if (is.vector(x)) return(rev(x)[margin_1])

  #get dims
  x_dims = dim(x)

  #make indices
  if (missing("margin_1")) {
    margin_1 = 1:x_dims[1]
  } else {
    margin_1 = (x_dims[1] + 1) - margin_1
  }
  if (missing("margin_2")) {
    margin_2 = 1:x_dims[2]
  } else {
    margin_2 = (x_dims[2] + 1) - margin_2
  }

  #subset
  return(x[margin_1, margin_2, drop = drop])
}

#tests
extract_last(iris, 1) == tail(iris, 1)
extract_last(iris, 10:1) == tail(iris, 10)
extract_last(iris, , 1) == iris[5]
extract_last(iris, , 2:1) == iris[4:5]
extract_last(iris, 10:1, 1) == iris[141:150, 5, drop = FALSE]


text:
Q: How can i control the numbers in a number textbox  according the incremental and decremental changes done in another textbox What i need is when the room quantity is set to 1, the adult max range be 3 and min range be 1. And when room quantity is set to 2, the adult max range be 6 and min range be 1. Can someone plz help me with javascript or jquery that is needed to solve this problem.

A: You can use some functionality of this example. It is not a polished solution, it's just the example of how you can manipulate max property of input element.

$("#roomsInput").change(function() {
 var maxAdults;
  var roomsSelected = $(this).val();
  if (roomsSelected == 1) {
   maxAdults = 3;
  } else if (roomsSelected == 2) {
   maxAdults = 6;
  } else {
   maxAdults = 10;
  }
  var adultsInput = $("#adultsInput");
  if (adultsInput.val() > maxAdults) {
   adultsInput.val(maxAdults);
  }
  adultsInput.prop("max", maxAdults);
});

  Rooms
  <input type="number" id="roomsInput" min="1" max="3">

  Adults
  <input type="number" id="adultsInput" min="0" max="10">

  Kids
  <input type="number" id="kidsInput" min="0" max="10">


text:
Q: Graphical representation of HTML table data using High charts I am trying to display the data in HTML table in graphical form using High Charts. When I use all the data from the table I am able to render the charts. I want to use only  some part of data from my table (some columns data) to render a chart. Can anyone please tell me how  to do this. If you have snippets please provide them. It will be helpful for me.

A: All 'docs' are included inline to the data.src.js module:

*

*http://code.highcharts.com/modules/data.src.js
For now only startRow/endRow/startColumn/endColumn options are supported:

table : String|HTMLElement
A HTML table or the id of such to be parsed as input data. Related options ara startRow, endRow, startColumn and endColumn to delimit what part of the table is used.


text:
Q: WIX: How to get value of selected feature of selectiontree to display on summary page I want to write summary page with selected feature and installation location. I am using ADDLOCAL to display selected feature but it will work if I use command line with addlocal to select the feature but if I use UI then it does not display selected feature.
<Control Id="InstalledFeaturesText" Type="Text" X="25" Y="215" Height="10" Width="100" Text="[ADDLOCAL]"/>

even I tried
<SetProperty Id="FEATURELIST" Value="[ADDLOCAL]" After="CostFinalize"/>
<Control Id="InstalledFeaturesText" Type="Text" X="25" Y="215" Height="10" Width="100" Text="[FEATURELIST]"/>

Is there any other way to do that ?
Please help me.