text:
Q: Python Import using __init__.py instead of adding to sys.path This is my file structure.
/working dir
    __init__.py
    main.py
    /packages
        __init__.py
        snafu.py
        /subfolder1
            __init__.py
            foo.py
        /subfolder2
            __init__.py
            bar.py
        /many_more
            ...

If I run main.py it will try to import, from subfolder1.foo import something
But foo.py will try to import subfolder2 which won't work because subfolder2 is not found.
It would be way too much work to go into every file and change every import statement to from packages.a_subfolder.whatever import something
I have gotten it to work by adding /packages to the sys.path, but I would prefer not to do this. Is there a way to fix this using __init__.py files?
Would adding import * to the /packages __init__.py file work?
The many_more/ folders are third party packages I downloaded, since i work on this on different computers instead of installing the packages on every computer I work on it just uses the one in the folder.
For example: to use googledrive in your program you need about 10 different packages to get it to work.

A: In your case it seems you want to import modules present in parent dierectory.
Having following code in the file from which you want to import the module in the parent directory should work:
import sys
sys.path.append('.')
sys.path.append('..')

A: So it looks like the only way that worked was to add
import sys, os
packagepath = os.getcwd() + '/packages'
sys.path.append(packagepath)

to the /packages __init__.py file and call it using
from packages.subfolder1.foo import something


text:
Q: Update progress bar slower I am using progress to render progress bars for a long computational process.  The issue stems from the fact that I am using a for loop with lots of items that are each processed very quickly.  This causes the progress bar to update itself rapidly, causing the time remaining to change quickly between nearby seconds, such as flickering between 10 and 11 or 10 and 9.
I've tried adding time.sleep(1) but this slows down the computation as well.
My code looks as follows:
fbar = Bar("Scanning:",max=maxindex,suffix='%(percent)d%% %(eta)s seconds remaining...')
for index, row in df.iterrows():
    if index == 0:
        # setup computation
    else:
        # computation
    fbar.next()
fbar.finish()

I would like the progress bar to update slower, such that it doesn't look like the time remaining is flickering.

A: You can use TQDM, it's very robust and configurable and will solve your problem!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reconfiguring NServiceBus Loses Messages This is my first post on StackOverflow.
I am trying to put NServiceBus behind an interface that looks like the following:
interface IMessagingService
{
    IObserver<T> RegisterPublication<T>() where T : IPublishedMessage;
    IObservable<T> RegisterSubscription<T>() where T : IPublishedMessage;
}

In order to support this interface without forcing users to have an explictit Start() call, I need to reconfigure the bus each time RegisterSubscription is invoked with a call to a method that looks like this:
IBus ConfigureBus()
{
    Configure config = BuildConfiguration();
    return config.CreateBus().Start();
}

I can't copy and paste the real code, but hopefully you can see that I need to have a started bus to listen for messages once RegisterSubscription is invoked. I need to add subscribers on subsequent invocations.
The problem that I am running into is that each call to ConfigureBus() seems to be spinning up more threads and results in messages being lost. My handler instances are not invoked, yet NServiceBus logs that it finished handling each of the messages.
With four calls to RegisterSubscription, I lose about 40% of my messages.
Is there a safe way to reconfigure and restart the IBus on the fly without causing this problem? The IBus.Subscribe doesn't seem to work.

A: @bsf's answer
I found a solution. CreateBus() returns an IStarableBus. If I keep a static reference to that and dispose it before my next call to CreateBus(), everything seems to work fine.


text:
Q: Class not found when unmarshalling Im trying to pass objects between fragments, and i use Parcelable interface.
Here is my class but something is messed up with the ArrayList property, as i got:
java.lang.ClassNotFoundException: hu.company.myapp.modul.RaceDayUnit

and my class has an ArrayList of RaceDayUnits. All was worked properly until i started to use ArrayList.
Please help if you can.
My class:
public class RegattaUnit implements Parcelable {

public String id;
public String name;
public String type;
public String status;
public String token;

public ArrayList<RaceDayUnit> raceDays = new ArrayList<RaceDayUnit>();

public static class Status {
    public static String NEW = "invited";
    public static String JOINED = "joined";
    public static String DECLINED = "declined";
}

public RegattaUnit() {
}

// not used at all
@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel out, int flags) {
    out.writeString(id);
    out.writeString(name);
    out.writeString(type);
    out.writeString(status);
    out.writeString(token);
    out.writeList(raceDays);
}

private RegattaUnit(Parcel in) {
    id = in.readString();
    name = in.readString();
    type = in.readString();
    status = in.readString();
    token = in.readString();

    raceDays = new ArrayList<RaceDayUnit>();
    in.readList(raceDays, null);
}

public static final Creator<RegattaUnit> CREATOR = new Creator<RegattaUnit>() {

    public RegattaUnit createFromParcel(Parcel in) {
        return new RegattaUnit(in);
    }

    public RegattaUnit[] newArray(int size) {
        return new RegattaUnit[size];
    }
};

 public RegattaUnit(JSONObject regattaJSONObject, String status) throws JSONException {

  //parsing from a jsonObject, the ArrayList is getting filled here.

    }

}

}

And log output:
04-27 12:54:23.014: E/Parcel(9257): Class not found when unmarshalling: hu.mycomp.myapp.modul.RaceDayUnit
    04-27 12:54:23.014: E/Parcel(9257): java.lang.ClassNotFoundException: hu.mycomp.myapp.modul.RaceDayUnit
    04-27 12:54:23.014: E/Parcel(9257):     at java.lang.Class.classForName(Native Method)
    04-27 12:54:23.014: E/Parcel(9257):     at java.lang.Class.forName(Class.java:309)
    04-27 12:54:23.014: E/Parcel(9257):     at java.lang.Class.forName(Class.java:273)
    04-27 12:54:23.014: E/Parcel(9257):     at android.os.Parcel.readParcelableCreator(Parcel.java:2281)
    04-27 12:54:23.014: E/Parcel(9257):     at android.os.Parcel.readParcelable(Parcel.java:2245)
    04-27 12:54:23.014: E/Parcel(9257):     at android.os.Parcel.readValue(Parcel.java:2152)
    04-27 12:54:23.014: E/Parcel(9257):     at android.os.Parcel.readListInternal(Parcel.java:2526)
    04-27 12:54:23.014: E/Parcel(9257):     at android.os.Parcel.readList(Parcel.java:1661)
    04-27 12:54:23.014: E/Parcel(9257):     at hu.mycomp.myapp.modul.RegattaUnit.<init>(RegattaUnit.java:58)
    04-27 12:54:23.014: E/Parcel(9257):     at hu.mycomp.myapp.RegattaUnit.<init>(RegattaUnit.java:14)
    04-27 12:54:23.014: E/Parcel(9257):     at hu.mycomp.myapp.RegattaUnit$1.createFromParcel(RegattaUnit.java:113)
    04-27 12:54:23.014: E/Parcel(9257):     at hu.mycomp.myapp.RegattaUnit$1.createFromParcel(RegattaUnit.java:110)
    04-27 12:54:23.014: E/Parcel(9257):     at android.os.Parcel.readParcelable(Parcel.java:2252)
    04-27 12:54:23.014: E/Parcel(9257):     at android.os.Parcel.readValue(Parcel.java:2152)
    04-27 12:54:23.014: E/Parcel(9257):     at android.os.Parcel.readArrayMapInternal(Parcel.java:2485)
    04-27 12:54:23.014: E/Parcel(9257):     at android.os.BaseBundle.unparcel(BaseBundle.java:221)
    04-27 12:54:23.014: E/Parcel(9257):     at android.os.BaseBundle.getString(BaseBundle.java:918)
    04-27 12:54:23.014: E/Parcel(9257):     at hu.mycomp.myapp.service.GpsService.onStartCommand(GpsService.java:117)
    04-27 12:54:23.014: E/Parcel(9257):     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2894)
    04-27 12:54:23.014: E/Parcel(9257):     at android.app.ActivityThread.access$2100(ActivityThread.java:151)
    04-27 12:54:23.014: E/Parcel(9257):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1401)
    04-27 12:54:23.014: E/Parcel(9257):     at android.os.Handler.dispatchMessage(Handler.java:102)
    04-27 12:54:23.014: E/Parcel(9257):     at android.os.Looper.loop(Looper.java:135)
    04-27 12:54:23.014: E/Parcel(9257):     at android.app.ActivityThread.main(ActivityThread.java:5254)
    04-27 12:54:23.014: E/Parcel(9257):     at java.lang.reflect.Method.invoke(Native Method)
    04-27 12:54:23.014: E/Parcel(9257):     at java.lang.reflect.Method.invoke(Method.java:372)
    04-27 12:54:23.014: E/Parcel(9257):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    04-27 12:54:23.014: E/Parcel(9257):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    04-27 12:54:23.014: E/Parcel(9257): Caused by: java.lang.ClassNotFoundException: Didn't find class "hu.mycomp.myapp.modul.RaceDayUnit" on path: DexPathList[[directory "."],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
    04-27 12:54:23.014: E/Parcel(9257):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    04-27 12:54:23.014: E/Parcel(9257):     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    04-27 12:54:23.014: E/Parcel(9257):     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    04-27 12:54:23.014: E/Parcel(9257):     ... 28 more
    04-27 12:54:23.014: E/Parcel(9257):     Suppressed: java.lang.ClassNotFoundException: hu.mycomp.myapp.modul.RaceDayUnit
    04-27 12:54:23.014: E/Parcel(9257):         at java.lang.Class.classForName(Native Method)
    04-27 12:54:23.014: E/Parcel(9257):         at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
    04-27 12:54:23.014: E/Parcel(9257):         at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
    04-27 12:54:23.014: E/Parcel(9257):         at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
    04-27 12:54:23.014: E/Parcel(9257):         ... 29 more
    04-27 12:54:23.014: E/Parcel(9257):     Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
    04-27 12:54:23.015: D/AndroidRuntime(9257): Shutting down VM
    04-27 12:54:23.021: E/AndroidRuntime(9257): FATAL EXCEPTION: main
    04-27 12:54:23.021: E/AndroidRuntime(9257): Process: hu.mycomp.myapp, PID: 9257
    04-27 12:54:23.021: E/AndroidRuntime(9257): java.lang.RuntimeException: Unable to start service hu.mycomp.myapp.service.GpsService@16aad1da with Intent { flg=0x4 cmp=hu.mycomp.myapp/.service.GpsService (has extras) }: android.os.BadParcelableException: ClassNotFoundException when unmarshalling: hu.mycomp.myapp.modul.RaceDayUnit
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2911)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.app.ActivityThread.access$2100(ActivityThread.java:151)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1401)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.os.Handler.dispatchMessage(Handler.java:102)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.os.Looper.loop(Looper.java:135)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.app.ActivityThread.main(ActivityThread.java:5254)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at java.lang.reflect.Method.invoke(Native Method)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at java.lang.reflect.Method.invoke(Method.java:372)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    04-27 12:54:23.021: E/AndroidRuntime(9257): Caused by: android.os.BadParcelableException: ClassNotFoundException when unmarshalling: hu.mycomp.myapp.modul.RaceDayUnit
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.os.Parcel.readParcelableCreator(Parcel.java:2295)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.os.Parcel.readParcelable(Parcel.java:2245)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.os.Parcel.readValue(Parcel.java:2152)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.os.Parcel.readListInternal(Parcel.java:2526)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.os.Parcel.readList(Parcel.java:1661)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at hu.mycomp.myapp.modul.RegattaUnit.<init>(RegattaUnit.java:58)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at hu.mycomp.myapp.modul.RegattaUnit.<init>(RegattaUnit.java:14)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at hu.mycomp.myapp.modul.RegattaUnit$1.createFromParcel(RegattaUnit.java:113)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at hu.mycomp.myapp.modul.RegattaUnit$1.createFromParcel(RegattaUnit.java:110)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.os.Parcel.readParcelable(Parcel.java:2252)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.os.Parcel.readValue(Parcel.java:2152)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.os.Parcel.readArrayMapInternal(Parcel.java:2485)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.os.BaseBundle.unparcel(BaseBundle.java:221)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.os.BaseBundle.getString(BaseBundle.java:918)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at hu.mycomp.myapp.service.GpsService.onStartCommand(GpsService.java:117)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2894)
    04-27 12:54:23.021: E/AndroidRuntime(9257):     ... 9 more

