text:
Q: How do I move JQuery draggable element without mouse Is there a different way of JQuery draggable element moving?
Think yourself as a spammer.

A: it should not be such a big deal, only calling the correct sequence of: .mousedown(), .mousemove() and .mouseup()
as the official documentation says (http://api.jquery.com/mousedown/):

Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.

the same is true for the other two jquery function descriptions


text:
Q: Как распарсить конструкцию json в react native Не давно начал изучение react native.
И столкнулся с проблемой.
Пытаюсь распарсить https://www.cryptocompare.com/api/data/coinlist
И получить ссылки на картинки из раздела Data
Сам раздел я получил
dataImages: Array(responseJson.Data)
console.log(this.state.dataImages[0])

Выглядит так:
"42": {
"Id": "4321",
"Url": "/coins/42/overview",
"ImageUrl": "/media/12318415/42.png",
"Name": "42",
"Symbol": "42",
"CoinName": "42 Coin",
"FullName": "42 Coin (42)",
"Algorithm": "Scrypt",
"ProofType": "PoW/PoS",
"FullyPremined": "0",
"TotalCoinSupply": "42",
"PreMinedValue": "N/A",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "34",
"Sponsored": false
},
"300": {
"Id": "749869",
"Url": "/coins/300/overview",
"ImageUrl": "/media/27010595/300.png",
"Name": "300",
"Symbol": "300",
"CoinName": "300 token",
"FullName": "300 token (300)",
"Algorithm": "N/A",
"ProofType": "N/A",
"FullyPremined": "0",
"TotalCoinSupply": "300",
"PreMinedValue": "N/A",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "2212",
"Sponsored": false
},...

Не смотря на то что я добавил '[0]'
Могу получить элемент если после поставлю '.DOGE' (имя елемента)
Но нужно получить из всех элементов поле ImageUrl или Name
Подскажите пожалуйста что я не так делаю.

A: Вот таким вот образом я прошёлся по всем элементам
for (var key in this.state.dataImages) {
            if (key == coinKey) {
                urlImage = `${this.state.dataImages[key].ImageUrl}`
            }
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: how can I indicate selection in a clickable FrameLayout? I am trying to implement a clickable composite view.  The composite view is implemented using a FrameLayout which contains an inflated set of child views.  If the user taps anywhere in the FrameLayout, I would like to flash the view as if it was selected, and then perform some action.
Here is my current code:
private void fillFrameLayout(FrameLayout frame) {
    View disclosureItem = getLayoutInflater().inflate(R.layout.disclosure_item, frame);
    frame.setClickable(true);
    frame.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
            // Do something
        }
    });
}

Can someone please tell me how I can provide some visible feedback to the user when they tap the frame?  IE: select the frame in the same way that selection appears in a list or grid view.
Thanks.

A: You could define a background drawable with multiple drawables:
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"
      android:state_window_focused="true"
      android:drawable="@drawable/bg_selected" />

<item android:state_focused="true"
      android:state_window_focused="true"
      android:drawable="@drawable/bg_selected" />

<item android:state_selected="true"
      android:state_window_focused="true"
      android:drawable="@drawable/bg_selected />

<item android:drawable="@drawable/bg" />

In your layout, add this drawable as a background drawable:
<FrameLayout
    ...
    android:background="@color/bg_drawable" >

I hope this is what you meant?


text:
Q: toDataURL() small screens, small saved image I have created a web application which uses an HTML5 canvas element to allow users to draw in various shapes, colors, line widths. They can also upload an image, have it drawn onto the canvas and then draw on top of that, as a way to annotate their images.
My challenge is that I am using .toDataURL() to get the entire contents of the canvas saved as an image. As I understand, though, this can only capture the size of the canvas. On smaller devices (phones), the image which is saved, ends up quite small dimensions. Here's what I am doing to get what is on the canvas:
var image = document.getElementById("drawingCanvas").toDataURL("image/jpeg", 1.0);
image = image.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '');
Is there some way to set up my canvas to be able to save larger images, even if the size of the canvas is quite small, due to the device?

A: Sure...

*

*Save the commands used to create the client's drawing.

*Create a larger in-memory canvas with document.createElement.

*drawImage a full-sized image to the canvas.

*context.scale the canvas.

*Re-issue the drawing commands.

*Export the enlarged canvas with .toDataURL.

Thanks to context.scale you don't have to change any of the coordinates of the drawing commands.
...and alternatively...
You could eliminate step#1 if you're willing to downgrade the drawings to allow some "jaggies". Do this by using CSS to overlay a canvas on top of the client's img. That way the client's drawings are already isolated on the original canvas. Then your procedure simplifies to:

*

*Create a larger in-memory canvas with document.createElement. Make sure the larger canvas has the same aspect ratio as the original canvas.

*drawImage a full-sized image to the canvas.

*drawImage the original smaller canvas to the larger canvas. You can use the extended version of drawImage to simultaneously scale the client's drawings: context.drawImage(originalCanvas, 0, 0, originalCanvas.width, originalCanvas.height, 0, 0, largerCanvas.width, largerCanvas.height). Yes, the image source for drawImage can be another canvas. ;-)

*Export the enlarged canvas with .toDataURL.


text:
Q: Angular torque and velocity on different children of same parent This is my 3d object.
Target
  |-- Body
  |-- Label

Body is a 3d capsule
Label is a text field
I want this object to hang around in space and get knocked away when something collides with it. But i want the whole object, Target, to move away from the collision with the normal physical simulation. I dont want the body to move in its local space. However the rotational force (angular torque) should only affect the Body and not the Target object which always should have a rotation of 0,0,0 not to affect the Label and other children of Target.
This should be a quite normal situation but i cant remember seen any typical solution for it. How is this normally done?

A: To expand on my comment regarding separating Body from Target and placing Target under manual control, I imagine it would look like this:
Target
|-- Label
|-- Others

Body >> RigidBody

Then implement a script something like this on Target
public class Follow: MonoBehavior
{
    //This would likely be 'Body'
    public Transform Attached = null;
    //This is the offset you want Target, Label, etc. to be from Body
    public Vector3 Offset = new Vector3(10, 10, 10);

    //Fixed Update is preferred when responding to physical simulation
    void FixedUpdate()
    {
        if (Attached != null) transform.position = Attached.position + Offset;
    }
}


text:
Q: Permission changes after extracting tgz file While extracting a tgz file, I have noticed that the permission changes to something weird! The tgz file belongs to root:root however, the folder belongs to 502:games
[root@rocks7 common]# ls -l
-rw-r--r-- 1 root root 4779534 May  2  2012 scalapack-2.0.2.tgz
[root@rocks7 common]# tar xf scalapack-2.0.2.tgz
[root@rocks7 common]#
[root@rocks7 common]# ls -l
total 98576
drwxr-xr-x 10  502 games     4096 May  2  2012 scalapack-2.0.2
-rw-r--r--  1 root root   4779534 May  2  2012 scalapack-2.0.2.tgz

What is the issue here?

A: The tarball contains a scalapack-2.0.2 directory owned by user id 502 and whatever group id corresponds to the games group (or, perhaps, the games group by name). You can see this by running
tar tvf scalapack-2.0.2.tgz

Tar archives store ownership and permissions in addition to the file contents; since you're extracting as root, that metadata is applied to the extracted files. The ownership of the tarball itself has no impact on the ownership of the extracted data.
Since you're running CentOS, you're presumably running GNU tar, and you can use the --no-same-owner and --no-same-permissions options to extract tarballs without applying the stored ownership and permissions. Other tar implementations may have similar options (e.g. -o on FreeBSD tar).


text:
Q: How to simulate a tap at a specific coordinate in an android webview? I am able to simulate tap events on typical android views (textbox, button, etc.) using MotionEvent.obtain, like this:
 int meta_state = 0;
    MotionEvent motionEvent = MotionEvent.obtain(
            SystemClock.uptimeMillis(),
            SystemClock.uptimeMillis(),
            MotionEvent.ACTION_DOWN,
            x,
            y,
            meta_state
    );
    motionEvent.recycle();

    view_tapped.dispatchTouchEvent(motionEvent);

view_tapped is a reference to the view I want to sent the event to. However, when I call dispatchTouchEvent on a webview, it doesn't seem to tap any element inside.
I've also put an onTouchListener inside the webview, and then dumped all the information related to the motionevent when the view is actually tapped by a finger, and then created a new motionevent with all of the same information and dispatched it to the webview, and it isn't tapping the screen. The onTouchListener is still fired, but the element on the screen isn't tapped.
I also tried doing it with Javascript, by trying to figure out which element was at the specific coordinate and then firing the click event by injecting javascript, but no luck either.
Any ideas as to what I'm doing wrong?

A: There is my solution:
private void simulateClick(float x, float y) {
    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis();
    MotionEvent.PointerProperties[] properties = new MotionEvent.PointerProperties[1];
    MotionEvent.PointerProperties pp1 = new MotionEvent.PointerProperties();
    pp1.id = 0;
    pp1.toolType = MotionEvent.TOOL_TYPE_FINGER;
    properties[0] = pp1;
    MotionEvent.PointerCoords[] pointerCoords = new MotionEvent.PointerCoords[1];
    MotionEvent.PointerCoords pc1 = new MotionEvent.PointerCoords();
    pc1.x = x;
    pc1.y = y;
    pc1.pressure = 1;
    pc1.size = 1;
    pointerCoords[0] = pc1;
    MotionEvent motionEvent = MotionEvent.obtain(downTime, eventTime,
            MotionEvent.ACTION_DOWN, 1, properties,
            pointerCoords, 0,  0, 1, 1, 0, 0, 0, 0 );
    dispatchTouchEvent(motionEvent);

    motionEvent = MotionEvent.obtain(downTime, eventTime,
            MotionEvent.ACTION_UP, 1, properties,
            pointerCoords, 0,  0, 1, 1, 0, 0, 0, 0 );
    dispatchTouchEvent(motionEvent);
}

A: I think you just need one line of code. The below command is working fine for me.
Runtime.getRuntime().exec("/system/bin/input tap 100 400");

That's a much cleaner solution. Unfortunately, it doesn't have events like touch_down, touch_up, or move_to, etc.

A: This answer is based on Fedir Tsapana's response. I refactored it to make it more generalized, this is a utility that generates the two motion events needed to simulate a finger touch click event.
It was particularly useful for forwarding an event that was being consumed in another window on top of where I wanted the click to go.
fun simulateClickAtCoordinates(x: Float, y: Float): Pair<MotionEvent, MotionEvent> {
    val downTime = SystemClock.uptimeMillis()
    val eventTime = SystemClock.uptimeMillis() + 100
    val properties = buildPointerProperties()
    val pointerCoords = buildPointerCoords(x, y)
    return buildPressEvent(downTime, eventTime, properties, pointerCoords) to buildReleaseEvent(downTime, eventTime, properties, pointerCoords)
}