A: Rather than passing in null to readList() as the second parameter, pass in the ClassLoader that has RaceUnit. If RegattaUnit and RaceUnit are both in the same app and DEX file, getClass().getClassLoader() or RaceUnit.class.getClassLoader() should work.
(and now I am wondering what the SI unit of regatta actually is... :-)

A: It says classNotFoundException, so probably RaceDayUnit class not in your classpath. Have check hu.mycomp.myapp.modul package is in your source package?


text:
Q: Unexpected results from custom sort using VBA I am trying to sort a table in my spreadsheet, using a custom sort. After a bit back and forth, I came up with this macro:
Sub sort_SI()
    With Resultat_SI.Sort
        .SortFields.Clear
        .SetRange Resultat_SI.Range(Resultat_SI.Range("A1"), Resultat_SI.Range("J" & Resultat_SI.Rows.Count).End(xlUp))
        .SortFields.Add Key:=Resultat_SI.Columns("J"), CustomOrder:=Join(Application.Transpose(Fargar.ListObjects("Fargekoder").ListColumns(3).DataBodyRange), ",")
        .Header = xlYes
        .Apply
    End With
End Sub

It runs just fine, and the order of my entries does change, after the sub is finished, but there seems no sense to the ordering. At the very least I would expect the lines with the same values in column J to be grouped together, but this does not seem to be the case.
Printing Sort.SetRangeto the immediate window shows that it is

*

*$A$1:$J$20
as expected, while Join(Application.Transpose(Fargar.ListObjects("Fargekoder").ListColumns(3).DataBodyRange), ",") gives

*

*Green,Brown,Black,Black (600/610),Unmarked,Pink,Blue,White,White (378/428),Yellow,Ukjent,Red
also as expected.
The two sheets I am referencing in the sub looks like this:
Resultat_SI

Fargekoder

Basically I want my table in Resultat_SI to be sorted in the same order as the colors appear in the table in Fargekoder, with blank results appearing at the bottom, but I am failing miserably at achieving this result. Can someone please tell me where I am going wrong?

A: The issue with sorting my table was not with the sorting code itself, but rather with the formulas used to populate the table. I had locked the cell references in the formulas, meaning that once a line had been sorted to a different location in the table, the formulas on that line still referenced whatever was now shown to its previous location.
In other words, all it took to fix the problem was removing one $ from each cell reference, in order to have them change to the appropriate cells after having been sorted.
I.e. changing

*

*=IFERROR(VLOOKUP($H$2;Fargekoder;3;FALSE);"")
to

*

*=IFERROR(VLOOKUP($H2;Fargekoder;3;FALSE);"")
was all it took.


text:
Q: Postgresql performance issue on DigitalOcean VPS I have two instances of Postgresql. One is local (Macbook Pro Retina 15), another is on Digital Ocean $10 instance. Config is almost identical (mostly basic). The same db dump loaded on both. The issue is that execution time of the simple select query against 50k items table is almost 5x higher on remote instance.
Local:
explain (analyze,buffers) select * from car_trims limit 100 offset 40000;
                                                     QUERY PLAN
---------------------------------------------------------------------------------------------------------------------
 Limit  (cost=842.14..844.24 rows=100 width=66) (actual time=11.193..11.212 rows=100 loops=1)
   Buffers: shared hit=450
   ->  Seq Scan on car_trims  (cost=0.00..1139.01 rows=54101 width=66) (actual time=0.006..6.832 rows=40100 loops=1)
         Buffers: shared hit=450
 Planning time: 0.053 ms
 Execution time: 11.236 ms
(6 rows)

Remote:
explain (analyze,buffers) select * from car_trims limit 100 offset 40000;
                                                      QUERY PLAN
----------------------------------------------------------------------------------------------------------------------
 Limit  (cost=830.91..832.99 rows=100 width=66) (actual time=46.167..46.321 rows=100 loops=1)
   Buffers: shared hit=439
   ->  Seq Scan on car_trims  (cost=0.00..1124.18 rows=54118 width=66) (actual time=0.060..26.080 rows=40100 loops=1)
         Buffers: shared hit=439
 Planning time: 0.206 ms
 Execution time: 46.442 ms
(6 rows)

Is that how it's supposed to be due to more powerful hardware? Or there's a room for tuning? What tools could I use to localize the issue?
UPD: I did some warm-up before executing these queries. Also just in case I performed vacuum and reindexed this table.


text: Q: NSScroller draws above NSView I have NSView with 2 subviews: NSScrollView(with NSTableView inside) and custom NSView. Sometimes i need to resize custom NSView to show it above part of NSScrollView, but when i'm scrolling content of table NSScroller draws above my custom NSView. How to avoid it?