private fun buildPointerProperties(): Array<MotionEvent.PointerProperties?> {
    val properties = arrayOfNulls<MotionEvent.PointerProperties>(1)
    properties[0] = MotionEvent.PointerProperties().apply {
        id = 0
        toolType = MotionEvent.TOOL_TYPE_FINGER
    }
    return properties
}

private fun buildPointerCoords(x: Float, y: Float): Array<MotionEvent.PointerCoords?> {
    val pointerCoords = arrayOfNulls<MotionEvent.PointerCoords>(1)
    pointerCoords[0] = MotionEvent.PointerCoords().apply {
        this.x = x
        this.y = y
        pressure = 1f
        size = 1f
    }
    return pointerCoords
}

private fun buildPressEvent(downTime: Long, eventTime: Long, properties: Array<MotionEvent.PointerProperties?>, pointerCoords: Array<MotionEvent.PointerCoords?>) =
        MotionEvent.obtain(downTime, eventTime,
                MotionEvent.ACTION_DOWN, 1, properties,
                pointerCoords, 0, 0, 1f, 1f, 0, 0, 0, 0)

private fun buildReleaseEvent(downTime: Long, eventTime: Long, properties: Array<MotionEvent.PointerProperties?>, pointerCoords: Array<MotionEvent.PointerCoords?>) =
        MotionEvent.obtain(downTime, eventTime,
                MotionEvent.ACTION_UP, 1, properties,
                pointerCoords, 0, 0, 1f, 1f, 0, 0, 0, 0)

A: Try not recycling the motionEvent before dispatching it


text:
Q: Java Translating From English to Pig Latin I have an assignment for a computer science class to take in a word in english, and reprint it in pig latin (in this case, simply take the first letter and put it at the end). This is my code. Note: for full credit, it must be 2 different methods.
import java.util.Scanner;
public class PigLatin {

public static void main(String[] args){
    Scanner kboard = new Scanner(System.in);
    System.out.println("Enter a string in english: ");
    String x = kboard.nextLine();

}

public static void pLatin(String x){
    String pigx = x.substring(0,1);
    String pigy = x.substring(1);
    System.out.println("The string in pig latin is " + pigy + pigx);

    }

}

I get no errors in Eclipse, but when I run the program, it does not print anything after I type in the word for the scanner. what am I doing wrong? thanks

A: You never tell it to print the word, nor to call your pLatin() function for that matter.
public static void main(String[] args){
    Scanner kboard = new Scanner(System.in);
    System.out.println("Enter a string in english: ");
    String x = kboard.nextLine();
    // MISSING: System.out.println("recieved: " + x);
    // MISSING: pLatin(x);
}

Also I don't think your pLatin function makes correct pig latin.

A: Add this call of your method in the public static void main...
    public static void main(String[] args) {
        Scanner kboard = new Scanner(System.in);
        System.out.println("Enter a string in english: ");
        String x = kboard.nextLine();

        pLatin(x);

}

...and see what comes up.

A: please try this code:
public static void main(String [] args) {
    Scanner kboard = new Scanner(System.in);
    System.out.println("Enter a string in english: ");
    System.out.println("The string in pig latin is: "+ pLatin(kboard.nextLine()));
}

public static String  pLatin(String x){
    return x+x.charAt(0);
}

one problem is:
    String pigx = x.substring(0,1); //pigx = the first two letters
                                    //if the world is java -> pigx=ja
    String pigy = x.substring(1); //pigy= all the letters except the first
                                  //letter. if world is java-> pigy= ava

    System.out.println("The string in pig latin is " + pigy + pigx);

by this code you are not adding the first letter to the last index of a world,
you are getting and printing the first two letters(pigx) and all the letters except the first letter(pigy).


text:
Q: Determining if a closure is static in PHP A closure defined in PHP can also carry the static modifier.
$f = function () { };

$g = static function () { };

The static closure cannot be bound via Closure::bind or Closure::bindTo, and will issue a warning.
$g = Closure::bind(static function () { }, new stdClass());

// Warning: Cannot bind an instance to a static closure in ...

This is also the case of closures created by reflecting a static method with ReflectionMethod::getClosure.
class MyClass
{
    public static function myStaticMethod() { }
}

// reflect MyClass::myStaticMethod,  create an unbound closure, and try to bind it
$f = (new ReflectionMethod(MyClass::class, 'myStaticMethod'))
    ->getClosure()
    ->bindTo(new stdClass());

// Warning: Cannot bind an instance to a static closure in ...

While annoying, this is acceptable; however, how is one to test between a static and non-static closure?
ReflectionMethod::isStatic seemed like it might work, but sensibly doesn't as Closure::__invoke is instance-level, not static.
$f = static function () { };

// reflect Closure::__invoke because I think I'm tricky
$r = new ReflectionMethod($f, '__invoke');

// and it's not static anyway
var_dump($r->isStatic()); // bool(false)

Further, checking ReflectionMethod::getClosureThis can generally work, as a static method must be unbound, however that doesn't cover closures defined outside an instance method, or the corner-case of instance methods that have been unbound.
class MyClass
{
    public function myInstanceMethod() { }
}

$o = new MyClass();

// reflect MyClass::myInstanceMethod, create a bound closure, and then unbind it
$f = (new ReflectionMethod($o, 'myInstanceMethod'))
    ->getClosure($o)
    ->bindTo(null);

// then reflect the closure
$r = new ReflectionFunction($f);

// and see it's bound to nothing, as would be the case of a static closure
var_dump($r->getClosureThis()); // NULL

So, to restate, how do you determine whether a closure is static (or more specifically, bindable) or not?
It really seems as though we should have a ReflectionFunctionAbstract::isBindable, or that ReflectionMethod::isStatic be moved up to ReflectionFunctionAbstract.

A: If binding works, the Closure will have a $this bound to it. So, just bind it and then check for the $this. If it's null, well, then it's a static Closure.
function isBindable(\Closure $closure) {
    $boundClosure = @\Closure::bind($closure, new stdClass);

    return $boundClosure && (new ReflectionFunction($boundClosure))->getClosureThis() != null;
}

A: It seems impossible now.
You can find some debates here: https://bugs.php.net/bug.php?id=64761
The only real workaround I use for myself now is adding ->isBindable property manually.
Here's some code I found here https://github.com/atoum/atoum/blob/master/classes/test/adapter/invoker.php
Maybe will give you a few ideas
protected static function isBindable(\closure $closure)
    {
        $isBindable = (version_compare(PHP_VERSION, '5.4.0') >= 0);
        if ($isBindable === true)
        {
            $reflectedClosure = new \reflectionFunction($closure);
            $isBindable = ($reflectedClosure->getClosureThis() !== null || $reflectedClosure->getClosureScopeClass() === null);
        }
        return $isBindable;
    }

A: Very old question but still shows up in google search. The mentioned isStatic nowadays exists in ReflectionFunction,as of php 8.1 (I tested it out)
$fn = static fn() => true;
$refl = new ReflectionFunction($fn);

$refl->isStatic(); // returns true

$fn = fn() => true;
$refl = new ReflectionFunction($fn);

$refl->isStatic(); // returns false

It does not show up in documentation as of writing.
See: https://www.php.net/manual/en/class.reflectionfunction.php
I also created a missing doc report here: https://github.com/php/doc-en/issues/2136


text:
Q: linux tar command -t option to show max-depth=1 A tar.gz file may contain many files and folders, and the folders may, in turn, have a lot of files and folders.
I want to list the contents of the tar.gz file, but only one directory deep.
How can I write this command?

A: The tar command does not provide a way to do this, but you can filter its output using grep:
tar tfz file.tar.gz | grep -v '/'

or, to add one level more
tar tfz file.tar.gz | grep -v '/.*/'

or, to add another level of files:
tar tfz file.tar.gz | grep -v '/.*/.*/'

A: grep, egrep did not work for me.
tar -tf <file.tar> | cut -f1-<whatever...> -d\ | uniq works w/o -v optionf or tar, where <file.tar> is obvious, yet <whatever...> depends on the length of the path of the directories archived, e.g. /home/luser1/his_forgotten_stuff, /home/luser2/other_desperate_deadline, etc.
I suppose a combo of --no-recurse, and --exclude=  would do a better jobs, yet is beyond and above me to deal w/glob(), which I suspect it behaves  distro dependent. :/ :( .


text:
Q: Why use spyOn instead of jasmine.createSpy? What is the difference between

jasmine.createSpy('someMethod')

And

spyOn(someObject, 'someMethod')

And why should one choose to use spyOn?
My guess is that the first alternative will match the method someMethod no matter in what object it's contained but spyOn will only match if it's contained in someObject. Thus making createSpy just a more generic matcher?

A: The difference is that you should have a method on the object with spyOn
const o = { some(): { console.log('spied') } };
spyOn(o, 'some');

while the mock method is created for your with createSpy():
const o = {};
o.some = jasmine.createSpy('some');

The advantage of the spyOn is that you can call the original method:
spyOn(o, 'some').and.callThrough();
o.some(); // logs 'spied'

And as @estus says the original method is restored after the test in case of spyOn. This should be done manually when it's reassigned with.

A: Additionally to the other fine answer:

*

*Use spyOn() to spy (intercept) an existing method on an object to track calls of other modules to it.

*Use jasmine.createSpy() to create a function that can be passed as callback or Promise handler to track call-backs.


text:
Q: date using either raw_input() or input() coming up as integer New to Python and have read so many other SO questions that I feel like I am missing something with how to massage user input to string format. I have this simple code and I get the AttributeError: 'int' object has no attribute 'split' so I added exception handiling and am getting error everytime. I have tried almost everything with the str(), datetime() and std.readline() and nothing.
 def dateConverter(userDate):
        try:
            #split the substrings for month day year
            date = userDate.split("/")
            #day
            day = date[:2]
            #month
            month = date[3:5]#[ beginning : beginning + LENGTH]
            months = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}
            for key,value in months:
                month=value
            #year
            year = date[4:]
            print(str(month + ' ' + day + ',' + year))
            return True
        except:
            print('Error')
            return False
print('Enter a date in the format: mm/dd/yyyy \n')
    userInput = raw_input()
    dateConverter(userInput)

main()

Note: I have both Python27 and Python34 installed on Win7
Edit

vaibhav-sagar was correct, I wasn't slicing the string the right way and had nothing to do with the input. Although, I have Python27 & Python34 installed and even though I set my variable path to Python34 I have to use raw_input() which I heard was deprecated in Python34 so look out for that too. That is what was stumping me! Sorry, this was my second look at Python so it was really new territory. I actually got the slicing examples from another SO answer so that is what I get for assuming. Here is the solution:
 #custom date converter func
    def dateConverter(userDate):
        try:
            #split the substrings for month day year
            date = userDate.split("/")
            #day
            day = date[1]#[ beginning : beginning + LENGTH]
            #month
            month = date[0]
            months = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}
            month=months[int(month)]
            #year
            year = date[2]
            print(month + ' ' + day + ',' + year)
            return True
        except:
            print('Error')
            return False

Next step is to validate using re to validate the  date is valid

A: I am using Python 3.3.5 and getting a different error. An exception is being raised at
for key, value in months:

Because iterating over a dictionary yields only keys, and not keys and values. What you want can be accomplished by:
for key, value in months.items():

More generally, your issues seem unrelated to your massaging of user input. This can be verified by using IDLE or another REPL. For example:
>>> someDate = '12/10/2014'
>>> date = someDate.split('/')
>>> date
['12', '10', '2014']
>>> day = date[:2]
>>> day
['12', '10']
>>> month = date[3:5]
>>> month
[]
>>> year = date[4:]
>>> year
[]

Python's slice syntax is doing something different to what I think you want. I also think you don't need a for loop, instead you can do:
month = months[int(month)]

This will assign the month name to month, like you expect. A function that does what I think you want would look something like this:
def dateConverter(userDate):
    #split the substrings for month day year
    date = userDate.split("/")
    #day
    day = date[1]
    #month
    month = date[0]
    months = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}
    month = months[int(month)]
    #year
    year = date[2]
    print(str(month + ' ' + day + ',' + year))
    return True

I hope that helps.


text:
Q: Loop through python array, set specific values to a specified column I have tried many things but still stuck. This is mostly because I'm failing to understand how python loops through an array or what options I have to loop through it.
I want to build an array: 4 columns, 18 rows.
I need the first column of each row to be a persons name in the person_list. Every 3 rows of my array I would then increment to the next person.
It would seem that my loop is not looping through the array the way I intended. It seems that it sets all values in the first column equal to the person_list value.
person_list = ["person1", "person2","person3","person4","person5","person6"]
my_array = [[0]*4]*len(person_list)*3

i=0
j=1
for row in my_array:
    while j <= 3:
        row[0] = person_list[i]
        j+=1
    j=1
    i+=1

So the goal would be the resulting array
[
["person1", 0, 0, 0],
["person1", 0, 0, 0],
["person1", 0, 0, 0],
["person2", 0, 0, 0],
["person2", 0, 0, 0],
["person2", 0, 0, 0],
["person3", 0, 0, 0],
["person3", 0, 0, 0],
...
]

A: The problem seems to stem from the way my_array was initialized. Each row is 'nested' with the other rows, by that I mean if you try to modify my_array[0], you will end up modify all the remaining rows. Here is an example to illustrate that:
my_array[0].insert(0, 'hello_world')
# this prints:
# [['hello_world', 0, 0, 0],
   ['hello_world', 0, 0, 0],
   ....
   ['hello_world', 0, 0, 0]]

To get around, this you can use numpy to initialize your array of zeros or do something like this:
my_array = [[0, 0, 0, 0] for i in range(18)]

To make the code slight more concise and print the expected output, you can then do the following:
for i in range(len(person_list)):
    # person1 : idx 0, 1, 2
    # person2 : idx 3, 4, 5
    # ...
    end_idx = (i + 1) * 3
    start_idx = end_idx - 3

    for sub_arr in arr[start_idx:end_idx]:
        sub_arr.insert(0, person_list[i])

Hope this helped!

A: You could use the modulo % to increment at certain intervals. For example, row%3==0 will return True at multiples of 3. FYI in your above code you were not resetting the row variable  every interval of 3.
person_list = ["person1", "person2","person3","person4","person5","person6"]
my_array = [[0]*4]*len(person_list)*3

j=0
i=0
for row in my_array:
    if j%3==0:
        row[0] = person_list[i]
        i+=1
    j+=1 # increment the row here

A: I think everything is good in your code, you are just multiplying it by 3 :
person_list = ["person1", "person2","person3","person4","person5","person6"]
my_array = [[0]*4]*len(person_list)

i=0
j=1
for row in my_array:
    while j <= 3:
        row[0] = person_list[i]
       j+=1
    j=1
    i+=1

I think its this like which needs to change from my_array = [[0]*4]*len(person_list)*3 to my_array = [[0]*4]*len(person_list)

A: So I think NeuralX was helpful in pointing out the way I create the array is not going to work for what I intend to do to it. He is absolutely correct when I run a change it will update every entry in the final array.
In more searching with working with nested lists, I have found how I should create the array so that I can update nested lists individually by looping through it. The final results are going to be below.
person_list = ["person1", "person2","person3","person4","person5","person6"]

# The way I create the array appears the be the main root cause here. I need to create it like this
my_array = [[0 for x in range(4)] for y in range(sum(person_assessments))]

i=0
j=0
for person in person_list:

    for assessment in range(1, 4):
        my_array[i][0] = person
        # print(person, ", ", assessment)
        # print(i,", ", j,", ", person)

        i+=1

    j += 1

print(my_array)


text:
Q: Publishing Android library to bintray maven produces 2 separate artifacts I'm trying to publish my android library using bintray, but I end up with two separate artifacts in bintray maven stringx and stringx-android-sdk:
https://dl.bintray.com/klimaszewski/stringx/io/stringx/
where sources and all the stuff is placed here:
https://dl.bintray.com/klimaszewski/stringx/io/stringx/stringx/1.0.2/
and POM file is placed in correct artifact:
https://dl.bintray.com/klimaszewski/stringx/io/stringx/stringx-android-sdk/1.0.2/
My bintray repo is: stringx and library name: stringx-android-sdk
Bacause of that library cannot be resolved in my projects. What's wrong here?
build.gradle
buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }

    dependencies {
        classpath 'com.github.dcendents:android-maven-gradle-plugin:2.0'
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'
    }
}
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
apply plugin: 'com.jfrog.bintray'

ext {
    bintrayRepo = 'stringx'
    bintrayName = 'stringx-android-sdk'

    publishedGroupId = 'io.stringx'
    libraryName = 'StringX-SDK'
    artifact = 'stringx-android-sdk'

    libraryDescription = 'Automatic app Translation for Android'

    siteUrl = 'https://www.stringx.io'
    gitUrl = 'https://github.com/SzyQ/stringx-android-sdk'

    developerId = 'klimaszewski'
    developerName = 'Szymon Klimaszewski'
    developerEmail = 'klimaszewski.szymon@gmail.com'

    licenseName = 'The Apache Software License, Version 2.0'
    licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
    allLicenses = ["Apache-2.0"]
    versionMajor = 1
    versionMinor = 0
    versionHotFix = 2

    libraryVersion = buildVersionName()
}

android {
    compileSdkVersion 27
    buildToolsVersion "26.0.2"
    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 27
        versionCode buildVersionCode()
        versionName buildVersionName()
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:support-annotations:27.0.0'
}

def buildVersionName() {
    String versionName
    if (versionHotFix == null || versionHotFix == 0) {
        versionName = versionMajor + "." + versionMinor
    } else {
        versionName = versionMajor + "." + versionMinor + "." + versionHotFix
    }
    println "Version name: " + versionName
    return versionName
}

def buildVersionCode() {
    Integer versionCode
    if (versionHotFix == null || versionHotFix == 0) {
        versionCode = versionMajor * 10000 + versionMinor * 100
    } else {
        versionCode = versionMajor * 10000 + versionMinor * 100 + versionHotFix
    }
    println "Version code: " + versionCode
    return versionCode
}

apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/installv1.gradle'
apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/bintrayv1.gradle'

A: Android module name has to match bintray package, 'stringx-android-sdk' in my case.
So I had to change module in settings.gradle
include ':stringx-android-sdk'
project(":stringx-android-sdk").projectDir = file("../../stringx")


text:
Q: ignore Mapping from DomainModel to ViewModel I have 2 fields in DomainModel (CreatedOn,ModifiedOn) which are not in my ViewModel. How can I put ignore on Source fields when mapping from DomainModel to ViewModel. Please fix below code.
Mapper.CreateMap<DomainModel, ViewModel>()
                .ForMember(d => d.CreatedOn, opt => opt.Ignore())
               .ForMember(d => d.ModifiedOn, opt => opt.Ignore());

A: You don't need to specify anything about those fields. Just:
Mapper.CreateMap<DomainModel, ViewModel>();

If the CreatedOn and ModifiedOn properties don't exist on your view model when mapping between DM and VM they will be simply ignored.