text:
Q: Jenkins Or condition in when block I'm trying to implement an or condition for the execution of a stage.
The behaviour I seek is that if the PROJECT_TAG parameters is either project1, or project2, do not execute the stage.
I've tried the following, but it does not seem to work, and executes the stage regardless:
  stages {
    stage('Cloudformation Init') {
      when {
        expression {params.PROJECT_TAG != 'project1' || params.PROJECT_TAG != 'project2'}
      }

If I just define one parameter in the when block, like the following, it works, and bypasses that particular stage if the params.PROJECT_TAG == project1. For example, this works:
  stages {
    stage('Cloudformation Init') {
      when {
        expression {params.PROJECT_TAG != 'project1'}
      }

However, I really need the pipeline to be more flexible, and therefore needed to implment an or condition into the when block.
Is this possible?

A: Try this:
 when {
     anyOf {
         expression {params.PROJECT_TAG != 'project1'}; expression {params.PROJECT_TAG != 'project2'}
     }
 }


text:
Q: Dictionary of lists won't save as DataFrame Background:
I have a dictionary of lists, with with the following structure:(note: there are more keys than shown here):
urls = {

'Course': ['https://www.simplyrecipes.com/recipes/course/appetizer/',
                'https://www.simplyrecipes.com/recipes/course/breakfast/',
                'https://www.simplyrecipes.com/recipes/course/brunch/',
                'https://www.simplyrecipes.com/recipes/course/dessert/',
                'https://www.simplyrecipes.com/recipes/course/dinner/',
                'https://www.simplyrecipes.com/recipes/course/drink/',
                'https://www.simplyrecipes.com/recipes/course/lunch/',
                'https://www.simplyrecipes.com/recipes/course/salad/',
                'https://www.simplyrecipes.com/recipes/course/sandwich/',
                'https://www.simplyrecipes.com/recipes/course/side_dish/',
                'https://www.simplyrecipes.com/recipes/course/snack/',
                'https://www.simplyrecipes.com/recipes/course/soup/',
                'https://www.simplyrecipes.com/recipes/course/soup_and_stew/',
                'https://www.simplyrecipes.com/recipes/course/stew/'],
     'Cuisine': ['https://www.simplyrecipes.com/recipes/cuisine/african/',
                 'https://www.simplyrecipes.com/recipes/cuisine/basque/',
                 'https://www.simplyrecipes.com/recipes/cuisine/belgian/',
                 'https://www.simplyrecipes.com/recipes/cuisine/brazilian/',
                 'https://www.simplyrecipes.com/recipes/cuisine/british/']
}

What I'm trying to do: Using BeautifulSoup, I intend to iterate through these links and scrape certain information from a recipe websites. I would like to store this information in a pandas DataFrame, for ease of iterating through, with a loop.
My Code (that doesn't work):I have written this code, that I was expecting to create a DataFrame -
df=pd.DataFrame.from_dict(urls,orient='index').transpose()

Code Error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-46950d5ba288> in <module>
----> 1 df=pd.DataFrame.from_dict(result,orient='index').transpose()

~/anaconda3/envs/DataScience/lib/python3.7/site-packages/pandas/core/frame.py in from_dict(cls, data, orient, dtype, columns)
   1233         orient = orient.lower()
   1234         if orient == "index":
-> 1235             if len(data) > 0:
   1236                 # TODO speed up Series case
   1237                 if isinstance(list(data.values())[0], (Series, dict)):

TypeError: object of type 'Response' has no len()

Code for creating the structureThis is the code, that creates the structure:
from recipe_scrapers import scrape_me
import re

scraper = scrape_me('https://www.simplyrecipes.com/index/')
raw_dict = scraper.links()
result = []
for d in raw_dict:
    for key, value in d.items():
        # If the key is not equal to 'href' and the value doesn't contain ''/recipe' then that pair is skipped.
        if key != "href" or "https://www.simplyrecipes.com/recipes/" not in value:
            continue
        txt = ''
        for i in re.findall("recipes/.*", value):
            txt += i
            title = txt.split('/')[1]

            result.append({title: value})

Note:recipe_scraper (specifically scraper.links())  dependency allows you to return a list of dictionaries containing all of the <a> tag attributes. The attribute names are the dictionary keys.
Help:I would be very grateful if someone could tell me why my code isn't work (I'm relatively new!) and what recommendations you might have for the correct / most elegant way to store this information for iterating through, using a loop.

A: I was able to save my structure into a dataframe successfully using: db = pd.DataFrame.from_dict(urls, orient='index')


text:
Q: JavaScript: Function creates arrays as values of the returned object I'm creating a function that accepts an array and a callback, and returns an object. It is designed to iterate through the array and perform the callback on each element. Then, each return value from the callback is saved as a key on the object. The value associated with each key will be an array consisting of all the elements that resulted in that return value when passed into the callback.
function groupBy(array, callback) {
  let obj = {};
  let newArr = [];
  //loop through each ele w/ callback
  //return value saved as key in obj obj[key] = value
  array.forEach(ele => {
    let key = callback(ele)
    obj[key] = callback(ele);
    if (obj[key] === undefined) {
      obj[key] = array[ele]
      newArr.push(array[ele]);
        } else {
        newArr.push(obj[key]);
        }
    });
  return obj;
}

The function should create arrays as values of the returned object but it doesn't. Also, it does not group array items together if the callback returns the same value when they are passed in.
Test cases(s):
const decimals = [1.3, 2.1, 2.4];
const floored = function(num) { return Math.floor(num); };
console.log(groupBy(decimals, floored)); // should log: **{ 1: [1.3], 2: [2.1, 2.4] }**

Instead I get: { 1: 1, 2: 2 }</be
expected { odd: 'odd', even: 'even' } to deeply equal { odd: [ 1, 3, 5 ], even: [ 2, 4 ] }

A: There are more than 1 problem with your code.
First, you are using obj[key] = callback(ele) asignment which assigns key to object[key]
Second, you are pushing into the newArr array but never using it.
Snippet below  might help you.

function groupBy(array, callback) {
  let obj = {};

  //loop through each ele w/ callback
  //return value saved as key in obj obj[key] = value
  array.forEach(ele => {
    let key = callback(ele)
    obj[key] = obj[key] || [];
    //                  ^^^^ Create an empty array if it doesn't exist
    obj[key].push(ele)
  });
  return obj;
}

const decimals = [1.3, 2.1, 2.4];
const floored = function(num) {
  return Math.floor(num);
};
console.log(groupBy(decimals, floored)); // should log: **{ 1: [1.3], 2: [2.1, 2.4] }**

Update
You can also use Array.reduce()

function groupBy(array, callback) {

  return array.reduce((acc,cur) => {
    let key = callback(cur)
    acc[key] = acc[key] || [];
    acc[key].push(cur)
    return acc;
  },{})

}

const decimals = [1.3, 2.1, 2.4];

const floored = function(num) {
  return Math.floor(num);
};

console.log(groupBy(decimals, floored));

A: function groupBy(array, callback) {
  let obj = {};
  //loop through each ele w/ callback
  //return value saved as key in obj obj[key] = value
  array.forEach(ele => {
    let key = callback(ele)
    if (obj[key] === undefined) {
      obj[key] = [ele]
        } else {
        obj[key].push(ele);
        }
    });
  return obj;
}

A: You should not override the key, instead you should get array and push it to the array.

function groupBy(array, callback) {
  let obj = {};
  let newArr = [];
  //loop through each ele w/ callback
  //return value saved as key in obj obj[key] = value
  array.forEach(ele => {
    let key = callback(ele)

    //obj[key] = key;
    let newArr = obj[key];
    if (newArr === undefined) {
        newArr = new Array();
    }
    newArr.push(ele);
    obj[key] = newArr;
    });
  return obj;
}

const decimals = [1.3, 2.1, 2.4];
const floored = function(num) { return Math.floor(num); };
console.log(groupBy(decimals, floored));


text:
Q: How to keep a branch synchronized/updated with master? At the moment git is doing my head in, I cannot come up with the best solution for the following.
There are two branches, one called master and one called mobiledevicesupport. I want to keep mobiledevicesupport as a continuous branch that will be merged/synced with the master branch whenever mobiledevicesupport is stable. This would merge changes from mobiledevicesupport into master but also bring all the changes from master into mobiledevicesupport so that branch can continue to be worked on and the features improved or amended. This needs to work with a central repository and multiple developers.
Please an example of similar workflows other people use or just tell me if this idea is stupid and I should consider other options. At the moment the workflow seems sound, but I just don't know how I can make git work this way.
Thanks, all help much appreciated.
Update 1:
If I was to merge master into mobiledevicesupport and mobiledevice support into master, do I get replicated commits across both branches. Or is git smart enough to work out that I have pulled the latest changes from branch A into branch B and add merge commit C to branch B. And I have pulled the latest changes from branch B into branch A and add merge commit D to branch A?
I was going to post an image but I don't have enough reputation for it, so I guess the following illustration will have to do. Two branches continuously running with merges going both directions often. The key thing I am not sure about is how git will play out the commits and will it fill either branch with the commits from the other branch on merges or will it stay clean. I have used rebase before but it seems to end the branch and put all the commits into the master, or I did it wrong. Thanks for the help so far.
master
A--B--C-----H--I--J--M--N
       \   /    \
mobile  \ /      \
D--E--F--G--------K--L

A: Yeah I agree with your approach. To merge mobiledevicesupport into master you can use
git checkout master
git pull origin master //Get all latest commits of master branch
git merge mobiledevicesupport

Similarly you can also merge master in mobiledevicesupport.
Q. If cross merging is an issue or not.
A. Well it depends upon the commits made in mobile* branch and master branch from the last time they were synced. Take this example:
After last sync, following commits happen to these branches
Master branch: A -> B -> C [where A,B,C are commits]
Mobile branch: D -> E

Now, suppose commit B made some changes to file a.txt and commit D also made some changes to a.txt. Let us have a look at the impact of each operation of merging now,
git checkout master //Switches to master branch
git pull // Get the commits you don't have. May be your fellow workers have made them.
git merge mobiledevicesupport // It will try to add D and E in master branch.

Now, there are two types of merging possible

*

*Fast forward merge

*True merge (Requires manual effort)

Git will first try to make FF merge and if it finds any conflicts are not resolvable by git. It fails the merge and asks you to merge. In this case, a new commit will occur which is responsible for resolving conflicts in a.txt.
So Bottom line is Cross merging is not an issue and ultimately you have to do it and that is what syncing means. Make sure you dirty your hands in merging branches before doing anything in production.

A: Run the following commands:
$ git checkout mobiledevice
$ git pull origin master

This would merge all the latest commits to your branch. If the merge results in some conflicts, you'll need to fix them.
I don't know if this is the best practice but works for me.

A: Yes, just do:
git checkout master
git pull
git checkout mobiledevicesupport
git merge master

to keep mobiledevicesupport in sync with master.
Then, when you're ready to put mobiledevicesupport into master, first, merge in master like above, then:
git checkout master
git merge mobiledevicesupport
git push origin master

and that's it.
The assumption here is that mobilexxx is a topic branch with work that isn't ready to go into your main branch yet. So only merge into master when mobiledevicesupport is in a good place.

A: Whenever you want to get the changes from master into your work branch, do a git rebase <remote>/master. If there are any conflicts. resolve them.
When your work branch is ready, rebase again and then do git push <remote> HEAD:master. This will update the master branch on remote (central repo).

A: concept47's approach is the right way to do it, but I'd advise to merge with the --no-ff option in order to keep your commit history clear.
git checkout develop
git pull --rebase
git checkout NewFeatureBranch
git merge --no-ff master

A: You are thinking in the right direction. Merge master with mobiledevicesupport continuously and merge  mobiledevicesupport with master when mobiledevicesupport is stable. Each developer will have his own branch and can merge to and from either on master or  mobiledevicesupport depending on their role.

A: The accepted answer via git merge will get the job done but leaves a messy commit history, correct way should be 'rebase' via the following steps (assuming you want to keep your feature branch in sync with develop before you do the final push before PR).
1 git fetch from your feature branch (make sure the feature branch you are working on is update to date)
2 git rebase origin/develop
3 if any conflict should arise, resolve them one by one
4 use git rebase --continue once all conflicts have been dealt with
5 git push --force

A: using yourBranch = mobiledevicesupport;

Keeping yourBranch in sync with master consists of two important details:

*

*update the yourBranch version in the cloud according to master

*update the yourBranch version on your PC according to master
How To:
Assuming yourBranch is behind master

*

*create a merge request from master to yourBranch (e.g. via
GitLab web UI)

*accept/solve the merge request from master to yourBranch (e.g.
via GitLab web UI)

*

*now you have changes from master in yourBranch

*this has loaded master changes to yourBranch on remote (in the cloud) but not locally yet

*update the old version of yourBranch which you have locally (on
your PC)

*

*make sure you are now locally interacting with your branch

*git fetch will check for changes

*git status will tell you the status of your local repository (of your local yourBranch) - e.g. 5 commits behind master

*git pull will download the new updated version from the cloud (from "remote") where changes from master are added - now you will be in sync with master also in the local repository (on your machine)


text:
Q: How to read lines from arbitrary BZ2 streams for CSV? The bz2 module provides a standard open() method from which one can call readline(). However, my situation is one where I have a stream (pointing to a large amount of data) that I want to decompress lines from on the fly. My current implementation is as follows but I know there must be a more succinct way to do this.
import bz2
import csv

BZ2_BUFFER = ''

BZ2_DECOMPRESSOR = None

BZ2_FILE = None

BZ2_READ_SIZE = 100 * 1024

def bz2_csv_rows(fp):
    global BZ2_BUFFER, BZ2_DECOMPRESSOR, BZ2_FILE, BZ2_READ_SIZE

    BZ2_BUFFER = ''
    BZ2_DECOMPRESSOR = bz2.BZ2Decompressor()
    BZ2_FILE = fp

    for row in csv.reader(iter(bz2_line_reader, b'')):
        yield row

def bz2_line_reader():
    global BZ2_BUFFER, BZ2_DECOMPRESSOR, BZ2_FILE, BZ2_READ_SIZE

    if BZ2_BUFFER is None:
        return None

    while '\n' not in BZ2_BUFFER:
        bindata = BZ2_FILE.read(BZ2_READ_SIZE)

        try:
            data = BZ2_DECOMPRESSOR.decompress(bindata)
        except EOFError:
            break
        except IOError:
            pass

        BZ2_BUFFER += data

        if len(data) < BZ2_READ_SIZE:
            BZ2_FILE = None
            break

    i = BZ2_BUFFER.find('\n')
    if i is None or i < 0:
        line = BZ2_BUFFER
        BZ2_BUFFER = None
        return line

    line = BZ2_BUFFER[:i]
    BZ2_BUFFER = BZ2_BUFFER[i + 1:]
    return line

Thoughts?

A: Here's something that's a little more succinct, and (in my opinion) it's more readable and gets rid of all those nasty global variables your code uses:
import bz2
import csv
from functools import partial

class BZ2_CSV_LineReader(object):
    def __init__(self, filename, buffer_size=4*1024):
        self.filename = filename
        self.buffer_size = buffer_size

    def readlines(self):
        with open(self.filename, 'rb') as file:
            for row in csv.reader(self._line_reader(file)):
                yield row

    def _line_reader(self, file):
        buffer = ''
        decompressor = bz2.BZ2Decompressor()
        reader = partial(file.read, self.buffer_size)

        for bindata in iter(reader, b''):
            block = decompressor.decompress(bindata).decode('utf-8')
            buffer += block
            if '\n' in buffer:
                lines = buffer.splitlines(True)
                if lines:
                    buffer = '' if lines[-1].endswith('\n') else lines.pop()
                    for line in lines:
                        yield line

if __name__ == '__main__':

    bz2_csv_filename = 'test_csv.bz2'
    for row in BZ2_CSV_LineReader(bz2_csv_filename).readlines():
        print(row)

A: Maybe it'll be useful: I use Python 3 and I have a large csv.bz2 file.
I handle it this way:
import bz2
import csv

def bz2_csv_rows(fp):
    with bz2.open(fp, mode='rt', newline='') as bzfp:
        for row in csv.reader(bzfp):
            yield row

Key feature is to open stream in text mode: mode='rt' in call bz2.open() instead of manual searching "\n" in binary mode. But I'm not sure this will work for not physical files.


text:
Q: Returning elements consecutively in a row I have a function that returns elements consecutively in a row  so for instance, If there are 4 'green' elements consecutively in a row, the Function should return the string: 'Green Wins'
['green', 'blue', 'green', 'green', 'green', 'green', 'blue'] // -->it should return 'Green wins'

otherwise, it should return 'Draw'

const consecutive  = arr => {
  for(let i  = 0; i < arr.length; i++) {
    if(arr[i] === 'green' && arr[i+1] === 'green' && arr[i+2] === 'green' && arr[i+3] === 'green') {
      return 'Green Wins'
    }
    if(arr[i] === 'blue' && arr[i+1] === 'blue' && arr[i+2] === 'blue' && arr[i+3] === 'blue') {
      return 'Blue Wins'
    }
  }
  return 'Draw';
}

let greenWins = consecutive(['green', 'blue', 'green', 'green', 'green', 'green', 'blue']);
console.log(greenWins); // --> 'Green Wins'

This is the code that solves it, but it's kind of repetitive, that's why I'm asking your help if we could solve it with something like reduce method?
 const consecutive  = arr => {
 for(let i  = 0; i < arr.length; i++) {
   if(arr[i] === 'green' && arr[i+1] === 'green' && arr[i+2] === 'green' && arr[i+3] === 'green') {
     return 'Green Wins'
   }
   if(arr[i] === 'blue' && arr[i+1] === 'blue' && arr[i+2] === 'blue' && arr[i+3] === 'blue') {
     return 'Blue Wins'
   }
 }
 return 'Draw!';
}

let greenWins = consecutive(['green', 'blue', 'green', 'green', 'green', 'green', 'blue']);
console.log(greenWins); // --> 'Green Wins'

A: You could take a counter and a value for the last color ach check and exit early if four consecutive same colors/values are in the array.

let array = ['green', 'blue', 'green', 'green', 'green', 'green', 'blue'],
    counter = 0,
    color,
    check = v => {
        if (v === color) return ++counter === 4;
        counter = 1;
        color = v;
    };

if (array.some(check)) console.log(color, 'wins');

A: I would be tempted to separate out the logic of "How many consecutive colours" from the logic of "Winning".

const input = ['green', 'blue', 'green', 'green', 'green', 'green', 'blue'] // -->it should return 'Green wins'

const consecutive = arr => {
  return arr.slice(1).reduce( (acc,x,i) => {
    if( x == arr[i] ) {
      acc[x]++
    }
    else {
      acc[x] = 1
    }
    return acc
  },{[arr[0]]:1})
}

var result = consecutive(input);
if(result.green >= 4) {
  console.log("Green wins")
}else if (result.blue >= 4){
  console.log("Blue wins")
} else{
  console.log("Draw")
}

A: simple use of for loop may solve this,

function checkConsecutivity(srcArray) {

  let count = 1,
    curColor = srcArray[0];
  for (let i = 1; i < srcArray.length; i++) {

    if (curColor == srcArray[i]) {
      count++;
      if (count == 4)
        return curColor + ' wins';
    } else {
      count = 1;
      curColor = srcArray[i]
    }
  }

  return 'Draw';
}

const input = ['green', 'blue', 'green', 'green', 'green', 'green', 'blue'];

console.log(checkConsecutivity(input))


text:
Q: C# Relection addeventhandler : create Delegate fail cannot bind to the target method I have tried to add event from external dll file and i got argumentexception "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type".
I tried to search the solution but they do not work with my code.
This is code in dll file.
public class StartProcess
{
     public StartProcess(){}

     public delegate void MSTStepInformEventHandler(object sender, MSTStepInformEventArg e);
     public event MSTStepInformEventHandler StepInformed;

     protected virtual void OnStepInformed(MSTStepInformEventArg e)
     {
          if (this.StepInformed != null)
          {
               this.StepInformed(this, e);
          }
     }

     public void Start()
     {
          this.OnStepInformed(new MSTStepInformEventArg() { Info = DateTime.Now.toString()});
     }

public class MSTStepInformEventArg : EventArgs
{
    public MSTStepInformEventArg() { }
    public string Info { get; set; }
}

And the below is reflection code.
class Test
{
    void HandleEvent(object sender, MainDLL.MSTStepInformEventArg e)
    {
        Console.WriteLine("HandleEvent called " + e.Info);
    }

    static void Main()
    {
        Assembly ass = Assembly.LoadFrom("StartProcess.dll");

        Type classEx = ass.GetType("StartProcess.StartProcess");

        Test test = new Test();

        object obj = Activator.CreateInstance(classEx);

        MethodInfo method = typeof(Test).GetMethod("HandleEvent", BindingFlags.NonPublic | BindingFlags.Instance);

        EventInfo eventInfo = classEx.GetEvent("StepInformed");

        Type type = eventInfo.EventHandlerType;

        Delegate handler = Delegate.CreateDelegate(type, test, method); // Exception throw is here -----

        eventInfo.AddEventHandler(obj, handler);

        classEx.InvokeMember("Start", BindingFlags.InvokeMethod, null, obj, null);
    }
}

Please help...


text:
Q: node.js refusing connection? I have some node.js code that I am running called app.js When it runs is gives an error saying connection refused?
It is running on plesk so I cannot debug it. I have added the package.json too but maybe I am missing something?
package.json:
{
  "name": "socket-example",
  "version": "0.0.1",
  "description": "test socket.io app",
  "dependencies": {
    "socket.io": "^1.7.3"
  },
  "scripts": {
    "start": "node app.js"
  }
}

app.js:
var http = require('http');
var fs = require('fs');

// Loading the index file . html displayed to the client
var server = http.createServer(function(req, res) {
    fs.readFile('./index.html', 'utf-8', function(error, content) {
        res.writeHead(200, {"Content-Type": "text/html"});
        res.end(content);
    });
});

// Loading socket.io
var io = require('socket.io').listen(server);

// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
    console.log('A client is connected!');
});

server.listen(8080);

index.html:

Communicating with socket.io!

<input type="button" value="Poke the server" id="poke" />

A: Try changing all you code like this as this will resolve your issues
app.js

var express = require('express');

var app = express();

app.set("view engine","html");

var http = require('http');

//making express server for routes
var server = http.Server(app);

// Loading socket.io
var io = require('socket.io')(server);

//index route
//loaded when the website is loaded root route.
app.get('/',function(req,res){
 //specify the path to the directory (assuming both are in the same directory)
 res.sendFile(__dirname + '/index.html');
})

// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
    console.log('A client is connected!');

    //message of client side
    socket.on('little_newbie',function(message){
     //give the username in terminal of the connected client
     console.log(message);
     //send a hello to the client from the server.
     io.sockets.emit('message',"Hello "+message);
    })
    //button poke mesage response
    socket.on('message',function(message){
     //print the hello message from the server
     console.log(message)

     //after this you can send a response back to the client as in the above case
     io.sockets.emit('poke',"Hi I am fine ");
    })

});

server.listen(8080);
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Socket.io</title>

Communicating with socket.io!

<input type="button" value="Poke the server" id="poke" />

{
  "name": "socket-example",
  "version": "0.0.1",
  "description": "test socket.io app",
  "dependencies": {
    "express": "^4.16.4",
    "socket.io": "^1.7.3"
  },
  "scripts": {
    "start": "node app.js"
  }
}

A: There ate no routes configuration , and when you try to ping from browser it won't connect . just like meaning less URI. Try making a route and then calking route from Browser.


text:
Q: how to fix textviews on image on different resolutions on android? I have 3 textviews 100, 300 and 500, I want to fix them on image like below.

my layout code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:layoutDirection="ltr"
    tools:context="com.kortexta.pandaz.MainActivity"
    android:layout_height="match_parent">

<ImageView
    android:src="@drawable/bg"
    android:id="@+id/imageView"
    android:adjustViewBounds="false"
    android:scaleType="fitCenter"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    app:srcCompat="@drawable/kk"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true" />

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="202dp"
    android:id="@+id/textView3" />

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toLeftOf="@+id/textView3"
    android:layout_toStartOf="@+id/textView3"
    android:layout_marginRight="19dp"
    android:layout_marginEnd="19dp"
    android:id="@+id/textView4" />

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/textView4"
    android:layout_toRightOf="@+id/textView3"
    android:layout_toEndOf="@+id/textView3"
    android:layout_marginLeft="16dp"
    android:layout_marginStart="16dp"
    android:id="@+id/textView5" />
</RelativeLayout>

but when I run my app on different devices with different resolutions, I get results like below:

and

how can fix textviews on different resolutions?
please help me.

A: is the TextViewhaving some kind of pentagon background?
If yes then keep your images for each resolution in mipmap.


text:
Q: List mount points in C++ on Linux without using /proc/mounts, /etc/fstab, system() or popen() I am looking for a solution to get the list of all tmpfs mount points available on my Linux system and I need to get it from a C/C++ program.
I need a generic solution that is not distro dependent.
I don't want to access /proc/mounts or /etc/fstab.
I don't want to use a system() or popen().
Is there another way?
Thanks for your help!

A: The way mount implements this is to read /etc/mtab - strace mount is the fastest way to verify this if you don't have the source at hand. But as /etc/mtab is updated by mount/umount, and /proc/mounts is managed by the kernel itself, /proc/mounts is the better idea of the 2, and it's there on every linux system, independent of distro (hmm, maybe my Suse 4.4.2 which dates back to 1996 is an exception).
Or, if you want to be portable to non-linux Unixes, use the getmntent family of functions - but as the manual page states, other unixes have functions with the same name perform differently from the linux implementation, so while your code may compile on non-linux unixes, it won't neccesarily work correctly there.


text:
Q: iterate over a vector thats defined as a typedef C++ I have a struct as follows
struct pins
{
    PType pintypes;
    GType Grouptypes
};

where PType and GType are defined as
typedef std::vector< pInfo > PType;
typedef std::vector<gInfo> GType;

where pInfo and gInfo are classes with sample members as
struct pInfo {
    std::string pinNumber;
    std::string pinName;
};

Now I am comparing two PinInfos from pins variable.I want to see if given two pins, they have exactly the same pintypes.
I am trying as follows.
for (std::vector<pInfo>::const_iterator prim1Pin = pins.pinTypes.begin(); prim1Pin != pins.pinTypes.end(); prim1Pin++)
    {
        if (bRet)
        {
            std::vector<pInfo>::const_iterator prim2pin = std::find(prim2.pinTypes.begin(), prim2.pinTypes.end(), (*prim1Pin).pinNumber);
            if (prim2pin!=prim2.pinTypes.end())
            {
                bRet &= ((*prim2pin).PinNumber== (*prim1Pin).PinNumber&& (*prim2pin).pinName == (*prim1Pin).pinName)
            }
            else
                bRet &= false;
        }
    }

when I compile this I get the following error in algorithm.h file
Error  C2678   binary '==' : no operator found which takes a left-hand operand of type 'pInfo' (or there is no acceptable conversion)  C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\algorithm    41
Not sure whats wrong with this.
I am using some version less than C++ 11.

A: In your call to find, you're iterating over a container that holds a bunch of pinType objects, while you're searching for a string value.  The compiler will need an overload of operator== that takes a pinType on the left and a string on the right.
So you'll want to either provide that operation, or define a lambda or comparison class to handle it.


text:
Q: This application does not exist - GAE This application is live. I previously used this project for php, now I am experimenting with Java and I cannot get the project to upload. Below is the error message I get:

com.google.appengine.tools.admin.HttpIoException: Error posting to
  URL:
  https://appengine.google.com/api/appversion/create?app_id=laraveltest2014&version=1&
  404 Not Found This application does not exist
  (app_id=u'laraveltest2014').

I tried adding the parameter below and it had no effect.
--no_cookies

A: If you logged in with different google account previously, try deleting these two files from home directory:
.appcfg_oauth2_tokens_java
.appcfg_cookies


text:
Q: "Open with" Options through vbscript Manually we right click on a file and select the "open with" option to open in other format.
Now i need to do this through vbscript

A: To open a file using a specific application, use the WshShell.Run methood to run that application and pass the file name as a parameter.
Here's an example that opens the same text file in Notepad, Internet Explorer and Microsoft Word:
strFileName = "c:\myfile.txt"
Set oShell = CreateObject("WScript.Shell")

oShell.Run "notepad "  & strFileName
oShell.Run "iexplore " & strFileName
oShell.Run "winword "  & strFileName

Note that if the file name includes spaces, you need to enslose it in quotes, like this:
oShell.Run "winword ""c:\my file.txt"""

A: If you want to create an association script with VBScript, for example when you write click on a file and open it with certain program, you can use this script I had created way back:
'Run Script
InsertContextMenu

Sub InsertContextMenu ()
Dim sText
Dim sExePath

'For executable-only context menu, the key should be created here
'HKEY_CLASSES_ROOT\exefile\shell

sText = InputBox ("Enter the Text for the context menu." & vbNewLine & vbNewLine & "Example" & vbNewLine & "Open with Notepad")

If Len(Trim(sText)) > 0 Then
    sExePath = InputBox ("Enter the path of the executable file for the context menu." & vbNewLine & vbNewLine & "Example" & vbNewLine & "C:\Windows\Notepad.exe")
    If Len(Trim(sExePath)) > 0 Then
        Set SHL = CreateObject ("WScript.Shell")
        SHL.RegWrite "HKCR\*\Shell\" & sText & "\",sText
        SHL.RegWrite "HKCR\*\Shell\" & sText & "\Command\", sExePath & " %1"

        If Len(SHL.RegRead ("HKCR\*\Shell\" & sText & "\Command\")) > 0 Then
            MsgBox "The Context Menu successfully created !.",vbInformation
        Else
            MsgBox "An unknown error has occured !!",vbCritical
        End If
    End If
End If

Set SHL = Nothing
End Sub

Just copy above code, and paste into a file and give that file .vbs extension.


text:
Q: Behavior of let, eval, and quote I was trying to understand the behavior of let.
Why does case2 throw me an error?
;; case1: worked fine.
(let ((NF 5)) NF)
5

;; case2: got an error
(let ((NF 5)) (eval 'NF))
error: The variable NF is unbound

A: EVAL doesn't have access to lexical variables. The CLHS says:

Evaluates form in the current dynamic environment and the null lexical environment.

If you declare the variable special it will work, since this performs a dynamic binding rather than a lexical binding.
(let ((NF 5))
  (declare (special NF))
  (eval 'NF))
5


text:
Q: nautilus show desktop file as normal file here is my desktop file. nautilus show icon and name i set in desktop file.
▶ cat gitauto.desktop
[Desktop Entry]
Type=Application
Terminal=true
Name=Git Auto Push/Pull
Icon=github-color.svg

but if i add one line, "Exec=xxxxx/git.pl", nautilus show it as normal file, not show "github-color.svg" here.
i use 14.04, and i found only "Exec" line within [Desktop Entry] can occour this, quicklist items not effect. Is this a nautilus bug?
put a screen-shot to introduce different between normal file and desktop file

A: As all executables files a .desktop file needs executable permissions too to be recocgized as a "trusted" starter. Only then Nautilus will also display it's icon.
chmod +x gitauto.desktop

Note that you need an Exec=/path/to/binary_or_script line for a valid .desktop file. Also note that once made executable you will no longer have a right-click context entry to edit a .desktop file.


text:
Q: How to group the power point images programatically I'm trying to extract the images from pdf using pdf miner module.I want to extract the graph image as single image but actually module is not returning the whole graph image instead its returning the separated images.I have converted the pdf to ppt.Then manually grouped the graphic image as single image then again converted to pdf. Now pdf miner is extracting the graph image as single image.
Manually we can group the power point images.Is there any way to do that programmatically

A: In order to do this, you need to be able to supply some condition that will identify your shapes uniquely; they might be the only picture shapes on a slide, the only shapes on an otherwise blank slide, or any shapes added after you've first gotten a count of the number of shapes on the slide.  Once you have a condition you can apply this can build an array of the shapes that meet the condition then group them:
Sub GroupCertainShapes()

    Dim x As Long
    Dim sTemp As String
    Dim aShapeList() As String
    Dim lShapeCount As Long

    With ActivePresentation.Slides(1)
        ' iterate through all shapes on the slide
        ' to get a count of shapes that meet our condition
        For x = 1 To .Shapes.Count
            ' Does the shape meet our condition? count it.
            If .Shapes(x).Type = msoAutoShape Then
                lShapeCount = lShapeCount + 1
            End If
        Next

        ' now we know how many elements to include in our array,
        ' so redim it:
        ReDim aShapeList(1 To lShapeCount)

        ' Reset the shape counter
        lShapeCount = 0

        ' Now add the shapes that meet our condition
        ' to the array:
        For x = 1 To .Shapes.Count
            ' apply some criterion for including the shape or not
            If .Shapes(x).Type = msoAutoShape Then
                lShapeCount = lShapeCount + 1
                aShapeList(lShapeCount) = .Shapes(x).Name
            End If
        Next

        ' and finally form a group from the shapes in the array:
        If UBound(aShapeList) > 0 Then
            .Shapes.Range(aShapeList).Group
        End If

    End With
End Sub


text:
Q: Utf-8 en raw_input() No me funciona el utf-8 cuando coloco un raw_input, por ejemplo en
raw_input('Ingrese un número')

me lo muestra mal, y también si coloco
raw_input(u'Ingrese un número')

me muestra error, como se debe colocar? aquí dejo codigo de referencia
# -*- coding: utf-8 -*-

def binary_search(numbers, number_to_find, low, high):

    if low > high:
        return False

    mid = (low + high) / 2

    if numbers[mid] == number_to_find:
        return True
    elif numbers[mid] > number_to_find:
        return binary_search(numbers, number_to_find, low, mid - 1)
    else:
        return binary_search(numbers, number_to_find, mid + 1, high)

if __name__ == '__main__':
    numbers = [1, 2, 3, 4, 5, 6, 9, 10, 11, 25, 27, 28, 34, 36, 49, 51]
    number_to_find = int(raw_input('Ingresa un número: '))

    result = binary_search(numbers, number_to_find, 0, len(numbers) - 1)

    if result is True:
        print(u'Sí se encontró el número en la lista.')
    else:
        print(u'No se encontró el número en la lista.')

    raw_input()

A: El problema está en que la terminal de turno (posiblemente CMD-Windows) no usa UTF-8 como página de códigos. Una posible solución es codificar la cadena de acuerdo a la codificación usada por la terminal:
# -*- coding: utf-8 -*-

import sys

n = raw_input("Ingrese un número".decode("UTF-8")
                                 .encode(sys.stdin.encoding))

Claro está que la página de códigos de la consola y la fuente de la misma deben soportar el carácter ó, por ejemplo CP 850 (Latin-1) junto a Lucida Console.

A: ¿Cómo funciona esto de los encodings en python2?
Típicamente hay que comenzar el fuente con una línea como: # -*- coding: utf-8 -*-
En python2 esa línea simplemente le dice al intérprete python que codificación usó tu editor de texto a la hora de guardar el archivo. Eso lo necesita saber para decodificar correctamente las secuencias de bytes que se encontrará entre comillas en el fuente.
Cuando Python encuentre en el código fuente algo "Entre comillas", lo que en realidad está viendo el intérprete es una secuencia de bytes. En general guardará esa secuencia de bytes sin tratar de entender qué caracteres representa (porque de hecho podría no representar carácter alguno, la secuencia de bytes podría ser puramente binaria, como en "\x05\x12\x07" por ejemplo).
Si intentas imprimir una secuencia de bytes así, el intérprete se limitará a enviarlos sin más a la terminal, y es la terminal la que tratará de decodificarlos (usando el encoding de la terminal), para mostrar caracteres.
Si la terminal no usa el mismo encoding que la secuencia de bytes (por ejemplo, si la terminal usa CP-850, mientras que el fichero fue guardado como UTF-8), los caracteres no-ascii no se mostrarán correctamente (los acentos, eñes, etc.) Los caracteres ASCII sí se mostrarán bien porque todos los encodings coinciden en cómo codificar esa parte del alfabeto.
Esto puedes notarlo al ejecutar un código como el siguiente:
# coding: utf-8
print "Eñe"

Si el fichero efectivamente fue guardado como UTF-8, entonces lo que va dentro de las comillas será la secuencia de bytes: 45, C3, B1, 65 (donde 45 es el código UTF-8 de la E, C3 y B1 en secuencia codifican la ñ y finalmente 65 es el código de la e).
Si ejecutas ese programa en una terminal que use UTF8, la terminal simplemente recibirá esa secuencia (45, C3, B1, 65) y la decodificará como UTF-8, mostrando Eñe.
Ahora bien, si lo ejecutas en una terminal que use CP-850 (por ejemplo, una terminal Windows), la terminal mostraría E├▒e, pues en ese encoding los bytes 45 y 65 siguen representando E y e (por ser parte del ASCII), pero los bytes C3 y B1 representan dos caracteres separados (├y ▒, respectivamente, como puedes ver en la tabla de códigos CP-850).
Cadenas unicode
Para evitar este comportamiento errático, en el que lo que muestra depende del encoding usado por la terminal, es mejor usar "cadenas unicode", que se diferencian de las normales en que comienzan por u (delante de las comillas). El programa anterior quedaría ahora así:
# coding: utf-8
print u"Eñe"

La diferencia con lo anterior es que ahora Python no trata lo que hay entre comillas como una secuencia de bytes sin significado alguno, sino que sabe que se trata de una cadena de caracteres, por lo que convierte del encoding usado por el editor (le tenemos que decir cuál es a través del comentario de la primera línea) a una codificación interna de Python que no depende de la terminal ni del editor ni del operativo. En esta codificación, cada letra de tu cadena se convierte en una letra para python (y no como antes, en que aparecían casos como la ñ que, aún siendo una letra aparentemente, eran dos bytes en la representación interna).
Una consecuencia inmediata de esto es que si hacemos len() para averiguar la longitud de la cadena, en el primer caso nos hubiera dado 4 (el número de bytes), pero ahora nos dará 3 (el número de caracteres). Esto hace que todas las funciones de manipulación de cadenas se comporten "mejor" (por ejemplo, pasar a mayúsculas, minúsculas, etc. funcionarán correctamente).
Otra ventaja es que a la hora de hacer el print, python intentará averiguar el encoding de la terminal y convertirá su representación interna a la secuencia de bytes apropiada para esa terminal, de modo que el usuario vea Eñe, lo mismo que escribió el programador.
El inconveniente es que si python no es capaz a determina el encoding de la terminal, asumirá ASCII por defecto, y entonces fallará en cuanto se encuentre una letra que no pueda ser representada como ASCII.
Una vez sabemos todo esto:
¿Por qué no funciona raw_input("Número: ")?
En realidad funciona a medias, pues al ser una cadena "normal", python no entra a decodificarla. Simplemente la trata como una secuencia de bytes y eso será lo que envíe a la terminal. Siempre que la terminal use la misma codificación que el programa, se verá correctamente. Si no usa la misma codificación se verán mal todas las letras no-ascii (que aparentemente es lo que te sucede a tí)
¿Por qué no funciona raw_input(u"Número: ")?
De acuerdo con lo antes explicado, esto sí debería funcionar. Pero no lo hace debido a un bug. La función raw_input() no usa el encoding de sys.stdout (la salida estándar), como hace la función print. En lugar de ello asume codificación ASCII y falla cuando encuentra un caracter no ascii.
¿Solución?
Ya que el bug impide hacerlo "bien", las soluciones son un poco insatisfactorias:

*

*Usa un editor que utilice el mismo encoding que la terminal en que lo vas a ejecutar (y declara esa codificación en el primer comentario del programa)

*Cambia la codificación de la terminal para que use UTF-8.

*Recodifica la cadena antes de imprimirla, como en la respuesta de FJSevilla.

O lo mejor de todo: cámbiate a Python3. En python3 todo el soporte unicode es mucho mejor, el bug antes mencionado está corregido, y el encoding por defecto para el fuente es utf8, con lo que no tienes ni que declararlo en la primera línea. El inconveniente es que tendrás que cambiar más cosas en tu programa para que sea compatible con python3 (las más inmediatas: print() requiere paréntesis alrededor del argumento; raw_input() se llama ahora input() y el antiguo input() ha desaparecido; todas las cadenas son ahora por defecto unicode en lugar de "binarias", y cuando hagas entrada/salida a disco o por sockets debes manejar explícitamente su conversión a bytes).
De todas formas, python3 es el futuro. Python2 dejará de recibir soporte definitivamente en 2020. ¡Vete preparándote!


text:
Q: How do I show an animation while creating user control In a WPF 4 app, I have a very big user control full of controls which takes something like 4s to initialize on a fast machine. During this time the application is of course not responsive at all.
Is there a way to show an animation in the main window while this control is initialized?
I understand that I cannot create it on another thread. But is there maybe a way to create it with a lower priority from the Dispatcher so that I could show a spinning wheel or so on the main window which would still spin?
(The only solution I can think of right now would be to break the user control into further pieces and load them only when needed. But this will take a lot of development time to change.)
Update1
To be more clear: It is a simple WPF window using tab pages. When a new tab page is opened I'm initializing the user control which holds the controls for this tab page. One of these user controls is so full of controls that it takes 4s until the new tab page will be shown.
So I thought showing a spinning wheel would be better than having a blocked application.

A: I think you are going to have to break this user control up into pieces. What you can do is use a BackgroundWorker to coordinate the 'building' of this user control. Each time the DoWork event is fired, use Dispatcher.BeginInvoke to create an add the next control to your UI. This technique is described in the following blog post:
http://loekvandenouweland.com/index.php/2010/12/wp7-add-user-controls-graphics-in-background-thread/
This will allow you to show an animation during loading.

A: Why can't you initialize it on another thread?  I see two scenarios:

*

*Initialization is slow for non-WPF reasons that be preloaded/precomputed on another thread before entering the core WPF initialization.

*WPF itself is consuming 4 seconds of CPU time (though, that's really WTF levels of CPU time...).  If so, you can start another STA thread with it's own message pump that can display an independant UI (e.g: a spinning wheel) until the primary thread is done loading.

You can create "dialogs" which implicitly create a new Dispatcher and run on a background thread, or you can explicitly create your own Dispatcher (=message pump).
I use the following method to do so:
public static Dispatcher StartNewDispatcher(ThreadPriority cpuPriority = ThreadPriority.Normal) {
    using (var sem = new SemaphoreSlim(0)) {
        Dispatcher retval = null;
        var winThread = new Thread(() => {
            retval = Dispatcher.CurrentDispatcher;
            sem.Release();
            Dispatcher.Run();
        }) { IsBackground = true, Priority = cpuPriority };
        winThread.SetApartmentState(ApartmentState.STA);
        winThread.Start();
        sem.Wait();
        return retval;
    }
}

This gives you real multi-threaded UI; but it also means you can't databind or in any other way directly communicate between the two UI's: after all, WPF objects have thread-affinity.
Before you go this route, verify there aren't any slow components you can preload using a profiler: option 1 (preload heavy stuff before WPF init) is simpler and cleaner.

A: A solution could be to move the slow part (loading data? that doesn't belong IN the control) to another thread as you mentioned.
Or use a VirtualizingStackPanel to lazy load what is needed.
Could you elaborate on the reason for the delay?


text:
Q: Angular material button-toggle-group I have a button toggle group. The functionality is that when I click a particular item, the background color should be changed. When I toggle one of the buttons, the newly selected button's color should change and the old one should return back to the default background color. Here is my code:
HTML
<mat-button-toggle-group name="fontStyle" aria-label="Font Style" vertical >
  <mat-button-toggle value="bold" (click)="changeColor()" mat-button-toggle [style.background-color]="color">Bold</mat-button-toggle>
  <mat-button-toggle value="italic" (click)="changeColor()" mat-button-toggle [style.background-color]="color">Italic</mat-button-toggle>
  <mat-button-toggle value="underline"(click)="changeColor()" mat-button-toggle [style.background-color]="color">Underline</mat-button-toggle>
</mat-button-toggle-group>

TypeScript
export class ButtonToggleOverviewExample {
  color:string;

  changeColor(){
    this.color='green';
  }

}

The problem is that once a button is toggled it remains in the same color as clicked one.

A: Try something like this:
DEMO
in style.css
.mat-button-toggle-checked{
  background-color: green;
}


text:
Q: React Native android App refused to run on Emulator I did all the steps to create a react native application , but when it came to running the App it shows me this Error below in the image , what could be the problem.

A: You have to make sure your emulator is run (i recommended using genymotion), and also ensure you have been to configure your system with android environment. You can follow step by step in the documentation.


text:
Q: Cannot cast 'Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1[Microsoft.AspNetCore.Identity.IdentityUser`1[System.Int32]]' PROBLEM:
System.InvalidCastException: 'Unable to cast object of type 'Microsoft.EntityFrameworkCore.Internal.InternalDbSet1[Microsoft.AspNetCore.Identity.IdentityUser1[System.Int32]]' to type 'System.Linq.IQueryable`1[DAL.User]'.'
RELEVANT CODE:
...
public class SocialNetworkDbContext : IdentityDbContext<IdentityUser<int>, IdentityRole<int>, int>
...
public IQueryable<User> FindAll()
        {
            var allUsers = (IQueryable<User>)_socialNetworkDbContext.Users;
            if (allUsers == null)
            {
                throw new NoRecordFoundException();
            }
            return allUsers;

TRIED:

*

*public class SocialNetworkDbContext : IdentityDbContext<User>, IdentityRole<int>, int>
//no exception but this code breaks
            var result = await _userManager.CreateAsync(user, model.Password);
            await _userManager.AddToRoleAsync(user, model.Role);

*public IQueryable FindAll()
{
var allUsers = (IQueryable)_socialNetworkDbContext.Users.AsQueryable();
if (allUsers == null)
{
throw new NoRecordFoundException();
}
return allUsers;

//the same exception
3)
public IQueryable<User> FindAll()
        {
            var allUsers = (IQueryable<User>)(IEnumerable<User>)_socialNetworkDbContext.Users;
            if (allUsers == null)
            {
                throw new NoRecordFoundException();
            }
            return allUsers;

// the same exception (unable to cast to IEnumerable). Cast to ICollection (unable to cast to ICollection)
Would be very thankful for any advice!!!

A: You should change your DbContext to use the actual user type:
public class SocialNetworkDbContext : IdentityDbContext<User, IdentityRole<int>, int>
{
}

If you have a class for the roles, you should use that as the generic type argument as well.
This way you won't need any type casts.

A: From your code, it seems that the _socialNetworkDbContext.Users was stored the IdentityUser, instead of User model, right? So, after query data from the Users table, you could use the following code to convert the query result:
    public IQueryable<User> FindAll()
    {
        var allUsers = _socialNetworkDbContext.Users.Select(c => new User()
        {
            UserName = c.UserName,
            Email = c.Email,
            //... other properties
        }).AsQueryable();
        if (allUsers == null)
        {
            throw new NoRecordFoundException();
        }
        return allUsers;
    }

Update
You can refer the following sample code:
Add an ApplicationUser class to customize the Identity User model:
public class ApplicationUser : IdentityUser<int>
{
    public string CustomTag { get; set; }
}

Use the ApplicationUser type as a generic argument for the context:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int>
{
    public DbSet<ApplicationUser> ApplicationUsers { get; set; }
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

Update Pages/Shared/_LoginPartial.cshtml and replace IdentityUser with ApplicationUser:
@using Microsoft.AspNetCore.Identity
@using WebApp1.Areas.Identity.Data
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

Update the Startup.ConfigureServices and replace IdentityUser with ApplicationUser:
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDatabaseDeveloperPageExceptionFilter();

    services.AddIdentity<ApplicationUser, IdentityRole<int>>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders();

    services.AddControllersWithViews();
}

Then, enable migration and generate the database.
After creating new user, the AspNetUser table data as below:

Create a UserViewModel and add the required properties:
public class UserViewModel
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Tag { get; set; }
}

Then, in the Controller, use the following code to query the user table:
public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly ApplicationDbContext _context;
    public HomeController(ILogger<HomeController> logger, ApplicationDbContext context)
    {
        _logger = logger;
        _context = context;
    }

    public IActionResult Index()
    {
        var result = FindAll();
        return View();
    }
    public IQueryable<UserViewModel> FindAll()
    {
        var allUsers = _context.Users.Select(c => new UserViewModel()
        {
            UserId = c.Id,
            UserName = c.UserName,
            Tag = c.CustomTag
        });
        //if (allUsers == null)
        //{
        //    throw new NoRecordFoundException();
        //}
        return allUsers;
    }

The result as below:

A:
try First(); or FirstOrDefault();

A: change your code :
    public async Task<List<User>> GetAllUsers()
        {
            var allUsers =  await _socialNetworkDbContext.Users.ToListAsync();
            if (allUsers == null)
            {
                throw new NoRecordFoundException();
            }
            return allUsers;
         }


text:
Q: How to replace node in sharded replica set? I got sharded mongodb setup with two replica sets:
mongos> db.runCommand( { listShards : 1 } )
{
    "shards" : [
        {
            "_id" : "rs01",
            "host" : "rs01/10.133.250.140:27017,10.133.250.154:27017"
        },
        {
            "_id" : "rs02",
            "host" : "rs02/10.133.242.7:27017,10.133.242.8:27017"
        }
    ],
    "ok" : 1
}

Node 10.133.250.140 just went down, and I replaced it with another one (ip-address changed). Replica set reconfiguration was pretty easy, just rs.remove() and rs.add()
Now I have to update host config for shard rs01. What is proper way to do it?

A: Many times you would need to modify the host string for a shard. The simplest way to change host string is to run an update operation.
Connect to mongos and do this -
> use config
> db.shards.update({ "_id" : "rs01"},{$set : { "host" : "rs01/newip:27017,anothernewip:27017"} })

You might need to restart all mongos.
Hope this helps :-)

A: Well, removing problem shard and adding it again seems the only option.


text:
Q: Virtual Blackboard for Online Meetings I would like to integrate a "virtual blackboard" functionality with my e-learning website. I would like users to be able to participate in "meetings", with the following functionality:

*

*chat (optionaly voice chat/videochat)

*virtual blackboard (collaborative drawing)

*screensharing (so one of the users can present material like pictures to other users)

*ideally Flash or Java applet based (so users wouldn't have to install any additional software - but this is not a requirement, as long as setup wouldn't be too cumbersome)

I guess there are no free solutions, so I'm looking for a paid one. It would be best if users didn't have to set up separate accounts to participate in meetings. Perhaps they could just click on a link with the meeting id.
I googled a little and looked at Adobe Connect Pro. Are there any alternatives that you can recommend?

A: Checkout BigBlueButton http://www.bigbluebutton.org/

BigBlueButton is an active open source
  project that focuses on usability,
  modularity, and clean design -- both
  for the user and the developer. The
  project is hosted at Google Code
  http://code.google.com/p/bigbluebutton/

A: It's not hard to create one with only JavaScript. Then the user really doesn't have to install anything, unlike with Flash or Java.
A pretty good tutorial is here, and additionally Ajax: The Definitive Guide has a good tutorial around Ch. 20 ish.

A: Influxis also has some Flash based meeting software apps and gives you the source code, so that you may extend them, if you are interested in that.
http://influxis.com/applications/


text:
Q: Xampp apache not starting showing dll file missing When i try to run apache on xampp it shows the following error .

I updated my windows 8.1 and I tried to install c++ redistributable 2015 it also shows error "Microsoft Visual C++ 2015 Redistributable Setup Fails [0x80240017] ".
How can i fix that error ?

A: copy one from the php folder to your apache bin folder. that will solve the problem

A: I uninstall the "Microsoft Visual C++ 2015 Redistributable" and update the windows. Then setup the Microsoft Visual C++ 2015 Redistributable again.Its work !
  Update for Windows (KB2999226) I think this is the important update about to fix the problem.

A: Try this
Go to services and stop World Wide Web Publishing Services.
And reinstall Xampp.

A: xampp 1.8 3 download for windows . this version is properly work not any problem. link are provided
https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/1.8.3/
i am 100% sure


text:
Q: Spock + Spring - Stubs returned from Stubbed @SpringBean always return null I am attempting to use Spock to create an integration test around a Spring application. As it is not a Spring Boot application and the @SpringBootTest annotation interfered significantly with the app's initialization, I am using a minimal configuration.
I specifically need to stub a service in my app that returns objects of type Message; in the actual app these objects would come from a third-party vendor's library and they cannot be instantiated or subclassed, nor do their members have setters, so my only option is to create Stubs for them. However, with this current configuration (I've simplified the test significantly just to get the gist across):
@ContextConfiguration([TestSetup]) // supplies actual Spring beans including some JPA repos
class LogicSpec extends Specification {
  @SpringBean
  RestService restService = Stub()
  @Autowired
  ServiceUnderTest sut
  @Autowired
  SomeJPARepo repository;

  def 'should do some business logic'() {
    given:
      Message m = new Stub() {
        getStatus() >> "stubbed status"
      }
      restService.getMessage(_ as String) >> {
        m
      }
    when:
      sut.businessMethod()
    then:
      // just checking for side effects that `businessMethod` causes, no mocks being matched against
      assert repository.findAll().every { it.processed == true }
    }
  }
}

Internally, the ServiceUnderTest.businessMethod() is using the Message object like this:
restService.getMessage(sid).getStatus() // should be "stubbed status"; always evaluates to null

however, every method of the Message stub always returns null regardless of whether I have defined a behavior for it. The Message objects must return specific values from its getters for the test to work. I would prefer to not have to declare every Message stub as its own @SpringBean; I need to eventually expand the test to use several different Message stub objects. I don't need mocks or spies because the number of invocations of RestService's methods doesn't matter, I just need it to emit proper stubs for ServiceUnderTest to chew on. Apologies if this question is unusual or I've missed something obvious; I'm slightly oblivious to Spock's notion of lifecycle, and the waters have been especially muddied with the addition of the Spring extension.

A: I discovered the answer soon after writing this, but just for posterity; the third-party Message class is declared as final and thus can't be subclassed; Spock was creating stubs for them but silently failing to add the overridden mock methods. I ended up using PowerMockito to remove this limitation; however this interfered with collecting test coverage metrics, so I instead used a wrapper class that can be mocked and used it everywhere in my code the original Message class was:
public class MessageWrapper {
  public MessageWrapper(Message from) {...}
}

it's an extra bit of headache, but it was necessary because test coverage was required in this case. There also seems to be a promising Spock-specific mocking utility that will mock final classes, but I haven't tested it nor do I know if it will interfere with collecting coverage metrics like PowerMockito does.


text:
Q: How can i add $5 extra fee on choosing of UPS shipping if order is greater then $200 using shipping rules in Magento2? I want to add shipping rule for ups shipping to add extra $5 if order total is greater then $200.
I want to use shipping Rules only as i will set many rules for different conditions.


text:
Q: Running tasks sequentially: how to deal with exceptions? Following a suggestion from svick I created a little class whose purpose is to run Tasks sequentially, that is, it schedules them on the ThreadPool but it ensures they execute one after the other, in the order they were submitted. It looks like this:
class SequentialTaskRunner<TResult> where TResult : new() {

    public Task<TResult> Run(Func<TResult> func) {
        var result = RunInternal(func, m_previous);
        m_previous = result;
        return result;
    }

    async Task<TResult> RunInternal(Func<TResult> func, Task<TResult> previous) {
        await previous;
        return await Task.Run(func);
    }

    Task<TResult> m_previous = Task.FromResult(new TResult());
}

Now, the problem I have is that if func() throws an exception, then every subsequent invocation of Run() will also return that exception, and it's impossible to run new tasks. I've tried to change RunInternal like so:
async Task<TResult> RunInternal(Func<TResult> func, Task<TResult> previous) {
    if (previous.Exception == null) {
        await previous;
    }
    return await Task.Run(func);
}

But this does not work reliably; if tasks are submitted quickly, the failure of one can still cause several to return the same exception. I am confused as to why and would like an explanation. I'm just getting started with async/await btw.

A: The reason why your code doesn't work is because you're pretty much asking it to predict the future.
When a Task isn't completed yet, its Exception will always be null. This means that it's quite likely that your await previous will throw.
The simplest solution here is to use a general catch:
async Task<TResult> RunInternal(Func<TResult> func, Task<TResult> previous)
{
    try
    {
        await previous;
    }
    catch {}

    return await Task.Run(func);
}

If you want to hide that empty catch (because that's usually a bad practice), or if you do this often and want to avoid repetition, you can write a helper method for this:
public static async Task IgnoreException(this Task task)
{
    try
    {
        await task;
    }
    catch {}
}

Usage:
async Task<TResult> RunInternal(Func<TResult> func, Task<TResult> previous)
{
    await previous.IgnoreException();
    return await Task.Run(func);
}

A: Maybe you can implement some kind of Queue.
This way if one task fail, only that task will return the exception, and the next tasks in the queue will be done. And you will be able to handle the exception, I don´t know, maybe Enqueuing the Task again ;)
But this is only an idea! I hope this helps!


text:
Q: Controller recieving empty data from Ajax I'm trying to send a collection from a view to a controller, using ajax. First I complete the data in a javascript array, and then I try to pass it to the server:
    var funciones = $("#funcionesUsuario").data("kendoGrid").dataSource.data();
    var func = [];

    for (var i = 0; i < funciones.length; i++) {
        func.push({
            "Estado": 1,
            "FechaAlta": null,
            "UsuarioAlta": null,
            "FechaModificacion": null,
            "UsuarioModificacion": null,
            "BitConcilia": funciones[i].BitConcilia,
            "BitLectura": funciones[i].BitLectura,
            "BitSupervisa": funciones[i].BitSupervisa,
            "ConciliacionId": funciones[i].ConciliacionId,
            "UsuarioId": funciones[i].UsuarioId
        })
    }

    $.post(url, { funcionesUsuario: func })
        .done(function (data) {
        alert("good job");
    });

Then, since I'm sending data for 2 objects, my parameter is a IEnumerable of said object:
public void ActualizarFuncionesUsuario(IEnumerable<FuncionUsuario> funcionesUsuario)
    {
        //do something
    }

My problem is that the controller receives 2 objects, as I can see in the funcionesUsuario.count, but they are both empty.
I tried sending int, bool and other types of variables with success, so I suspect I'm doing something wrong regarding data binding.
Below I attached pictures of what I'm sending and what I'm receiving in the other side.

This is the FuncionUsuario model: `
public class FuncionUsuario : AuditableEntity {
    public int ConciliacionId { get; set; }
    public int UsuarioId { get; set; }
    public bool BitLectura { get; set; }
    public bool BitConcilia { get; set; }
    public bool BitSupervisa { get; set; }
    public virtual Conciliacion Conciliacion { get; set; }
    [Display(ResourceType = typeof(Global), Name = "Descripcion")]
    [NotMapped]
    public string Descripcion { get; set; }
}

A: Try these:
Specify json as the dataType
$.post(url, { funcionesUsuario: func })
  .done(function (data) {
    alert("good job");
}, 'json');

Use $.ajax instead: docs
$.ajax({
  url: url,
  data: JSON.stringify(func),
  contentType: "application/json",
  type: "POST"
});

A: first construct you array as java script objects
var funciones = $("#funcionesUsuario").data("kendoGrid").dataSource.data();
var func = [];

for (var i = 0; i < funciones.length; i++) {
    func.push({
        Estado: 1,
        FechaAlta: null,
        UsuarioAlta: null,
        FechaModificacion: null,
        UsuarioModificacion: null,
        BitConcilia: funciones[i].BitConcilia,
        BitLectura: funciones[i].BitLectura,
        BitSupervisa: funciones[i].BitSupervisa,
        ConciliacionId: funciones[i].ConciliacionId,
        UsuarioId: funciones[i].UsuarioId
    })
}

Next, properly stringify them
var payload = JSON.stringify(func);

Then post it as JSON
$.ajax({
  url: url,
  type: "POST",
  contentType: "application/json",
  dataType: 'json'
  data: payload,
});


text:
Q: How can I keep a single component highlighted at a time in Elm 0.17? I have a game UI with a variety of components, some of which can be clicked on to become highlighted (the 'active' component). That is currently done by having a Bool in the state of each component that can be highlighted. However, I'd like to enforce that only one component can be highlighted at once - so, if something is clicked on, whatever else is currently highlighted has to update to un-highlight.
One way to do this is to have the common ancestor broadcast some message down to all of the various children, and every component can handle this message and turn itself off - however this seems pretty complicated and wasteful. There could be 1000 components, and only two are changing (one to highlight and one to un-highlight), so why should I send out and handle 1000 messages?
Is there a better way?
note: this seems pretty similar to Elm 0.17: How to subscribe to sibling/nested component changes. I think that one difference is that in that question there's a small number of related components, and when one changes the other always changes. In my case there are many many components at various locations in the overall model, and when one changes few or none of the others will change.

A: Yes, there probably is a better way. Duplicating some state in multiple places of an app is not recommended because it leads to synchronization problems and makes debugging harder.
Instead you would be better off not storing the highlighted state in the components but only in the main model. Then the components' view function would take an additional boolean "highlighted" parameter.
To store the highlighted state in the main model, you could give an ID to each component and add highlighted : Maybe ID to the model.
Thus, you will only have to propagate the click message from children to parent but not from parent to children.

A: The Elm runtime and the virtual DOM engine will ensure that only the components that changed will be re-rendered. So I wouldn't worry too much about sending messages to 1,000 components.
In your case:

*

*your update function would change only 2 components to set/ unset the active state/ only send out messages to 2 components.

*your view function would always run for all 1000 component's

*Elm's virtual DOM diff engine will only render the 2 components that changed to the DOM.

When working with components with internal state, what you would need is:

*

*each component needs to know whether it is active or not. Probably a Bool.
Could be a field in the component's model.

*the global model needs to know which of the components is active. Possibly with a Maybe Int, where Int is the ID of the active component.

*when a component is clicked to make itself active, it will send some Msg to the parent which should include its ID, so parent knows which component is now active. (see an example here of how this could work)

*the parent's update function updates the active element in its own model whenever it gets a message element. And parent updates 1 or 2 child components to change the active flag of those components.


text:
Q: how to append anchor tag into parent of div? My html code is:

Tesing

I want it to look like:

Tesing

How to do it using JavaScript?

A: Rather than putting the link outside of the div, I would recommend putting it nested inside.
Otherwise this would be invalid HTML.
Therefore your result would be:

Tesing

This can be done by doing:
$(function(){
    $(".xyz").html("" + $(".xyz").html() + "");
});

You can then style the anchor tag so that the whole div is selectable:
.xyz a
{
   display:block;
}

A: As previously said by Curt, your example is not valid. You should have div with text and surround text with 'a' tag.
You can use jQuery method .wrapInner() (jQuery doc)
You can do it with a simple line :
$('.xyz').wrapInner($(''));

jsFiddle is you want to try it :

http://jsfiddle.net/8vbXw/


text:
Q: PIC24F32KA302 RTC configuration I want to configure RTC of PIC24F32KA302 so that LED toggles every second. Howerver, it does not work. Please, find attach below RTC code which I write to initialize internal RTC.
IDE: MPLAB X IDE
Programmer: PICKit 3
Compiler: XC16
RCFGCALbits.RTCWREN = 1;
RCFGCALbits.RTCEN = 0;
while(RCFGCALbits.RTCSYNC==1);      //wait for RTCSYNC bit to become 0
ALCFGRPTbits.ALRMEN = 0;    //disable the alarm
RTCPWCbits.RTCCLK = 0;//00= External Secondary Oscillator (SOSC)
ALCFGRPTbits.AMASK = 1; //Alarm Every 1 second
ALCFGRPTbits.ARPT = 0;          //Alarm will not repeat
ALCFGRPTbits.CHIME = 0;         //Alarm CHIME Enable
ALCFGRPTbits.ALRMEN = 1 ;       //Alarm Enabled

//RTCC CONFIGURATION
RCFGCALbits.RTCOE = 0;          //RTCC output disabled
RCFGCALbits.CAL=0;              //RTC Drift Calibration
RCFGCALbits.RTCEN = 1;          //RTCC Enabled
RCFGCALbits.RTCWREN = 0;        //Disabled RTCC value write

//TODO: Investigate what this does
//PADCFG1bits.RTSECSEL = 0b11;    //RTCC Seconds Clock is not selected for the RTCC pin

//Interrupt configuration
IFS3bits.RTCIF = 0;             //Clear RTCC Alarm interrupt flag
IEC3bits.RTCIE = 1;             //RTCC Alarm interrupt Enabled

void __attribute__ ( (interrupt, no_auto_psv) )  _RTCCInterrupt(void) {
LED = ~LED;
IFS3bits.RTCIF = 0;}

Is there any problem with my code?
Thank you!


text:
Q: Trying to visualize Time Complexity by plotting graph, unexpected output I have defined a simple funcion that computes sum of elements of a list. It is of linear complexity. I tried as below to visualize the graph(X axis for n=no of elements in the list, Y axis for time taken to compute sum of elements in the list with n elements):
import matplotlib.pyplot as plt
code_to_test='''

def find_sum(input_list):
    total =0
    for i in input_list:
        total +=i
    return total

'''

X=[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

Y=[]

for n in X:
    input_list=list(range(n))
    elapsed_time=timeit.timeit(code_to_test, number=1000)/1000
    Y.append(elapsed_time)

print(len(Y))

plt.plot(X,Y)

The graphical output is not linear. Also, the output is varying every time I rerun.
I am using Macbook Pro and have many chrome windows with many tabs open with youtube links but all are paused.  Is this impacting the graph or I am missing something in plotting?


text:
Q: Class/id/elements shortcut in non-HTML files In HTML files, if I write for example:
span.my-first-span

and press enter, VS Code will automatically create a span with a class of my-first-span, like this:

how can I make it do the same on other files, such as .js, .jsx, etc?
I tried searching for it online, but I didn't find anything (I don't know if my search was the best, I don't really know how I should explain what I want...)

A: Add the following fields to your settings.json file in Visual Studio Code:
"emmet.syntaxProfiles": {
    "javascript": "jsx"
},
"emmet.triggerExpansionOnTab": true,
"emmet.includeLanguages": {
    "javascript": "javascriptreact"
}

The Emmet plugin must be installed for it to work.


text:
Q: On device back button the previous fragment web service call is called again We have the following implementation:
We have a fragment e.g.: InboxFragment which has a list view of all messages.
In InboxFrgament, on load we call a web service to retrieve the latest messages from the cloud using a web service call:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_inbox, container, false);
    context = getActivity();

    //Get Messages From Cloud - web service call
    if (ON_BACK_PRESSED == 0) {
        GetMessagesFromCloud();
    }
}

When you tap on a message, we add a new fragment MessageDetailsFragment to the stack. We use the following function to add a new fragment:
public void AddFragmentToStack(Fragment newFragment, String tag) {
    FragmentTransaction ft = this.getSupportFragmentManager()
            .beginTransaction();
    ft.replace(R.id.content_frame, newFragment, tag);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    ft.addToBackStack(null);
    ft.commit();
}

Now this works properly. But when we hit the device back button (while we are on the MessageDetailsFragment), it takes us back to InboxFragment and the onCreateView function gets called again because of which the web service call to fetch new messages is made to server.
We don't want this web service call to happen each time when we hit back on the MessageDetailsFragment. We have a pull down to refresh implemented in the InboxFragment which is the event to download any new messages. So, we have taken a flag ON_BACK_PRESSED = 1 when MessageDetailsFragment is loaded, and in InboxFragment if this flag is set to 1, then don't make the web service call GetMessagesFromCloud().
We want to know if above is right way to prohibit the web service call as onCreateView is always called when the fragment appear. Please advise.
From our knowledge when the same implementation is done on iOS platform, on hitting back, the fragment in view is popped out and the fragment behind appears. The web service call is not made each time when you hit back because the call to web service in in DidViewLoad event. They have 2 events - DidViewLoad and DidViewAppear. So when they hit back, DidViewAppear gets called where the service call is not made, and DidViewLoad does not get called.
Thank you.

A: You store you response in a Object and check for its null value.
 ResponseObject mResponse;//your response data type

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_inbox, container, false);
        context = getActivity();

        //Get Messages From Cloud - web service call
        if (mResponse == null) {
            GetMessagesFromCloud();
        } else {
            //update UI
        }
    }

    //your response callback. I am not sure what are your callbacks so its just a hint
    public void onSucess(ResponseObject response) {
        mResponse = response;
    }