A: I believe that AutoMapper will only try to populate those fields in the target.  As long as the target doesn't have fields that happen to be in the source, those fields won't exist in the target after mapping is complete.
However, if the fields did happen to exist in the target, it looks like your syntax is correct (although for consistency with all examples I have seen - you might use dest => dest.CreatedOn instead of d => d.CreatedOn - but I don't think that will break it).


text:
Q: jQuery UI Timepicker off by 1 minute I'm maintaining an application which uses the jQuery UI Timepicker and trying to troubleshoot a bug.
Basically, this is how to re-create it:
There are 2 timepickers, start time and end time
1. on the start-time, select 6:00am (from the hour area)
2. on the end-time, select 12:00pm (from the hour area)
3. go back to the start-time and select 00 from the minute area
Then some code runs to determine the elapsed time in minutes. That code is:
    function setDuration() {

        var $startTime = $(".field.times input[name$='StartTime']");
        var $endTime = $(".field.times input[name$='EndTime']");

        var $durationHours = $(".field.duration input[name$='DurationHours']");
        var $durationMinutes = $(".field.duration input[name$='DurationMinutes']");

        if ($startTime.val() != "" && $endTime.val() != "") {

            var startTime = $startTime.timepicker ? $startTime.timepicker('getTimeAsDate') : Date.parse('01 jan 01 ' + $startTime.val(), "hh:mm tt");
            var endTime = $endTime.timepicker ? $endTime.timepicker('getTimeAsDate') : Date.parse('01 jan 01 ' + $endTime.val(), "hh:mm tt");
            var duration = (endTime - startTime) / 1000 / 60;

            //check whether spanning multiple days
            if (startTime > endTime) {
                duration = duration + (60 * 24);
            }

            $durationHours.val(Math.floor(duration / 60));
            $durationMinutes.val(duration % 60);
        }
    }

I have found that after completing steps 1 and 2, everything is fine.
But, if I complete step 3, the endTime local variable is assigned a date object which has a time component of 11:59 and not 12:00.
Off by 1 minute.
If I then go to the End Time picker and select 00 from the minute area, as I did with the Start Time picker, the elapsed time rights itself again.
As an interesting observation when debugging, both timepickers are 1 minute behind after steps 1 and 2. That is, they are at 5:59 and 11:59. The elapsed time is correct, as the difference is important. But as a said, as soon as a user selects 00 from the hours area, it seems to "right itself" for that picker and the difference is out by 1 minute (until the same thing is done for the other picker).
Javascript dates are hard! Help would be great.

A: Yeah, figured it out. I guess it is an opinionated component which holds the opinion that the user must select a minutes figure from the minutes area. Because if they don't, the minutes will be -1.
Fair enough.
To fix this bug, in the onSelect handler, I wrote some code similar to this:
$('#timepicker').timepicker({
        onSelect: function (time, inst) {
            if (inst.minutes < 0)
                inst.minutes = 0;
        }
});

In our app, if they don't select '00' or any other minutes, it will be presumed to be 0.


text:
Q: Application randomly receives EXC_CRASH (SIGABRT) I am trouble understanding the following crash, because it happens randomly and I suspect might be a multi thread problem but here it is:
Incident Identifier: 0BE956AB-228A-4B1B-8A3D-A99A481F7F3F
CrashReporter Key:   da7dc0be9da2f7fa677999d7093fdf2495031393
Hardware Model:      iPhone3,1
Process:         MyApp test [2899]
Path:            /var/mobile/Applications/D6419515-BA52-4747-94C5-5626F0E69571/MyApp test.app/MyApp test
Identifier:      MyApp test
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2012-10-24 19:42:40.289 +0200
OS Version:      iPhone OS 5.0.1 (9A405)
Report Version:  104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x00000000, 0x00000000
Crashed Thread:  0

Last Exception Backtrace:
0   CoreFoundation                  0x33e118bf __exceptionPreprocess + 163
1   libobjc.A.dylib                 0x340611e5 objc_exception_throw + 33
2   CoreFoundation                  0x33e14acb -[NSObject doesNotRecognizeSelector:] + 175
3   CoreFoundation                  0x33e13945 ___forwarding___ + 301
4   CoreFoundation                  0x33d6e680 _CF_forwarding_prep_0 + 48
5   MyApp test                  0x000889f9 -[UploadPhotoViewController requestCompletedWithCode:] (UploadPhotoViewController.m:154)
6   CoreFoundation                  0x33d7022b -[NSObject performSelector:withObject:] + 43
7   MyApp test                  0x0005f6c9 -[ASIHTTPRequest reportFinished] (ASIHTTPRequest.m:2020)
8   CoreFoundation                  0x33d7022b -[NSObject performSelector:withObject:] + 43
9   Foundation                      0x357fb757 __NSThreadPerformPerform + 351
10  CoreFoundation                  0x33de5b03 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
11  CoreFoundation                  0x33de52cf __CFRunLoopDoSources0 + 215
12  CoreFoundation                  0x33de4075 __CFRunLoopRun + 653
13  CoreFoundation                  0x33d674dd CFRunLoopRunSpecific + 301
14  CoreFoundation                  0x33d673a5 CFRunLoopRunInMode + 105
15  GraphicsServices                0x305ebfcd GSEventRunModal + 157
16  UIKit                           0x371e8743 UIApplicationMain + 1091
17  MyApp test                  0x00032025 main (main.m:16)
18  MyApp test                  0x00031fd0 0x30000 + 8144

And here is UploadPhotoViewController requestCompletedWithCode: method:
-(void)requestCompletedWithCode:(int)statusCode{

    [hud hide];

    if (statusCode == 201){
        UINavigationController *navVC = [self.tabBarController.viewControllers objectAtIndex:3];
//        UpdatesViewController *updatesVC= (UpdatesViewController *)[navVC visibleViewController];
        UpdatesViewController *updatesVC= (UpdatesViewController *)[navVC topViewController];
        updatesVC.newPhoto = YES;
        [self.tabBarController setSelectedIndex:3];
        [self.navigationController popViewControllerAnimated:NO];

    }
}

Line 154 points at:
    [self.tabBarController setSelectedIndex:3];

Anyone knows what could be the issue?
Edit
I'm getting to the UploadPhotoViewController (The VC at hand) from the previous VC via those lines:
  [self performSegueWithIdentifier:@"UploadPhoto" sender:self];
  [self dismissModalViewControllerAnimated: NO];

DismissModalViewControllerAnimated is dismissing the UIImagePickerController.
Thanks a lot!

A: the problem might be in [NSObject doesNotRecognizeSelector:] , somewhere you might overwrite or remove your tabBarController (or instantiate the same view controller from modal window) and it get crazy.

A: This might be kind of an overkill but for test (and learning) purposes I would replace the
[self.tabBarController setSelectedIndex:3];

with
if ([self.tabBarController respondsToSelector:@selector(setSelectedIndex:)])
    [self.tabBarController setSelectedIndex:3];
else
    NSLog(@"self.tabBarController is not an instance of UITabBarController");


text:
Q: Reactivity issue in VueJs - unnecessary updates I have a Vue application, which renders a nested tree-like data structure. The structure has only two cases - boolean values at the leaves of the tree and key-value records as internal tree nodes.
The boolean case is internally encoded as { type: 'bool', value: <boolean value> } record.
The record case is internally encoded as { type: 'record', value: <js object> }.
The 'type' field makes it easier to dispatch between Vue components to render a particular case:
https://codesandbox.io/s/vue2-reactivity-issue-kbg4c
The boolean case component allows to switch the value of the boolean by clicking on it.
Now suppose the following structure is rendered:
record({
  a: record({ a1: bool, a2: bool }),
  b: bool,
  c: bool,
  d: record({ d1: bool, d2: bool })
});

When I click on the bool corresponding to the "a1" field, I see that "a1" and "a2" components are being updated. I've inserted trace to the "updated" component hook, so it's visible in the console what components are updated.
When I click on the bool corresponding to the "b" field, every components in the application is being updated - even the most nested one like "d1" and "d2".
This seems to me as unnecessary updates.
Why do they happen and how to avoid it?

A: the good point to start is this article https://v2.vuejs.org/v2/guide/reactivity.html
The first issue that you link bool object over the whole state.
The second one that you modify entirely state every mutation.
https://codesandbox.io/s/vue2-reactivity-issue-ocy0h


text:
Q: How to draw multiple Venn Diagrams using jVenn Plugin Hi I am working on an application and I need to draw multiple Venn Diagrams. I went for jVenn jQuery Plugin(http://bioinfo.genotoul.fr/jvenn/documentation.html). it works fine when you want to draw only 1 Venn Diagram but when you try to draw more than 1 Venn diagram it doesnt work at all. It just draws the last Venn Diagram.
DEMOS
Drawing only 1 Venn Diagram (Works fine)
https://jsfiddle.net/uhqqqrgh/
Trying to draw more than 1 Venn Diagram (Not working)
https://jsfiddle.net/uhqqqrgh/1/
HTML

jQuery
$(document).ready(function(){
  $('#example').jvenn({
    series: [{
        name: 'Actors',
        data: ["Marilyn Monroe", "Arnold Schwarzenegger", "Jack Nicholson", "Barbra Streisand", "Robert de Niro", "Dean Martin", "Harrison Ford"]
      }, {
        name: 'Singers',
        data: ["Freddy Mercury", "Barbra Streisand", "Dean Martin", "Ricky Martin", "Celine Dion", "Marilyn Monroe"]
      }]
  });

  $('#example1').jvenn({
    series: [{
        name: 'Models',
        data: ["Marilyn Monroe1", "Arnold Schwarzenegger", "Jack Nicholson", "Barbra Streisand", "Robert de Niro", "Dean Martin", "Harrison Ford"]
      }, {
        name: 'Directors',
        data: ["Freddy Mercury", "Barbra Streisand", "Dean Martin", "Ricky Martin", "Celine Dion", "Marilyn Monroe"]
      }]
  });
});

NOTE In demos initial jQuery is the plugin code and for the code to initiate jVenn is written at the bottom.

A: I checked this plug-in. It is working on id's internally and there is no context pass while selecting any element. That's why it always display the content inside the first container. You have to choose some other plug-in like D3.js.
May be this link will help you.


text:
Q: Coinbase Pro Fees and Total I have wondered on how the Coinbase get / calculate its Fees and total upon inputting a value in the Order (Market, Limit, Stop). Can anyone explain how to get the Fees and Total or maybe there's a coinbase api to be used in this one? It would really be a big help. Thank you! Here's the attached screenshot

A: You can read more about the Coinbase fees here.
At this moment, Coinbase trading fee is 0.2%.
Fee: 0.2% of 20 is: 0.04
Total: 20 - 0.04 = 19.96 GBP / 10601.60 GBP = 0.00188273468 BTC
*10601.60: is BTC market price


text:
Q: NodeJS CORS error when calling api from localhost Vue project I have a project with a NodeJS/Express backend and a VueJS frontend. The problem I am facing is that I constantly get CORS errors:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8080/api/plot. (Reason: CORS request did not succeed).
I have added the CORS middelware inside my index.js file of my NodeJS backend:
const express = require('express');

const app = express();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method',
  );
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
  res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
  next();
});

I also have tried a different approach:
const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors());

In the Vue project I have added the proxy to my vue.config.js file:
module.exports = {
  devServer: {
    port: 8080,
    proxy: {
      '^/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        secure: false,
        pathRewrite: { '^/api': '/api' },
        logLevel: 'debug',
      },
    },
  },
};

Then I have changed the URL of my API call to post 8080:
import axios from 'axios';

export const addPlot = async (plot) => {
  const url = `https://localhost:8080/api/plot`;
  return await axios.post(url, plot).then((res) => {
    console.log(res);
  });
};

A: First, when you are using Webpack Dev server proxy, you don't need to configure Express with any CORS (assuming in production you are going to serve your Vue app build from the same Express server)
Reason why you getting CORS errors is that your app is served from http://localhost:8080 (Webpack Dev server) but you are making your Axios request to https://localhost:8080/api/plot - important part is HTTPS:// and because browser is using same-origin policy only if protocol + host + port are all same, browser is firing CORS pre-flight request
Just make your Axios calls to HTTP instead of HTTPS and you should be fine...

A: *

*Make sure you processing preflight request (OPTIONS with empty 204 answer)
https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

*Try to add Access-Control-Expose-Headers https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

allows a server to indicate which response headers should be made
available to scripts running in the browser, in response to a
cross-origin request

A: So a CORS error is basically a security error wherein browsers will not allow certain/most resources your project may need to be accepted from your server. You can handle it in two ways, and those two ways are dependent upon the environment of the server.

*

*While in development, (www.localhost:port), you will need to install a library called cors (npm install cors) in your project folder. After which, you will need to import the library into your code. Thereafter, you will need to use the cors object as middleware (ps. I do not exactly know what middleware is - thanks to all the stackoverflow committee for their active answers). EXAMPLE:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors())
// app.get(....)

*While in production, though, your cost-free options are limited. If you examine the error closely, the remarks state that cross resourcing is allowed for the https protocol (more, but not for http), so what is needed for your VPS is a Secure Socket Layer certificate, SSL certificate, which I bought for 8 dollars for a year. It is quite intimidating to acquire, but answers were never more than a few searches away, at maximum. Acquiring an SSL certificate requires a port forwarded IP address, so I would strongly suggest paying an extra 6 dollars a month to rent a VPS. Linode is offering some free credit, as of now, (not sponsored), so you might wanna rush. Anyway, steps for acquiring a certificate like this include installing OPENSSL, generating a Certificate Signing Request, (CSR), and then passing it on to your CA, after which you follow the steps they instruct you to follow, and then searching for instructions on using those certificates in your server. You guessed it - On Stackoverflow (:
For added instructions, please comment and I will try and answer.


text:
Q: How do you initialize/add/remove items from Fuel UX SelectList with javascript (not canned html) I'm also using knockout.js, so if possible, I would like to use knockout binding, though I can work around that if there is a way to add/remove items from the dropdown list via javascript.

A: I'd think you'd do it however you'd add items to a normal Bootstrap Dropdown which I believe is just appending <a>'s. As long as your <a>'s click event gets fired and thus this.itemClicked runs--I don't think it should matter. See this line in selectlist.js.
And you might not want to use the auto resize feature either. It's a little buggy right now.


text:
Q: window.onload is not firing in IE Here is my code:
var scrollOnLoad = function scrollOnLoad(selector, offset) {
    window.onload = function() {
        if ($(window).height() <= 800) {
            var attempts = 100;
            var interval = setInterval(function() {
                var h = $(selector).height();
                console.log("attempt #" + attempts + ", h=" + h);
                if (h > 0 || !attempts--) {
                    $("body,html").animate({scrollTop : h + offset}, '1000');
                    clearInterval(interval);
                }
            }, 50)
        }
    }
}

and here is how its caling:
scrollOnLoad(".content-wrapper", 50);

I've noticed that window.onload event is not firing in IE (console is not logging anything) - any ideas why? Thanks in advance!

A: You can use document.readyState property:
function scrollOnLoad(selector, offset) {
    if(document.readyState === 'complete')
        x();
    else
        document.addEventListener('readystatechange', function(){
            if(document.readyState === 'complete')
                x();
        });

    function x(){
        if ($(window).height() <= 800) {
            var attempts = 100;
            var interval = setInterval(function() {
                var h = $(selector).height();
                console.log("attempt #" + attempts + ", h=" + h);
                if (h > 0 || !attempts--) {
                    $("body,html").animate({scrollTop : h + offset}, '1000');
                    clearInterval(interval);
                }
            }, 50)
        }
    }
}

A: As mentioned in comments your function scrollOnLoad is getting executed after the window has loaded.
Now in better scenarios these events should be added in global scope.
So it should be like
 window.onload = function() {
  if(someConditionIsSatisfied){

    if ($(window).height() <= 800) {
            var attempts = 100;
            var interval = setInterval(function() {
                var h = $(selector).height();
                console.log("attempt #" + attempts + ", h=" + h);
                if (h > 0 || !attempts--) {
                    $("body,html").animate({scrollTop : h + offset}, '1000');
                    clearInterval(interval);
                }
            }, 50)
        }
    }
}


text:
Q: sed command failing in script with arguments I am trying to perform a two step string editing:

*

*Match for the string "payload". If found, then add some "#if #endif" code as shown in output file.

*Then copy the line containing "payload", replace it with "upper_payload" and then paste it within the "if endif" conditions.

Input File:
Let's see if this works or not payload.
alskdjaslkdjn.
aslkdjbnalkgfjbaglbjbjdgfsbkgjbsg;
Also here is another_payload.
alskdjbnalgkjb.
kjhsdfjlkgfjlknbsgdfljkbgsbljk((*&)(&;

Expected Output File:
Let's see if this works or not payload.
#if defined(NV_C2C_UPPER_PD)
Let's see if this works or not upper_payload.
#endif
alskdjaslkdjn.
aslkdjbnalkgfjbaglbjbjdgfsbkgjbsg;
Also here is another_payload.
#if defined(NV_C2C_UPPER_PD)
Also here is another_upper_payload.
#endif
alskdjbnalgkjb.
kjhsdfjlkgfjlknbsgdfljkbgsbljk((*&)(&;

I finally came up with the following code in a shell file so that I can run this on multiple text files:
#!/bin/csh -f
sed -i '/payload/a #if defined(NV_C2C_UPPER_PD)\n#endif' $1
sed -i "/NV_C2C_UPPER_PD/a `sed -n '/payload/s/payload/upper_payload/p' $1`" $1

With the above shell script when I pass a command such as:
> ./my_shell.sh test.txt

the text file is modified to the following output:
Let's see if this works or not payload.
#if defined(NV_C2C_UPPER_PD)
Let's see if this works or not upper_payload.
#endif
alskdjaslkdjn.
aslkdjbnalkgfjbaglbjbjdgfsbkgjbsg;
Also here is another_payload.
#if defined(NV_C2C_UPPER_PD)
Let's see if this works or not upper_payload.
#endif
alskdjbnalgkjb.
kjhsdfjlkgfjlknbsgdfljkbgsbljk((*&)(&;

And it also gives this error/warning on the terminal:
sed: can't read Also here is another_upper_payload.: No such file or directory

In the output we can observe that the second "upper_payload" substitution was incorrect because the line copying is incorrect. It copied the first line instead of the newer line containing "another_payload".
I have tried different options but I am failing in solving this problem. Would appreciate some help.

A: Instead of trying to invoke another sed process to create input for one of your sed expressions, consider using the s/// command to reorganize the current line as soon as you find the trigger substring (payload).
/payload/!b

s/.*/&\
#if defined(NV_C2C_UPPER_PD)\
&\
#endif/

s/payload/upper_&/2

The above sed editing script starts by skipping any line containing our trigger string.  The b ("branch") command skips to the very end of the script when used without a label.
On the remaining lines, we replace the entire contents with itself, followed by the #if line, the original line a second time, and the #endif line.  One may insert newlines using the s/// command if they are escaped as shown above (GNU sed allows for inserting literal newlines with \n too).
The second occurrence of the string payload is then prepended by the string upper_ in a separate substitution.
This solution assumes that the trigger string does not occur multiple times in a single line, or the last substitution would not replace the correct substring.
On the command line,
sed -e '/payload/!b' \
    -e 's/.*/&\
#if defined(NV_C2C_UPPER_PD)\
&\
#endif/' \
    -e 's/payload/upper_&/2' file

or, using a separate script file for the script,
sed -f script file

or, using a here-document for the script,
sed -f /dev/stdin file <<'SED_SCRIPT'
/payload/!b

s/.*/&\
#if defined(NV_C2C_UPPER_PD)\
&\
#endif/

s/payload/upper_&/2
SED_SCRIPT

or, using GNU sed,
sed -e '/payload/!b' \
    -e 's/.*/&\n#if defined(NV_C2C_UPPER_PD)\n&\n#endif/' \
    -e 's/payload/upper_&/2' file

Result:
Let's see if this works or not payload.
#if defined(NV_C2C_UPPER_PD)
Let's see if this works or not upper_payload.
#endif
alskdjaslkdjn.
aslkdjbnalkgfjbaglbjbjdgfsbkgjbsg;
Also here is another_payload.
#if defined(NV_C2C_UPPER_PD)
Also here is another_upper_payload.
#endif
alskdjbnalgkjb.
kjhsdfjlkgfjlknbsgdfljkbgsbljk((*&)(&;

A: You can try this sed
$ sed -i 's/\(.*\)\(payload\)\(.*\)/&\n#if defined(NV_C2C_UPPER_PD)\n\1upper_\2\3\n#endif/ ' input_file

\(.*\)\(payload\) Here, the match is split into 2 groups so we can easily back reference them on the return
& will return the full match unaltered
\1upper_\2 This is where we return the grouping in the order we require, the first group matches all the way to payload which allows upper_ to be inserted before payload
Output
$ sed 's/\(.*\)\(payload\)\(.*\)/&\n#if defined(NV_C2C_UPPER_PD)\n\1upper_\2\3\n#endif/' input_file
Let's see if this works or not payload
#if defined(NV_C2C_UPPER_PD)
Let's see if this works or not upper_payload
#endif.
alskdjaslkdjn.
aslkdjbnalkgfjbaglbjbjdgfsbkgjbsg;
Also here is another_payload
#if defined(NV_C2C_UPPER_PD)
Also here is another_upper_payload
#endif.
alskdjbnalgkjb.
kjhsdfjlkgfjlknbsgdfljkbgsbljk((*&)(&;

A: Great sed solutions here already, but I'd personally prefer awk for this:
awk \
-v if='#if defined(NV_C2C_UPPER_PD)' \
-v endif='#endif' \
'
/payload/{
  line=$0
  gsub("payload","upper_payload",$0);
  printf "%s\n%s\n%s\n%s\n",$line,if,$0,endif
  next
}
1' file

A: One way using POSIXly only constructs:
sed -e 'p
  /payload/!d
  s//upper_&/
  i\
#if defined(NV_C2C_UPPER_PD)
  a\
#endif
' file

If you don't want escaped newlines,
you can do as follows while still being
POSIXly compliant:
sed -e 'p
  /payload/!d
  s//upper_&/
  H;s/.*//;x;G
  s/^/#if defined(NV_C2C_UPPER_PD)/
  s/$/#endif/
' file


text:
Q: Apache Nifi MergeContent output data inconsistent? Fairly new to using nifi. Need help with the design.
I am trying to create a simple flow with dummy csv files(for now) in HDFS dir and prepend some text data to each record in each flowfile.
Incoming files:
dummy1.csv
dummy2.csv
dummy3.csv

contents:
"Eldon Base for stackable storage shelf, platinum",Muhammed MacIntyre,3,-213.25,38.94,35,Nunavut,Storage & Organization,0.8
"1.7 Cubic Foot Compact ""Cube"" Office Refrigerators",BarryFrench,293,457.81,208.16,68.02,Nunavut,Appliances,0.58
"Cardinal Slant-D Ring Binder, Heavy Gauge Vinyl",Barry French,293,46.71,8.69,2.99,Nunavut,Binders and Binder Accessories,0.39
...

Desired output:
d17a3259-0718-4c7b-bee8-924266aebcc7,Mon Jun 04 16:36:56 EDT 2018,Fellowes Recycled Storage Drawers,Allen Rosenblatt,11137,395.12,111.03,8.64,Northwest Territories,Storage & Organization,0.78
25f17667-9216-4f1d-b69c-23403cd13464,Mon Jun 04 16:36:56 EDT 2018,Satellite Sectional Post Binders,Barry Weirich,11202,79.59,43.41,2.99,Northwest Territories,Binders and Binder Accessories,0.39
ce0b569f-5d93-4a54-b55e-09c18705f973,Mon Jun 04 16:36:56 EDT 2018,Deflect-o DuraMat Antistatic Studded Beveled Mat for Medium Pile Carpeting,Doug Bickford,11456,399.37,105.34,24.49,Northwest Territories,Office Furnishings,0.61

the flow

splitText-

ReplaceText-

MergeContent-

(this may be a poor way to achieve what I am trying to get, but I saw somewhere that uuid is best bet when it comes to generating unique session id. So thought of extracting each line from incoming data to flowfile and generating uuid)
But somehow, as you can see the order of data is messing up. The first 3 rows are not the same in output. However, the test data I am using (50000 entries) seems to have the data in some other line. Multiple tests show usually the data order changes after 2001st line.
And yes, I did search similar issues here and tried using defragment method in merge but it didnt work. I would appreciate if someone can explain what is happening here and how can I get the data in the same way with unique session_id,timestamp for each record. Is there some parameter I need to change or modify to get the correct output? I am open to suggestions if there is a better way as well.

A: First of all thank you for such an elaborate and detailed response. I think you cleared a lot of doubts I had as to how the processor works!

The ordering of the merge is only guaranteed in defragment mode because it will put the flow files in order according to their fragment index. I'm not sure why that wouldn't be working, but if you could create a template of a flow with sample data that showed the problem it would be helpful to debug.

I will try to replicate this method using a clean template again. Could be some parameter problem and the HDFS writer not able to write.

I'm not sure if the intent of your flow is to just re-merge the original CSV that was split, or to merge together several different CSVs. Defragment mode will only re-merge the original CSV, so if ListHDFS picked up 10 CSVs, after splitting and re-merging, you should again have 10 CSVs.

Yes, that is exactly what I need. Split and join data to their corresponding files. I dont specifically (yet) need to join the outputs again.

The approach of splitting a CSV down to 1 line per flow file to manipulate each line is a common approach, however it won't perform very well if you have many large CSV files. A more efficient approach would be to try and manipulate the data in place without splitting. This can generally be done with the record-oriented processors.

*

*I used this approach purely instinctively and did not realize this is a common method. Sometimes the datafile could be very large, that means more than a million records in a single file. Wont that be an issue with the i/o in the cluster? coz that would mean each record=one flowfile=one unique uuid. What is a comfortable number of flowfiles that nifi can handle? (i know it depends on cluster config and will try to get more info about the cluster from hdp admin)

*What do you suggest by "try and manipulate the data in place without splitting" ? can you give an example or template or processor to use?

In this case you would need to define a schema for your CSV which included all the columns in your data, plus the session id and timestamp. Then using an UpdateRecord processor you would use record path expressions like /session_id = ${UUID()} and /timestamp = ${now()}. This would stream the content line by line and update each record and write it back out, keeping it all as one flow file.

This looks promising. Can you share a simple template pulling files from hdfs>processing>write hdfs files but without splitting?
I am reluctant to share the template due to restrictions. But let me see if I can create a generic templ and I will share
Thank you for your wisdom! :)


text:
Q: Using AsyncController to help increase concurrency on a legacy ASP.NET MVC 3 project We have a website that is struggling with concurrent users right now.
Here is the very high-level background of the project:

*

*Legacy ASP.NET MVC 3 project (.NET 4)

*Can't do any major rewriting of core code

*Main entry point that takes the longest time to execute is the SubmitSearch action on the Search controller.  Average time to respond is 5-10 seconds.

So as the second point outlines, we don't want to spend too much time on this project rewriting large sections.  However, we want to attempt to increase concurrent users.  We're not looking to change anything else or increase performance since it would require much more work.
What we are seeing is that as more people hit SubmitSearch, the web site in general slows down.  That's most likely due to all the IIS threads being locked up executing the search.
We are looking to implement AsyncController and making the SubmitSearch action execute on a normal CLR thread.  Here's how we wanted to implement it:
Assume this is the original SubmitSearch method:
/// <summary>
/// Submits a search for execution.
/// </summary>
/// <param name="searchData">The search data</param>
/// <returns></returns>
public virtual ActionResult SubmitSearch(SearchFormModel searchData)
{
    //our search code
}

The quickest way we were hoping to convert to AsyncController is to simply do this:
/// <summary>
/// Submits a search for execution.
/// </summary>
/// <param name="searchData">The search data</param>
/// <returns></returns>
protected virtual ActionResult SubmitSearch(SearchFormModel searchData)
{
    //our search code
}

/// <summary>
/// Asynchronous Search entry point
/// </summary>
/// <param name="searchData"></param>
public void SubmitSearchAsync(SearchFormModel searchData)
{
    AsyncManager.OutstandingOperations.Increment();
    System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
        ActionResult result = SubmitSearch(searchData);
        AsyncManager.Parameters["result"] = result;
        AsyncManager.OutstandingOperations.Decrement();
    });

    return;
}

/// <summary>
/// Called when the asynchronous search has completed
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
public ActionResult SubmitSearchCompleted(ActionResult result)
{
    //Just return the action result
    return result;
}

Of course this didn't work because all through-out the code, we are referencing HttpContext.Current, which we know ends up being null in this approach.
So we were then hoping to do this with SubmitSearchAsync:
/// <summary>
/// Asynchronous Search entry point
/// </summary>
/// <param name="searchData"></param>
public void SubmitSearchAsync(SearchFormModel searchData)
{
    AsyncManager.OutstandingOperations.Increment();
    System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
        ActionResult result = null;
        AsyncManager.Sync(() =>
        {
            result = SubmitSearch(searchData);
        });

        AsyncManager.Parameters["result"] = result;
        AsyncManager.OutstandingOperations.Decrement();
    });

    return;
}

This fixes the issue.
So here's my concern:
Does wrapping the execution of SubmitSearch in the AsyncManager.Sync method defeat the purpose of using this model?  In other words, when we are within the AsyncManager.Sync method, are we back on the IIS threads, which puts us back at square one?
Thanks

A:
Does wrapping the execution of SubmitSearch in the AsyncManager.Sync method defeat the purpose of using this model? In other words, when we are within the AsyncManager.Sync method, are we back on the IIS threads, which puts us back at square one?

More or less, yes. But unfortunately, in your case, using Task.Factory.StartNew also defeats the purpose of using an async controller. With the approach you're trying to use, you can't win.
IIS threads, threads started by ThreadPool.QueueUserWorkItem, and Task threads, are all taken from the same thread pool.
In order to gain any benefit from async controllers, you need true async methods. In other words, methods like Stream.ReadAsync or WebRequest.GetResponseAsync. These specially-named methods use I/O completion ports instead of normal threads, which use hardware interrupts and operate on a different thread pool.
I wrote about this a long time ago in my answer here: Using ThreadPool.QueueUserWorkItem in ASP.NET in a high traffic scenario. Tasks and awaiters are pretty sweet, but they don't change the fundamental dynamics of the .NET thread pool.
One thing to note is that there is an option, TaskCreationOptions.LongRunning, that you can specify when creating a Task, which essentially informs the framework that the task will be doing a lot of waiting, and in theory the TPL will attempt to avoid scheduling it in the thread pool. In practice, this probably won't be very practical on a high-traffic site because:

*

*The framework doesn't actually guarantee that it won't use the thread pool. That's an implementation detail, and the option is simply a hint that you provide.

*Even if it does avoid the pool, it still needs to use a thread, which is essentially like using new Thread - if not literally then at least effectively so. What this means is heavy context-switching, which absolutely kills performance and is the main reason why thread pools exist in the first place.
A "search" command clearly implies some kind of I/O, which means there's probably a real asynchronous method you can use somewhere, even if it's the old-style BeginXyz/EndXyz. There are no shortcuts here, no quick fixes; you'll have to re-architect your code to actually be asynchronous.
The .NET framework can't inspect what's going on inside your Task and magically convert it into an interrupt. It simply cannot make use of an I/O completion port unless you refer directly to the specific methods that are aware of them.
Next web or middleware application you work on, try to consider this ahead of time and avoid synchronous I/O like the plague.

A: I think @Aaronaught has the best answer so far: you need true asynchronous processing in order to scale (i.e., Begin/End, not just using thread pool threads), and that there are no shortcuts or quick fixes to asynchronous code - it will take a re-architecting of at least that portion.
Which brings me to this part of your question:

we don't want to spend too much time on this project rewriting large sections.

The best bang for your buck is probably to purchase more memory and stick that in the server. (You should check with a profiler first just to make sure it is a memory issue - memory usually is the limiting factor on ASP.NET but it's best to check first).
As much as we developers love to solve problems, the truth is we can burn a lot of hours, e.g., changing synchronous code to asynchronous. FYI, the Task-based Asynchronous Pattern (async/await) in .NET 4.5 will allow you to change synchronous code to asynchronous much more easily.
So for now I say buy a couple RAM chips and make a mental note to do the (much easier) upgrade to async after you change to .NET 4.5.

A: I would start by looking at the performance of the server itself and then consider using  the profiling tools in visual studio to identify exactly what and where the bottleneck is. Consider looking at the mini profiler a discussion of which can be found here http://www.hanselman.com/blog/NuGetPackageOfTheWeek9ASPNETMiniProfilerFromStackExchangeRocksYourWorld.aspx. Generally agree with the comment above about thread consumption.

A: There are dozens of reasons that can cause the server to slow down. If we only talk about threads, threads consume a minimum of 1/4 memory each, that means the more threads drawn up from the thread pool, the more memory is consumed. This can be one of the problems causing the server to slow down.
If the response from server takes over 10 seconds, consider using Asynchronous. Like in your code, make SubmitSearchAsync function Asynchronously, it will avoid blocking a thread, and also releases the thread back to thread pool. However, like the code you provided, when a request is received from the SubmitSearchAsync action, a thread is drawn from the thread pool to executed its body.
The SubmitSearch is a synchronous action, it waits until the implementation is finished, and it blocks the thread until the implementation finishes.
In other word, you released one thread, but you also blocked another thread. If you need to synchronize code from an asynchronous thread, use the AsyncManager.Sync method. But in your case, AsyncManager.Sync might not help much. I suggest two possible solutions:
1) manually spawning a thread:
public virtual ActionResult SubmitSearch(SearchFormModel searchData){
    new Thread(() => {
        //your search code
    }).Start();
}

In this case, your search code might take longer, but the execution of the search will be done on a thread not a part of the pool.
2) change the SubmitSearch function asynchronously along with using Parallelism:
protected virtual async Task<ActionResult> SubmitSearch(SearchFormModel searchData){
   // Make your search code using Parallel task like below.
  var task1 = DoingTask1Async(searchData);
  var task2 = DoingTask2Async(searchData)
  await Task.WhenAll(task1,task2);
}

Aside from above suggestion, consider using Cancellation tokens, it further reduces thread usage.
Hope it helps.

A:
What we are seeing is that as more people hit SubmitSearch, the web site in general slows down. That's most likely due to all the IIS threads being locked up executing the search.

If it was the threads locked up then it wouldn't be a slow down but probably http errors were returned. Can I ask how many parallel hits causes the slow down? The threadpool in .Net4 is quite big. Also, if your search takes 10 seconds that means your database is doing the heavy-lifting. I would have a look at the DB performance: if other parts of your site are also DB dependent then several parallel DB intensive searches will slow down your application.
If for some reason you can't/don't want to perfmon the database then here is a simple test: change the database search call to a sleep call for X seconds (around 10 in this case). Then run your parallel requests and see if the site responsiveness drops or not. Your request thread numbers are the same so if that was the reason then it should have the same effect.


text:
Q: Смена background-color при скролле - jQuery/JS Здравствуйте, подскажите, как можно реализовать подобную вещь:
есть блоки (обязательно более двух, в моем случаем четыре), у всех разный цвет фона. Нужно, чтобы при скролле страницы вверх/вниз, цвет из одного плавно перетекал в другой!
Пример сайта, где это реализовано (второй-третий-четвертый блок): http://sfcd.com.
Нашел способы как это реализовано на примере двух блоков на всю страницу:
http://www.jqueryscript.net/animatio...colorizer.html. Нужно, повторяюсь, четыре цвета.
Большое спасибо!


text:
Q: Active Directory Query using LDAP Query in custom search Some of the users in the domain I'm working on have no manager assigned or no Job title so I tried to create a new query with this LDAP query in the definequery>customsearch>advanced tab:
(&(objectCategory=user)(objectClass=user))(|(!manager=*)(!title=*)

This returns zero results even though I know they exist.  Using the Custom Search creates the same search string and also returns zero results.  I tried this, based on research elsewhere, which also returns zero results.
(&(objectCategory=person)(objectClass=user))(|(!manager=*)(!title=*)

What am I doing wrong?
Also I want to search only in specific folders and their subfolders, should I pre-pend this:
(|(OU=Innsbruck)(OU=Totnes)(OU=Dueren))

where these are immediately below the domain and each location has its own sub folders of Computers, Groups, Users.

A: Your query is just invalid. That window doesn't tell you that - it just gives zero results.
You're missing closing parentheses and you need to put the OR condition inside the AND condition. And you also need to use (objectCategory=person), not (objectCategory=user). You don't really need (objectCategory=person) since (objectClass=user) is good enough to limit the search to user objects, but it doesn't hurt.
This is what it should look like:
(&(objectCategory=person)(objectClass=user)(|(!manager=*)(!title=*)))

I will usually paste my query into Notepad++, which highlights matching parentheses, so it's easy to find missing ones. Or you can break it up over multiple lines to make it easier to read and easier to spot errors:
(&
    (objectCategory=person)
    (objectClass=user)
    (|
        (!manager=*)
        (!title=*)
    )
)

Regardless of how you search (through the Users and Computers UI or through code) you can only search one OU at a time. There is no OU attribute or any other attribute that you can use in a query to limit to specific OUs.
In the UI, you can click 'Browse' in the top right to pick the OU you want to search.
If you were doing this in code, you can do a couple things to limit it to specific OUs:

*

*Search each OU separately (you can optionally set the Search Scope to not search sub-OUs if you want), or

*Search the whole domain, then look at the distinguishedName attribute of each result and discard the results from OUs you don't want.

Option #2 will probably perform faster since it's less network requests.

A: It seems to me that the filter is not compliant with RFC 4515: LDAP String Representation of Search Filters.
May be AD and the tool you are using is accepting it, but NOT filters should be in the form of (!(manager=*)).
(&(objectCategory=person)(objectClass=user)(|(!(manager=*))(!(title=*))))


text:
Q: Drag and Drop panel with label I am using WinForms that has a drag and drop feature.  Right now it is event based and I have no problems dragging the panel around and keeping the label attached to the the panel.  However, when I click on the label, in this case a number, I can't get it to raise both drag and drop events for the label and the panel at the same time, so nothing can be moved.
My thoughts to solve this were binding coordinates of the label (.Text is always 1-9) to the label coordinates.
My other thought is to create a custom UI component that would have a constructor like Tile(string labelText) which would "hide" the fact the label is there, so I would just have to use the Panel's drag and drop event.
What is the best way to handle this?

A: Perhaps something like:
private void label1_MouseDown(object sender, MouseEventArgs e)
{
    panel1_MouseDown(null, null);
}


text:
Q: Android Studio create another layout folder In Android Studio, besides the default layout folder, I need to create layout-land for different layout in landscape mode. However I couldn't add a new folder. I've tried some ways such as right click -> new -> Directory,  right click -> new -> Android resource directory, right click -> new -> Folder but all of them didn't work at all. What is the appropriate way to create a new layout folder?

A: On the left on Android studio there where you can see all your classes and packages you can see on top a selector. try altering that selector to show Project rather than your app if this is the situation.
Sometimes when you show only app contents resource folders are somehow hidden when they are empty but when you switch to project view most of the times are visible.

A: Right click on layout folder -> New -> Layout resource file
Choose Orientation in bottom frame and select Landscape


text:
Q: How to properly initialize/access an array of structs with multiple sources? I'm working on a school assignment that requires different sources and headers.
I have my data.h which holds the struct information below.
typedef struct volunteer{
    int hours;
    int tasksCompleted;
}volunteer;

typedef struct employee{
    float salary;
    int serviceYears;
    int level;
}employee;

typedef struct person{
    char firstName[20];
    char lastName[20];
    char telephoneNum[20];
    union{
        employee e;
        volunteer v;
    };
}newPerson;

I then have a volunteer.c and employee.c which contains the functions to handle things such as printing records, searching for someone by name, etc etc.
a mainMenu.c that displays the menu and takes user input to add a person record.
and finally, a mainProgram.c which ties it all together.
I'm suppose to have an array of persons[20], and I must be able to access them (get, set, etc). My main problem is here, I'm not sure where is the proper place to initialize the array of persons, and I'm not sure where I would create the get/set functions for the persons.
I tried to initialize in the mainMenu.c's main function like so.
int main(){
    //mainMenu();
    //menu();

    newPerson person[20];

    strcpy(person[0].firstName, "George");
    strcpy(person[0].lastName, "Michaels");
    strcpy(person[0].telephoneNum, "5645651232");
    person[0].v.hours= 44;
    person[0].v.tasksComplete = ;

    printf("The name is = %s\n", person[0].firstName);
    printf("The number of tasks completed is = %d\n", person[0].v.tasksCompleted);

    //testing my addFirstName method below, 1 for person[1] since I already    did person [0]
    addFirstName(1);

    return 0;
}

I just wanted to make sure I was able to access/read properly after adding the information to person[0], so nothing important in the main right now.
I then have an addFirstName(int num) function that would be called from the menu.c. (however testing it from mainProgram.c atm). I'm not sure if this would be the best way to do it, but the menu counts how many records are being added, starting from 0. so int num=0, and would be addFirstName(0);
void addFirstName(int num){
    char firstName[20];
    printf("\n\tEnter Volunteer's first name: ");
    scanf("%20s", firstName);
    strcpy(person[num].firstName, firstName);
}

However, when I try doing it this way, it says that person is undeclared, even though I initialized in the main function. This makes me think I didn't initialize the array of persons in the ideal place.
Would it be better if I were to take a struct person as the function argument?
Sorry if my question is a bit messy. Basically I would just like to know where would the most logical place/method to initialize the array of persons, and the best place/method to have my get/set methods as I would need to get/set the person from my other sources, (volunteer.c, employee.c, mainMenu.c)

A: void addFirstName(newPerson *const person){
    char firstName[20];
    printf("\n\tEnter Student's first name: ");
    scanf("%20s", firstName);
    strcpy(person->firstName, firstName);
}

in main.c
addFirstName(&person[1]);

A: Your function addFirstName is doing reference to an array declared in main, that's why  it says person is undeclared.
Like you said you can put the person array as the function argument and it will work
void addFirstName(newPerson *person, int num){
    char firstName[20];
    printf("\n\tEnter Student's first name: ");
    scanf("%20s", firstName);
    strcpy(person[num].firstName, firstName);
}

And about the best way to to place methods for initialize the array of persons, that's up to you, you can have your own style and choose the best that works for you, since you already have volunteer.c and employee.c, maybe the nest logical step would be person.c


text:
Q: expand aliases before calling /usr/bin/time When I use the shell builtin time, I can pass any command I would pass to the shell without time.  But when I use the external /usr/bin/time, I cannot pass a shell alias, because /usr/bin/time is naturally not aware of those:
$ /usr/bin/time ll
/usr/bin/time: cannot run ll: No such file or directory

How can I convince the shell to expand the alias for ll before passing it on to /usr/bin/time?  Parsing the output of alias ll is tricky, in particular since the definition of the alias contains other aliases.

My reason for using /usr/bin/time is to measure peak memory usage.

A: You can define an alias for /usr/bin/time as:
alias 'ubtime=/usr/bin/time '

Or
alias 'ubtime=command time '

if you don't want to hard code the path to the time executable.
The trick is in the trailing space in the alias definition that tells the shell that aliases must be substituted after that alias so that
ubtime ll

Will actually be expanded to
/usr/bin/time ls -l

(assuming ll is an alias to ls -l).
In any case, /usr/bin/time being a standalone executable, it cannot time pipelines or compound commands or functions or shell builtins, so it cannot time the expansion of arbitrary aliases.
If the reason for using /usr/bin/time is because you prefer its default output format over the one for the time keywork, note that in many shells, the format can be modified. For instance, in zsh:
$ TIMEFMT=$'\e[31;1m%J\e[m: U:%U S:%S (%*E total) [avgtext:%X avgdata:%D maxmem:%M]'
$ time ls -l | head -n1
total 288072444
ls -l: U:0.00s S:0.01s (0.017 total) [avgtext:0 avgdata:0 maxmem:3]
head -n1: U:0.00s S:0.00s (0.015 total) [avgtext:0 avgdata:0 maxmem:3]

(the \e[31;1m for coloured (bold red) output).

A: This may work in bash:
/usr/bin/time  $(alias "ll" | sed "s/^alias [^=]*='\(.*\)'/\1/")

but not yet fully safe for arbitrary aliases, regarding spaces, escaped characters, nested aliases and functions etc.
I guess there is no non-ugly solution possible. That's why shells have a built-in time. Even if alias expansion would be easier, the next problem would be how to time functions. Note that aliases may even use shell functions.
If your aliases are defined in bash's configuration files and if you don't care about the timed overhead you could try
/usr/bin/time bash -l -i -c "ll"


text:
Q: making a calculation on a timestamp array It is easy to perform a calculation on a timestamp:
from datetime import datetime
timestamp = 1456741175
dt = datetime.fromtimestamp(timestamp)
print(dt.day)
# Week day number
print(dt.weekday())
print(dt.minute)
print(dt.second)

But how about if my timestamp is an array, instead of a single value. For e.g:
timestamp = [1456741175, 1456741176, 1456741177, ....]

With a loop, it takes a lot of time as my array's length is more than 3 million. So, how can I perform the same calculation on an array of timestamps using a method that is simple and fast?

A: pandas is pretty fast.
# timestamps.py
from time import localtime
import pandas as pd

timestamps = range(1000000)    # 1,000,000 seconds starting from Jan 1, 1970

def test_pandas():
    datetimes = pd.to_datetime(timestamps, unit='s')
    # if you just want the week days
    week_days = datetimes.weekday

def test_time():
    week_days = [localtime(t).tm_wday for t in timestamps]

Compare execution times with timeit:
$ python -m timeit -s 'import timestamps' 'timestamps.test_time()'
10 loops, best of 3: 2.11 sec per loop
$ python -m timeit -s 'import timestamps' 'timestamps.test_pandas()'
10 loops, best of 3: 357 msec per loop

Pandas is about 6 times faster than using a list comprehension, which it itself a little faster than the map() solution in the accepted answer.

A: It can be calculated parallelly using multiprocessing library. It will spawn number of processes and distribute the input values to those.
You can rewrite the code:
from multiprocessing import Pool
from datetime import datetime

def datetime_from_timestamp(timestamp):
    dt = datetime.fromtimestamp(timestamp)
    print(dt.day)

timestamps = [1456741175, 1456741176, 145674117]

pool = Pool(processes=4)
pool.map(datetime_from_timestamp, timestamps)

A: e.g.
map(lambda x: datetime.fromtimestamp(x).weekday(), timestamp)


text:
Q: Synchronized (Hash)Map of Singletons Description below the code...
// Singleton
public static final Map<String, Account> SHARED_ACCOUNT_HASHMAP =
        Collections.synchronizedMap(new HashMap<>());

public init(String[] credentials) {

    Account account = null;

    String uniqueID = uniqueAccountIdentifier(credentials);

    if (SHARED_ACCOUNT_HASHMAP.containsKey(uniqueID)) {
        account = SHARED_ACCOUNT_HASHMAP.get(uniqueID);
        log("...retrieved Shared Account object: %s", uniqueID);
    }

    // create the Account object (if necessary)
    if (account == null) {
        account = new Account(credentials);

        // Store it in the SHARED_ACCOUNT_HASHMAP
        SHARED_ACCOUNT_HASHMAP.put(uniqueID, account);
        log("...created Account object: %s",uniqueID);

    }

}

What I want to achieve

*

*There are multiple Threads accessing this Singleton HashMap

*The goal of this HashMap is to only allow the creation of ONE Account per uniqueID

*The account later can be retrieved by various threads for Account operations

*Each Thread has this init() method and runs it once.

*So the first Thread that cannot find an existing uniqueID Account, creates a new one and places it in the HashMap. The next Thread finds that for the same uniqueID, there is an Account object already - so retrieves it for its own use later

My problem...

*

*How can I get the other Threads (second, third, etc.) to wait while the first Thread is inserting a new Account object?

*to phrase it another way, there should never be 2 threads ever that receive a value of null when reading the HashMap for the same uniqueID key. The first thread may receive a value of null, but the second should retrieve the Account object that the first placed there.

A: According to the docs for synchronizedMap()

Returns a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map.
It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views

In other words you still need to have synchronized access to SHARED_ACCOUNT_HASHMAP:
public init(String[] credentials) {
    Account account = null;
    String uniqueID = uniqueAccountIdentifier(credentials);

    synchronized (SHARED_ACCOUNT_HASHMAP) {
        if (SHARED_ACCOUNT_HASHMAP.containsKey(uniqueID)) {
            account = SHARED_ACCOUNT_HASHMAP.get(uniqueID);
            log("...retrieved Shared Account object: %s", uniqueID);
        }

        // create the Account object (if necessary)
        if (account == null) {
            account = new Account(credentials);

            // Store it in the SHARED_ACCOUNT_HASHMAP
            SHARED_ACCOUNT_HASHMAP.put(uniqueID, account);
            log("...created Account object: %s",uniqueID);
        }
    }
}

A: Consider using ReadWriteLock if you have multiple readers/writers (see ReadWriteLock example).
Generally the ConcurrentHashMap performs better than the sinchronized hash map you are using.

A: In the following code I can feel smell of race condition check-then-act as you are trying to perform two operations on the synchronised map (containsKey and get):
if (SHARED_ACCOUNT_HASHMAP.containsKey(uniqueID)) {
        account = SHARED_ACCOUNT_HASHMAP.get(uniqueID);
        log("...retrieved Shared Account object: %s", uniqueID);
 }

So to avoid race condition you need to synchronize over this map as:
synchronized (synchronizedMap) {
  if (SHARED_ACCOUNT_HASHMAP.containsKey(uniqueID)) {
            account = SHARED_ACCOUNT_HASHMAP.get(uniqueID);
            log("...retrieved Shared Account object: %s", uniqueID);
     }
  // rest of the code.
}

Actually the synchronizedMap can protect itself against internal race conditions that could corrupt the map data but for external conditions (like above) you need to take care of that. If you feel you are using synchronized block at many places you can also think of using a regular map along with synchronized blocks. You will find this question also useful.


text:
Q: Is there a way to download a lower quality image from a source uri? I currently have a lot of images hosted on a website, and I get them with their respective URLs with React Native. But each image is very large, and sometimes, I only need small versions of the images. Is there a way to download a small version of the same image from the same URL?

A: To download smaller image server has to implement the feature so that the client can send query or parameters like width=100 & height=100 to the server and get the requested image in response.
But if you want to resize the images without concerning about what server is giving. You can set your compression code on the client side and store/show image as you want.
You can use image resize libraries like react-native-image-resizer


text:
Q: Avoid "Complete action using" dialog for sending SMS I have following code which i am using for opening send SMS window:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", msgString);
sendIntent.setType("vnd.android-dir/mms-sms");
activity.startActivity( sendIntent );

Above code avoids "Complete action using" dialog that Android displays when there are two many apps are registered for sending SMS.
This code works on some device bug not on all, so is there any generic solution which will work on all the devices, to open a Send SMS screen without displaying "Complete action using" dialog.

A: please try this code
public void sendSMS()
{
    SmsManager sm = SmsManager.getDefault();
    String number = "123456789";
    String msg = "Hello";
    sm.sendTextMessage(number, null, msg, null, null);
}

A: Use below code
private void send() {
    Intent shareIntent = new Intent(Intent.ACTION_VIEW);
    shareIntent.setType("vnd.android-dir/mms-sms");
    shareIntent.putExtra("sms_body", "hello this is test");

    List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(shareIntent, 0);
    if (!resInfo.isEmpty()) {
        for (ResolveInfo resolveInfo : resInfo) {
            String packageName = resolveInfo.activityInfo.packageName;
            if (packageName.equals("com.android.mms")) {
                shareIntent.setPackage(packageName);
                            break;
            } else {
                // Else show chooser
            }
        }
        startActivity(shareIntent);
    }
}

Update for a perticular Activity.
There are two Activities of com.android.mms application, .ui.ConversationComposer and  ui.ComposeMessageMms. You can use only two of them. As my above answer this was using .ui.ConversationComposer. So to use second activity use below code.
try {
    Intent shareIntent = new Intent(Intent.ACTION_VIEW);
    shareIntent.setType("vnd.android-dir/mms-sms");
    shareIntent.putExtra("sms_body", "hello this is test");
    shareIntent.setComponent(new ComponentName("com.android.mms","com.android.mms.ui.ComposeMessageMms"));
    startActivity(shareIntent);
} catch (ActivityNotFoundException exception) {
    // This will happen if Device have no MMS application. Handle this exception.
}

This will show android default application to send MMS.

A: You can resolve the intent before using it, to see what is matched :
List<ResolveInfo> infos = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : infos) {
    // Searching for a System installed package
    if (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM > 0) {
        intent.setComponent(new ComponentName(
               info.activityInfo.applicationInfo.packageName,
               info.activityInfo.name));
    }
}

This has not been tested, but should work, as the flag 'SYSTEM' is apparently the flag for apps that are in the system image.
If this does not work, you can take the first item in the list, or search for a package name such as google or android, or see if preferredOrder can be of any help.
edit
queryIntentActivities is of course queryIntentActivities and ActivityInfo.FLAG_SYSTEM is ApplicationInfo.FLAG_SYSTEM. I must have beed tired when I wrote this...


text:
Q: Three20 - Attempt to Refresh TTThumbsViewController stays stuck on "Loading..." I am using a TTThumbsViewController to display a gallery. Users can upload photos to a server and when the upload is complete I post a notification which I receive further up the navigation stack at the TTThumbViewController where I want to reload the gallery so that when the user navigates back the gallery includes their newly added photo.
I call the following in my TTThumbsViewController subclass when I receive the notification:
[self invalidateModel];
[self reload];

This results in a message of "Loading" with a spinner but it stays stuck there. Hoping someone can nudge me in the right direction. Thank you!
Other things I've tried:
[self invalidateModel];

or
[self invalidateModel];
[self reload];
[self updateView];

or
[self invalidateModel];
[self reloadIfNeeded];

I've reviewed this SO question and tried the approach:
refresh TTThumbsViewController on a buttonClick in Three20

A: Use the Following code
creating model
- (void)createModel {

    [self setPhotoSourceToView];

}

Setting the NSNotification
NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setPhotoSourceToView) name:NOTIF_UPDATES object:nil];

setPhotoSourceToView Function
- (void)setPhotoSourceToView {
       if (!doPhotoSource) {
                //call to datasource
                XXXPhotoSource=[[XXXThumbnailPhotoSource alloc]initWithURL:urlForDo ];

                }
            self.photoSource = XXXPhotoSource;

        }
}

This works fine

A: I just did this and it worked fine for me.
[self reload];


text:
Q: Can we use 'one of the' for the plural? whch sentense is correct of the following? Which sentence is correct?

Flour and meat are the one of the most used food ingredients in the world.
Flour and meat are two of the most used food ingredients in the world.

A: Flour and meat are two different ingredients, so you have to use the plural.
As such, only the second sentence is correct:

✔ Flour and meat are two of the most used food ingredients in the world.

However, it's also possible to rephrase the first sentence in a way that preserves some of its sense while having it be grammatical:

✔ Flour and meat are among the most used food ingredients in the world.