text:
Q: concatenate tables from loop getting error - InvalidIndexError: Reindexing only valid with uniquely valued Index objects I need to concatenate tables created from a loop. The have repeats of the names in the columns but they are telling a different story, but for some reason when running this code I get an error:
InvalidIndexError: Reindexing only valid with uniquely valued Index objects

Here is the code:
url = 'https://www.impactfees.com/publications%20pdf/2019survey.pdf'

tables = camelot.read_pdf(url, flavor = 'stream', edge_tol = 500, pages = '4-end')

i = 0

while i in range(0,tables.n):
    table_value = tables[i].df.loc[0,4]
    header = 1
    header = tables[i].df.iloc[header]
    tables[i].df = tables[i].df.rename(columns = header)

    nan_v = float("NaN")
    tables[i].df.replace('',nan_v,inplace = True)
    tables[i].df.dropna(subset = ['Jurisdiction'], inplace = True)
    tables[i].df.replace(['Jurisdiction'], nan_v, inplace = True)
    tables[i].df.dropna(subset = ['Jurisdiction'], inplace = True)

#    Tot_col = tables[i].df.columns.get_loc('Total')
#    tables[i].df = tables[i].df.iloc[:,0:Tot_col+1]
    tables[i].df['report_name'] = table_value
    tables[i].df.loc[~tables[i].df.index.duplicated(keep = 'first')]
    i = i + 1

dfs = pd.concat([table.df for table in tables])

dfs

and here is the error I am getting:
InvalidIndexError                         Traceback (most recent call last)
<ipython-input-133-2617eb5ae448> in <module>
     23     i = i + 1
     24
---> 25 dfs = pd.concat([table.df for table in tables])
     26
     27

~\anaconda3\lib\site-packages\pandas\core\reshape\concat.py in concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy)
    296     )
    297
--> 298     return op.get_result()
    299
    300

~\anaconda3\lib\site-packages\pandas\core\reshape\concat.py in get_result(self)
    514                     obj_labels = obj.axes[1 - ax]
    515                     if not new_labels.equals(obj_labels):
--> 516                         indexers[ax] = obj_labels.get_indexer(new_labels)
    517
    518                 mgrs_indexers.append((obj._mgr, indexers))

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_indexer(self, target, method, limit, tolerance)
   3169
   3170         if not self.is_unique:
-> 3171             raise InvalidIndexError(
   3172                 "Reindexing only valid with uniquely valued Index objects"
   3173             )

InvalidIndexError: Reindexing only valid with uniquely valued Index objects

A: *

*camelot has an issue.  I had to patch utils.py to use a different user-agent

*the pages are not fully consistent,  hence passing a list to rename(columns=) does not work.  You need to pass a dict

*have kept two data frames - one with target rows,  other with excluded rows

*there remain inconsistent columns e.g. Drain Parks
import pandas as pd
import camelot

url = 'https://www.impactfees.com/publications%20pdf/2019survey.pdf'
tables = camelot.read_pdf(url, flavor = 'stream', edge_tol = 500, pages = '4-end')

df = pd.DataFrame()
dfexc = pd.DataFrame()
for i in range(tables.n):
    dft = tables[i].df.rename(columns={i:v.replace("\n"," ") for i,v in tables[i].df.iloc[1].items() if v!=""})
    if " " in dft.columns[0]:
        dft = dft.rename(columns={dft.columns[0]:dft.columns[0].split(" ")[0], 1:dft.columns[0].split(" ")[1]})
    m = (dft.State.str.len()!=2) | (dft.index < 2)

    dfexc = pd.concat([dfexc, tables[i].df.loc[m].assign(page=i)])
    df = pd.concat([df, dft.loc[~m].assign(page=i)])#.reset_index(drop=True)


text:
Q: Haskell: list/vector/array performance tuning I am trying out Haskell to compute partition functions of models in statistical physics. This involves traversing quite large lists of configurations and summing various observables - which I would like to do as efficiently as possible.
The current version of my code is here: https://gist.github.com/2420539
Some strange things happen when trying to choose between lists and vectors to enumerate the configurations; in particular, to truncate the list, using V.toList . V.take (3^n) . V.fromList (where V is Data.Vector) is faster than just using take, which feels a bit counter-intuitive. In both cases the list is evaluated lazily.
The list itself is built using iterate; if instead I use Vectors as much as possible and build the list by using V.iterateN, again it becomes slower ...
My question is, is there a way (other than splicing V.toList and V.fromList at random places in the code) to predict which one will be the quickest? (BTW, I compile everything using ghc -O2 with the current stable version.)

A: Vectors are strict, and have O(1) subsets (e.g. take). They also have an optimized insert and delete. So you will sometimes see performance improvements by switching data structures on the fly. However, it is usually the wrong approach -- keeping all data in either one form or the other is better. (And you're using UArrays as well -- further confusing the issue).
General rules:

*

*If the data is large and being transformed only in bulk fashion, using a dense, efficient structures like vectors make sense.

*If the data is small, and traversed linearly, rarely, then lists make sense.
Remember that operations on lists and vectors have different complexity, so while iterate . replicate on lists is O(n), but lazy, the same on vectors will not necessarily be as efficient (you should prefer the built in methods in vector to generate arrays).
Generally, vectors should always be better for numerical operations. It might be that you have to use different functions that you do in lists.
I would stick to vectors only. Avoid UArrays, and avoid lists except as generators.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does cotrastive loss and triplet loss have the margin element in them? Trying to learn Siamese networks for ranking tasks from here, I find it hard to understand why triplet loss and contrastive losses have the "margin" element in them.
The contrastive loss
$L(A, B) = y|f(A) - f(B)| + (1-y)max(0, m-|f(A) - F(B)|)$
The triplet loss
$L(A, P, N) = max(0, |f(A) - f(P)| - |f(A) - f(N)| + m) $
both have the margin m, which doesn't allow samples to be pushed passed it.
In the lecture, Prof. Laura Leal-Taixé says:

I want to keep separating them (the samples), until we hit a margin
m. And the idea is that it makes no sense to actually push $f(A)$
and $f(B)$ further apart if they are already as far as the margin m.
... I am not going to spend any energy in pulling them even further
away.

Here it is explained why we want to bound the loss.
Still, I would like to understand how does changing the value of m change the output, from the user's perspective, meaning, how does it affect clustering, or classification accuracy or other metrics? Why choose large or small m when engineering a system?


text:
Q: Drawer layout listView transparent background I'm trying to set the background of the listview inside the drawer layout to be transparent like google's camera app.
What happens is whenever I set the background of the listview to be transparent its items disappears
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main_drawer_layout_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<ListView
    android:id="@+id/activity_main_navigation_list"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:background="@android:color/transparent"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp" />

</android.support.v4.widget.DrawerLayout>

I tried to set it to a transparent image it didn't work either it doesn't work with any transparency added to the color of it's background.
This works:
        android:background="#232321"

This doesn't
        android:background="#fb232321"

Any idea how can I fix this problem

A: Try using android:background="@color/transparent" on DrawerLayout view and not on the listView. Also, you can use background transparent on childView of your ListView

A: So the I solved my problem by wrapping the listview with a Relativelayout it works with other layouts as well.
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black">

<FrameLayout
    android:id="@+id/activity_main_frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="@android:color/transparent"
    android:focusableInTouchMode="true">

    <ListView
        android:id="@+id/activity_main_navigation_list"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:choiceMode="singleChoice"
        android:clickable="true"
        android:divider="@android:color/transparent"
        android:dividerHeight="1dp"
        android:focusable="true" />
</RelativeLayout>

A: use #00000000 for black transparency


text:
Q: D3 bar chart left aligned x-axis How do I retain the x-axis as 100% of the container width while maintaining left aligned ticks with some padding.
  this.xAxis = d3.scaleBand()
            .range([0, this.barWidth * this.data.length], 1);

If I change the range to .range([0, this.svgWidth]), the width is correct but my ticks are evenly spread out which is not my desired outcome.

A: The second and third arguments are not accepted anymore in range when you use a band scale. Instead, you'll have to use paddingInner and paddingOuter.
So, change your snippet to this:
this.xAxis = d3.scaleBand()
    .range([0, this.svgWidth])
    .paddingInner(someValue)
    .paddingOuter(someValue);

Tweak with someValue until you find the desired outcome.


text:
Q: Log a user out of a SP but not IDP Is it possible to log a user out of an application that uses SAML authentication, but keep them logged into the IDP so they can continue to access other service providers?
I want to be able to log a user out of an application, and have them authenticate when they return to the application without logging them out of the IDP (i.e. I don't want to use single sign out). Is this possible with SAML?

A: There is no standard way to exclude termination of the IDP session when performing Single Logout. Also termination of a session with an individual session participant (a single Service Provider) while keeping the others opened is explicitly out of scope of the SAML 2.0 Single Logout profile (see saml-profiles-2.0-os.pdf, lines 1139-1143). So that's not the way to go.
But there's another solution. You can use local logout at your service provider (e.g. simply invalidate local HTTP session) and combine it with attribute ForceAuthn when sending the AuthnRequest to the IDP (see saml-core-2.0-os, line 2042). Setting the ForceAuthn attribute to true forces the Identity Provider to authenticate user even in case when there's an existing IDP session.
The whole flow could look like this:

*

*User accesses SP and is required to authenticate

*SP sends an SAML 2.0 AuthnRequest to IDP and sets the ForceAuthn flag to true

*IDP forces user to authenticate and responds to the SP

*SP creates a local session after validating the response

*User logs-out of the SP application which terminates only the local session and doesn't interfere with the IDP session or sessions at other SPs

Setting the ForceAuthn flag to true effectively disables single sign-on, so you might want to use some SP-side logic determining whether to use the flag or not.
An example of a valid request with the flag set follows:
<?xml version="1.0" encoding="UTF-8"?>
<saml2p:AuthnRequest AssertionConsumerServiceIndex="0"
    AttributeConsumingServiceIndex="myServiceID"
    Destination="https://idp.ssocircle.com:443/sso/SSOPOST/metaAlias/ssocircle"
    ForceAuthn="true" ID="a228aje276h0id1g48eihj5gfj9h8bi"
    IsPassive="false" IssueInstant="2014-04-11T22:07:05.438Z"
    Version="2.0" xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol">
    <saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">urn:test:sp</saml2:Issuer>
</saml2p:AuthnRequest>


text:
Q: SQL select all values in a table from a specific date to a specific date I wan't to select all the values from the table where COLUMN_DATUM > int fran && COLUMN_DATUM < int till. This basically means select from table where date > from && date < to.
Under is the method that should do the SQL batch.
public Cursor getAllItemsByDate(int fran, int till) {
        //CODE to return everything in the table TABLE_UTGIFTER ->
        //where COLUMN_DATUM > fran && COLUMN_DATUM < till.
}

Whole class for reference.
public class MyDBHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "ekonomi.db";

    public static final String TABLE_UTGIFTER = "utgifter";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_TITEL = "_titel";
    public static final String COLUMN_KATEGORI = "_kategori";
    public static final String COLUMN_PRIS = "_pris";
    public static final String COLUMN_DATUM = "_datum";

    private static final String TABLE_INKOMSTER = "inkomster";
    public static final String COLUMN_INKOMSTER_ID = "_inkomster_id";
    public static final String COLUMN_INKOMSTER_TITEL = "_inkomster_titel";
    public static final String COLUMN_INKOMSTER_KATEGORI = "_inkomster_kategori";
    public static final String COLUMN_INKOMSTER_BELOPP = "_inkomster_belopp";
    public static final String COLUMN_INKOMSTER_DATUM = "_inkomster_datum";

    private static final String CREATE_TABLE_UTGIFTER = "CREATE TABLE " + TABLE_UTGIFTER + "(" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_TITEL + " TEXT, " +
            COLUMN_KATEGORI + " TEXT, " +
            COLUMN_PRIS + " INTEGER, " +
            COLUMN_DATUM + " INTEGER " +
            ");";

    private static final String CREATE_TABLE_INKOMSTER =  "CREATE TABLE " + TABLE_INKOMSTER + "(" +
    COLUMN_INKOMSTER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
    COLUMN_INKOMSTER_TITEL + " TEXT, " +
    COLUMN_INKOMSTER_KATEGORI + " TEXT, " +
    COLUMN_INKOMSTER_BELOPP + " INTEGER, " +
    COLUMN_INKOMSTER_DATUM + " INTEGER" +
            ");";

    public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_UTGIFTER);
        db.execSQL(CREATE_TABLE_INKOMSTER);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS" + TABLE_UTGIFTER);
        db.execSQL("DROP TABLE IF EXISTS" + TABLE_INKOMSTER);
        onCreate(db);
    }

    public void addUtgifter(Utgift utgift){
//        SimpleDateFormat sdf = new SimpleDateFormat(("yyyy-MM-dd"));
//        String date = sdf.format(new Date());
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_TITEL, utgift.get_titel());
        values.put(COLUMN_KATEGORI, utgift.get_kategori());
        values.put(COLUMN_PRIS, utgift.get_pris());
        values.put(COLUMN_DATUM, utgift.get_datum());
        db.insert(TABLE_UTGIFTER, null, values);
        db.close();
    }

    public void addInkomster(Inkomst inkomst){
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_INKOMSTER_TITEL, inkomst.get_inkomster_titel());
        values.put(COLUMN_INKOMSTER_KATEGORI, inkomst.get_inkomster_kategori());
        values.put(COLUMN_INKOMSTER_BELOPP, inkomst.get_inkomster_belopp());
        values.put(COLUMN_INKOMSTER_DATUM, inkomst.get_inkomster_datum());
        db.insert(TABLE_INKOMSTER, null, values);
        db.close();
    }

    public Cursor getAllItemsInCursor() {
        return getWritableDatabase()
                .rawQuery("SELECT * FROM " + TABLE_UTGIFTER, null);
    }

    public Cursor getAllItemsByDate(int fran, int till) {
           //CODE to return everything in the table TABLE_UTGIFTER ->
          //where COLUMN_DATUM > fran && COLUMN_DATUM < till.

    }

    public String databaseToStringTest(int databaseId) {
        String dbString = "";
        SQLiteDatabase db = getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_UTGIFTER + " WHERE _id = "+ databaseId;

        Cursor c = db.rawQuery(query, null);
        c.moveToFirst();

        while (!c.isAfterLast()) {
            if (c.getString(c.getColumnIndex("_titel")) != null) {
                dbString += "Titel: ";
                dbString += c.getString(c.getColumnIndex("_titel"));
                dbString += "\n";
            }if(c.getString(c.getColumnIndex("_kategori"))!=null){
                dbString += "Kategori: ";
                dbString += c.getString(c.getColumnIndex("_kategori"));
                dbString += "\n";
            }
            if(c.getString(c.getColumnIndex("_pris"))!=null){
                dbString += "Pris: ";
                dbString += c.getString(c.getColumnIndex("_pris"));
                dbString += "kr";
                dbString += "\n";
            }
            if(c.getString(c.getColumnIndex("_datum"))!=null){
                dbString += "Datum: ";
                dbString += c.getString(c.getColumnIndex("_datum"));
                dbString += "\n";
            }
            c.moveToNext();
        }

        db.close();
        return dbString;
    }

    public String databaseToString() {
        String dbString = "";
        SQLiteDatabase db = getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_UTGIFTER + " WHERE 1";

        Cursor c = db.rawQuery(query, null);
        c.moveToFirst();

        while (!c.isAfterLast()) {
            if (c.getString(c.getColumnIndex("_titel")) != null) {
                dbString += c.getString(c.getColumnIndex("_titel"));
                dbString += ", ";
//                dbString += "\n";
            }if(c.getString(c.getColumnIndex("_kategori"))!=null){
                dbString += c.getString(c.getColumnIndex("_kategori"));
                dbString += ", ";
            }
            if(c.getString(c.getColumnIndex("_pris"))!=null){
                dbString += c.getString(c.getColumnIndex("_pris"));
                dbString += ", ";
            }
            if(c.getString(c.getColumnIndex("_datum"))!=null){
                dbString += c.getString(c.getColumnIndex("_datum"));
                dbString += "\n";
            }
            c.moveToNext();
        }

        db.close();
        return dbString;
    }

    public String databaseToStringInkomst() {
        String dbString1 = "";
        SQLiteDatabase db = getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_INKOMSTER + " WHERE 1";

        Cursor cInkomst = db.rawQuery(query, null);
        cInkomst.moveToFirst();

        while (!cInkomst.isAfterLast()) {
            if (cInkomst.getString(cInkomst.getColumnIndex("_inkomster_titel")) != null) {
                dbString1 += cInkomst.getString(cInkomst.getColumnIndex("_inkomster_titel"));
                dbString1 += ", ";
//                dbString += "\n";
            }if(cInkomst.getString(cInkomst.getColumnIndex("_inkomster_kategori"))!=null){
                dbString1 += cInkomst.getString(cInkomst.getColumnIndex("_inkomster_kategori"));
                dbString1 += ", ";
            }
            if(cInkomst.getString(cInkomst.getColumnIndex("_inkomster_belopp"))!=null){
                dbString1 += cInkomst.getString(cInkomst.getColumnIndex("_inkomster_belopp"));
                dbString1 += ", ";
            }
            if(cInkomst.getString(cInkomst.getColumnIndex("_inkomster_datum"))!=null){
                dbString1 += cInkomst.getString(cInkomst.getColumnIndex("_inkomster_datum"));
                dbString1 += "\n";
            }
            cInkomst.moveToNext();
        }

        db.close();
        return dbString1;
    }
}


text:
Q: Stop vibrations (API level 26 and above) Is there a way to stop/cancel vibrations for API level 26 and above?
Currently, I am using foreground services since I don't want my program to stop (and from API level 26 and above, there are time restrictions for background services). However, since then my vibrations don't seem to cancel as before (API 25 cancels as I would expect).
How can I accomplish this, preferably without using JobScheduler?


text:
Q: objective c javaScript Is it possible for a NSTextField to respond to Javascript commands??

A: No. It only accepts objective-c messages.
If you have a WebView that generates some javascript events though, they can trigger something outside of your web view, but this is already objective-c or some other native language. This can then call obj-c messages on the NSTextField.


text:
Q: hg: Commit some changes to another branch I was working in branch-a when I found an unrelated bug that should be fixed in the default branch. So, I'd like commit some of my changes to default, then merge default into the current branch, and keep working.
As far as I know, Mercurial doesn't allow committing directly into another branch, so I would have to switch to the default branch first. The problem is, I can't simply checkout the default branch, because the other changes would cause conflicts. One workflow I can think of is to shelve, checkout default, unshelve only the files that relate to the fix, commit, checkout branch-a, merge default, and finally, unshelve the rest of the files. Is there an easier way to accomplish this?

A: *

*Commit only subset of files, related to branch-a changes (use additionally power of Record Extension, if bugfix's and branch-a's  changes happens in some file(s) - commit only needed hunks of file) as changeset A

If you haven't MQ Extension:

*

*Commit the rest of changes into branch-a as changeset B (child of A)

*Rebase B (with Rebase Extension) changeset into default branch with --keep option in oder to have B in original location also

If you have MQ extension

*

*Create new patch with working-dir changes

*Unapply MQ-patch

*Update to default

*Apply patch

*Test, test...

*Finish patch (convert to permanent changeset)

*Graft this changeset only into branch-a branch


text:
Q: windows phone 8 - Map thumbnail I'd like to display a small image from the map fixed over a given location and if the user taps the map I'd like to navigate to different page with a large map control (just like in the HERE maps app when you're looking at a place's information).
So I'd like to disable every interaction with the map control (like pan, zoom, etc.) but I need know when it's tapped, so disabling the control won't work.
I tried using a small map control
<maps:Map Height="100" Width="100" x:Name="Map" Tap="Map_Tap" >

but I couldn't find a way to achieve the desired result with it.
Could you suggest something for this?

A: This is the general approach...
Place a transparent rectangle on top of your Map control. This should cause gesture recognition to be handled by the rectangle rather than the Map.
In a tap handler for your rectangle, navigate to the next page.
<Grid>
    <Rectangle Height="100" Width="100" Fill="Transparent" Tap="Map_Tap"/>
    <maps:Map Height="100" Width="100" x:Name="Map" >
</Grid>

Disclaimer: I haven't tested this code yet, but I think it should work!
Hope it helps.


text:
Q: Sort negative number string in iOS with NSStringCompareOptions I am trying to sort some list of strings. And names of elements could be almost anything, from real names, strings, dates,... and numbers.
I found NSStringCompareOptions with NSNumericSearch, wich work fast enough and it work nice so :
[1,2,21,3,55,6] --> [1,2,3,6,21,55]

But my problems are negative numbers
[1,2,3,-1,-4,-5] --> [-1,-4,-5,1,2,3]

What it is not right.
I know that Apple stays :
Numeric comparison only applies to the numerals in the string,
not other characters that would have meaning in a numeric representation
such as a negative sign, a comma, or a decimal point.

But my question is how to achieve this, because I know I am not only who do this.

EDIT :
Thanks to Narendra Pandey, but my real case is a little bit complicated, so his answer can't be used here.
So let say I have some dictionary with numbers as keys and strings as values :
dic = {@1:@"123", @2:@"-123", @5:"MyName",...};

then I have array of object with ids.
array = @[{object with id 5}, {object with id 2},...];

and I need sorted array of object by name of properties.
NSStringCompareOptions comparisonOption = NSCaseInsensitiveSearch | NSNumericSearch;

array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

    NSString * name1 = [dic objectForKey:obj1.someId];
    NSString * name2 = [dic objectForKey:obj2.someId];

    return [name1 compare:name2 options:comparisonOption];;
}];

EDIT 2:
Maybe I should state that I have solution, but it is 4 times slower that sorting with NSStringCompareOptions
// CHECK IF IT IS NUMBER

NSNumber * number1 = [numberFormatter numberFromString:string1];
NSNumber * number2 = [numberFormatter numberFromString:string2];
//
//    NSLog(@"NUMBERS : %@, %@", number1, number2);
if (number1 && number2) {
    return [number1 compare:number2];
}

return [string1 compare:string2 options:comparisonOption];

A: NSArray * numbers = @[@1, @2, @3, @-4, @-5, @6, @9];

    NSPredicate * predicateForPositive = [NSPredicate predicateWithFormat:@"integerValue >= 0"];

    NSArray * positiveNumbers = [numbers filteredArrayUsingPredicate:predicateForPositive];

    NSPredicate * predicateForNegative = [NSPredicate predicateWithFormat:@"integerValue <= 0"];

    NSArray * NegativeNumber = [numbers filteredArrayUsingPredicate:predicateForNegative];

    NSLog(@"Negative  number %@",NegativeNumber);

    NSLog(@"Positive number %@",positiveNumbers);

Output:
Negative  number (
    "-4",
    "-5"
)

Positive number (
    1,
    2,
    3,
    6,
    9
)

Now sort both and concate both Array.

A: Thanks to Narendra Pandey I found solution for me.
Let me state first that Narendra Pandey solution works, but it is slower, even 3 times.
(in my case 0.014s with NSStringCompareOptions, and 0,042 Narendra Pandey solution).
But if I use his idea and change it a little bit :
array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

    NSString * name1 = somehow get string1;
    NSString * name2 = somehow get string2;

    if ([string1 integerValue] <0 && [string2 integerValue]<0) {
        return - [string1 compare:string2 options:comparisonOption];
    }

    return [string1 compare:string2 options:comparisonOption];

}];

this method is faster, in my case 0,015s which is comparable with NSStringCompareOptions.
In this way you avoid to go through whole array at beginning to separate negative and positive numbers, and then sort them.

A: This function get any array and convert it to sorted Double array
var numberArray: [Any] = [4, 3.9, -23,3, 7.6, -51, 75.3, "0", "-(22)"]

/// This function get any array and convert it to sorted _Double_ array
/// - Note: Non-numerical elements are automatically removed from the array
/// - Parameters:
///     - numbers: array of anything
/// - Returns: sorted _Double_ array
func sortAnyNumbers(_ numbers: [Any]) -> [Double] {
    var _numbers: [Double] = []
    numbers.forEach { number in
        // Delete non-numeric characters
        if let numb = Double("\(number)".components(separatedBy: CharacterSet(charactersIn: "-01234567890.").inverted).joined()) {
            _numbers.append(numb)
        }
    }
    return _numbers.sorted()
}

print(sortAnyNumbers(numberArray))  //[-51.0, -23.0, -22.0, 0.0, 3.0, 3.9, 4.0, 7.6, 75.3]


text:
Q: Can't install Homebrew on Catalina I have both Xcode and command line tool installed. I am trying to install Homebrew on Catalina.
Its not installing this is what I get
   ==> /usr/bin/sudo /bin/mkdir -p /usr/local/bin
   mkdir: /usr/local/bin: Not a directory
   Failed during: /usr/bin/sudo /bin/mkdir -p /usr/local/bin

What should I do?

A: On terminal, just run:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"


text:
Q: How do you change the display format of unicode strings in Xcodes debug window? I've got a few typedef'd types to hold unicode strings, UTF16 which is defined as uint_least16_t, and UTF32 which is defined as uint_least32_t (to be compatible with the standard's definition of char(16|32)_t)
In Xcode's debugger, UTF32 strings are displayed as
I've tried LLDB's formatters, but they're not entirely working.
Here's the latest version of my UTF32 formatter: type format add -f unicode32 -C yes UTF32
Other things I've tried:
type format add -f unicode32s -C yes UTF32
type format add -f unicode32[] -C yes UTF32
type format add -f unicode32* -C yes UTF32
and all of those with (UTF32*) and (UTF32[]) as well as without.
I'm just not sure what what else to try at this point.

A: Update: I have now been informed that the OP wants to compile for C, rather than C++ and have therefore added the appropriate language tag to the question.
The types in the answer below are also available in C11 onwards, so the rest of this answer still applies.

Try changing your UTF16 typedef to char16_t.  This works for me.
For UTF32, either char32_t or wchar_t will work.
Please note that when assigning variables from string literals, the types of the string literals must match, like so (this code requires C11 / C++11 or later):
int main ()
{
    const char16_t *s1 = u"s1 is char16_t";
    const char32_t *s2 = U"s2 is char32_t";
    const wchar_t *s3 = L"s3 is wchar_t";
    return 0;
}

And when I put a breakpoint on the return statement and print these variables in the console, I get this:
(lldb) p s1
(const char16_t *) $0 = 0x0000000100000f44 u"s1 is char16_t"
(lldb) p s2
(const char32_t *) $1 = 0x0000000100000f58 U"s2 is char32_t"
(lldb) p s3
(const wchar_t *) $2 = 0x0000000100000f7c L"s3 is wchar_t"
(lldb)

You can also see them by hovering the mouse over them or in the 'Locals' window.
The full gamut of string literals available in C11 / C++11 is described here (C) and here (C++).
To answer the question you pose in the comments, no header file is needed.  These are all built-in types.  If your compiler is objecting to these please check the C / C++ version you are using in the build settings for your project in Xcode.


text:
Q: Many-to-many self-referential table Is there a good way to implement many-to-many relation between rows in single table?
Example: table to store word synonyms:
-- list of words
CREATE TABLE word (
    id    integer      PRIMARY KEY,
    word  varchar(32)  NOT NULL UNIQUE
);
INSERT INTO words (id, word) VALUES (1, 'revolve');
INSERT INTO words (id, word) VALUES (2, 'rotate');

-- M:M link between words
CREATE TABLE word_link (
    word1  integer      REFERENCES word(id) NOT NULL,
    word2  integer      REFERENCES word(id) NOT NULL,
    PRIMARY KEY (word1, word2)
);

Obvious solution results in probably not-1NF table, containing duplicate data:
INSERT INTO word_link(word1, word2) VALUES (1, 2);
INSERT INTO word_link(word1, word2) VALUES (2, 1);

While duplication can be dealt by adding (word1 < word2) check, it makes SELECTs much more complex (union comparing to trivial join) and is pretty arbitrary. This specific case can benefit from auxiliary table (such as 'meaning', so words are M:N linked to common meaning and not to each other, giving cleaner schema), but I'm interested in some general solution.
So is there a better (and hopefully common) way to implement such M:M relation?

A: In this case I'd add a CHECK CONSTRAINT on UPDATE and on INSERT to enforce that word1 is always less than word2 and vice-versa.

A: I'd create a view that was the following:
select distinct
    case when word1 < word2 then word1 else word2 end as word1,
    case when word1 < word2 then word2 else word1 end as word2
from
    word_link

That way, you always have a clean, no duplicate list that's easy to select from. I've found that's about as clean of a way as you can have to do a many-to-many relationship.


text:
Q: Basic steps to add Siri functionality to radio app I would like to be able to tell Siri "Hey Siri, play [app name]" for my radio app, and have it play a default station. What are the basic steps to achieve this? I'm not really looking for a Siri Shortcut per se, but built in "play" functionality. Is this possible?

A: You can achieve the following with Swift.
However, without any coding, Hey Siri, open [App Name] is possible automatically.
To add custom functionalities such as play a default station, please refer to this link


text:
Q: How to change Layout Right to Left at runtime according to Locale I am not able to decide the tile of this question so may be Title is mismatching with my question.
I have developed an Java Desktop application but now we have to deliver that desktop application to an client whose language is Right-To-Left (Arabic). So according to Locale is it possible to change layout of application?
Is it possible to do so? Or I have to make another copy of application where layout as per Right-To-Left.


text:
Q: Why is Python sorted() result like this? I might be missing something obvious here, but why does Python 2.x sorted() function work like this?
In [95]: l = [1, '5', 4, 2, '3', 'b', 'c', '-a']
In [96]: sorted(l)
Out[96]: [1, 2, 4, '-a', '3', '5', 'b', 'c']

Python 3 returns exception (TypeError: unorderable types: str() < int()), which I expect more than this result.

A: It looks like the ASCII values of the characters are used to sort relative to the actual numbers.
After converting the characters to their decimal ASCII values, the sorted list looks something like this:
[1, 2, 4,  '-a', '3', '5', 'b', 'c']
[1, 2, 4, 45 97,  51,  53,  98,  99]

Note that '-a' is sorted by the first character first, as is normal for an "alphabetical" ordering.


text:
Q: how to use jquery validation plugin to view the label specific message at the top? I am using jquery validation plugin to display error message in the top instead instead of beside the labels.  say, i have address , city, zip code ....if user don't enter anything i have to display the error message at top in a div like " please enter valid address" , "please enter valid city" etc...
how can I override the default behavior of the plugin .....any help will be appreciated ...
thanks!

A: You can use errorLabelContainer and wrapper options for this:
$("form").validate({
  errorLabelContainer: "#someElementUpTop", //a <ul> element for example
  wrapper: "li" //display them in a list
});

errorLabelContainer determines where the error elements are added, wrapper determines what they're wrapped in.  In this case #someElementUpTop is a <ul> to append the <li> wrapped labels to...so clicking still goes to the correct element in the page that has the validation error.  If you need another element above this, say a <div> that hides and shows appropriately when there are/aren't errors, add a errorContainer: "#someDiv" option as well.


text:
Q: Writing a recursive Preorder tree search that returns the answer as a list I have created the following Tree
T<Integer> t1 = new T(84, new T(48, new T(30), new T(50)),
                new T(96, new T(90), new T(1)));

What I am now trying to do is to sort the tree in pre order and returns the answer as a list.  My code sorts of work but I am building multiple lists rather than one single list.  My code is as follows:
    public static<E> List<E> porderlist(T<E> a) {

           if (a.isEmpty())
               return new List<E>();
            else {

            return new List(a.getValue(), new List(porderlist(a.getLeft()),     porderlist(a.getRight())));

   }

The output I get is [84, [48, [30, []], 50, []], 96, [90, []], 1, []]
When the output I want is [84,48,30,50,96,90,1]
Any clues as to how I can stop the nesting of the lists.
Many thanks in advance

A: public static<E> List<E> porderlist(T<E> a) {
    if (a.isEmpty())
        return new ArrayList<E>();
    else {
        List<E> list = new ArrayList<E>();
        list.add(a.getValue());
        list.addAll(porderlist(a.getLeft()));
        list.addAll(porderlist(a.getRight()));
        return list;
    }
}


text:
Q: NumPy - Expand and Repeat Is there a way to "expand" an array and repeat the last element to fill the expansion?
Another post talks about expansion and padding with 0 but I wish to repeat the last value as the pad.
Say I have an array:
[[1, 2],
 [3, 4],
 [0, 0]]

And I need to insert [5, 6, 6] to replace the [0, 0], obviously NumPy wouldnt allow this. But can I reshape/expand to:
[[1, 2, 2],
 [3, 4, 4],
 [5, 6, 6]]

I'm reading through a file where the number of values may vary in length, but I need the array to be of the same shape. One way to do this is read through the file first and find the maximum length, then read it again an populate, but the file is 10GB+ so I would prefer to do it on a single pass by "expanding" and backfilling with repeats.

A: Looks like what you require is numpy.pad using the edge mode. From the doc:
'edge'
    Pads with the edge values of array.

Example code:
>>> ar = np.array([[1,2], [4,5]])
>>> ar
array([[1, 2],
       [4, 5]])
>>> np.pad(ar, [(0, 0), (0, 4)], mode="edge")
array([[1, 2, 2, 2, 2, 2],
       [4, 5, 5, 5, 5, 5]])

The first (0, 0) tuple specify no padding on the first axis, while the second basically does "add 0 padding to the left and 4 to the right"


text:
Q: What should I do to use place instead pack? How I can to use place() instead pack()?
tk.Label(frame, text='Label %i' % i).pack() # ==> tk.Label(frame, text='Label %i' % i).place(x=400,y=50*i)

When I use to place() instead pack() the Labels disappear from windows.
import tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root)
canvas.place(relx=0, rely=0, relheight=1, relwidth=1)

frame = tk.Frame(canvas)
# resize the canvas scrollregion each time the size of the frame changes
frame.bind('<Configure>', lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
# display frame inside the canvas
canvas.create_window((0,0), window=frame, anchor="nw")

scrolly = tk.Scrollbar(root, command=canvas.yview)
scrolly.place(relx=1, rely=0, relheight=1, anchor='ne')
canvas.configure(yscrollcommand=scrolly.set)

#################################
#Only this I want to use place() instead pack().
# populate the frame
for i in range(20):
    tk.Label(frame, text='Label %i' % i).pack() # ==> tk.Label(frame, text='Label %i' % i).place(x=400,y=50*i)
#################################

root.mainloop()


text:
Q: get the date of Monday of the week having the year and the week number of the year How could I get the date of the day Monday of a week having the year and number of week in the year?
For example, if the year is 2020 and the number of the week in the year is 01, the expected result is 2019-12-30

A: Hope this is what you are looking for :)
<?php

$week_number = '06';
$year_number = '2020';

function getStartAndEndDate($week, $year) {
  $date = new DateTime();
  $date->setISODate($year, $week);
  for ($i=0; $i < 7; $i++) {
    $array[$i] = $date->format('Y-m-d');
    $date->modify('+1 days');
  }
  return $array;
}

$week_array = getStartAndEndDate($week_number,$year_number);

echo $week_array[0]; // 0 = monday, 1 = tuesday, and so on :)

?>

A: <?php
$week = 1;
$year = 2020;

$dateTime = date_create(sprintf("%04dW%02d",$year,$week)); //always a monday

echo $dateTime->format('Y-m-d');  //2019-12-30


text:
Q: I want to Change color of table when i click on button when i click on dropdown then select multiple after that i have show same table repeatedly, But i want to show that table with different colors.I have append a table on click function, but i want to stop append when i click fourth time on button and also change the color of table at that time
I am new in coding..please help me!

                <select id="selector" onchange="yesnoCheck(this);">
                    <option value="select">__Select__</option>
                    <option value="single">Single</option>
                    <option value="multiple">Multiple</option>
                </select>

                        Location

                            <input id="t1" type="text">

                        P1
                            <input id="t2" type="text">

                        P2

                            <input id="t3" type="text">

                        P3

                            <input id="t4" type="text">

                        Sometime
                            <input id="t5" type="text">

                        Full day
                            <input id="t6" type="text">

                Location
                <input type="text" id="pan" name="pan">
                <button type="button" id="formButton">+</button>// when click on this button

Hello,I am new in coding and this is my code i want to change my table color repeatedly on click function

when i click on dropdown then select multiple after that i have show same table repeatedly, But i want to show that table with different colors.

A: check this resssources:

*

*How do you get random RGB in Javascript?

*https://sebhastian.com/jquery-change-background-color/


text:
Q: React Performance I found shouldDidUpdate's performance worse than refs control update。
CODE:
//A: shoudDidUpdate control udpate

import React, {Component, PropTypes, cloneElement} from 'react';
import ReactDOM from 'react-dom';

class Level1 extends Component {

    constructor(props, context) {
        super(props, context);
    }

    render() {
        let {rows, columns}=this.props;

        return

            {rows.map((row, idx) => {
                return <Level2 key={idx} row={row} columns={columns} ref={`row_${idx}`}/>
            })}

    }

    shouldComponentUpdate(nextProps) {
        return nextProps.rows !== this.props.rows
            || this.props.columns !== nextProps.columns;
    }
}

class Level2 extends Component {
    render() {
        let {row, columns}  = this.props;
        return

            <Level3 row={row} key="level2" ref="row" columns={columns}/>

    }

    shouldComponentUpdate(nextProps) {
        return nextProps.row !== this.props.row
            || this.props.columns !== nextProps.columns;
    }
}
class Level3 extends Component {
    render() {
        let {row, columns} = this.props;
        return

            {columns.map((column, i) => {
                return <Level4 ref={column} value={row[column]} key={i}/>
            })}

    }

    shouldComponentUpdate(nextProps) {
        return (nextProps.row !== this.props.row
        || this.props.columns !== nextProps.columns);
    }
}

class Level4 extends Component {
    render() {
        let {value} = this.props;
        this.value = value;
        return
            {value}

    }

    shouldComponentUpdate(nextProps) {
        return nextProps.value !== this.props.value;
    }
}

function getData(cIndex = "C",
                 vIndex = "V") {
    let rows = [],
        columns = [];

    for (let i = 0; i < 24; i++) {
        columns.push(`${cIndex}${i}`);
    }

    for (let row = 0; row < 20; row++) {
        let rowData = {};
        columns.forEach((column) => {
            rowData[column] = `${vIndex}${row}_${column}`;
        })
        rows.push(rowData)
    }
    return {rows: rows, columns: columns};
}

var __ret = getData();
var rows = __ret.rows;
var columns = __ret.columns;

ReactDOM.render(<Level1 rows={rows} columns={columns}/>, document.getElementById('root'));
console.time("a")

for (let i = 0; i < 10; i++) {

    var __ret = getData("C", "b" + i);
    var rows = __ret.rows;

    ReactDOM.render(<Level1 rows={rows} columns={columns}/>, document.getElementById('root'));
}
console.timeEnd("a")

//B: this.refs.update control update

import React, {Component, PropTypes, cloneElement} from 'react';
import ReactDOM from 'react-dom';

class Level1 extends Component {

    constructor(props, context) {
        super(props, context);
    }

    render() {
        let {rows, columns}=this.props;

        return

            {rows.map((row, idx) => {
                return <Level2 key={idx} row={row} columns={columns} ref={`row_${idx}`}/>
            })}

    }

    shouldComponentUpdate(nextProps) {
        this.preRows = this.props.rows;
        // console.info("l1",nextProps.rows !== this.props.rows
        //     || this.props.columns !== nextProps.columns);
        return nextProps.rows !== this.props.rows
            || this.props.columns !== nextProps.columns;
    }

    componentDidUpdate() {
        let {rows, columns}=this.props;
        rows.forEach((row, idx) => {
            this.refs[`row_${idx}`].update(row, columns);
        });
    }

}

class Level2 extends Component {
    render() {
        let {row, columns}  = this.props;
        this.row = row;
        this.columns = columns;
        return

            <Level3 row={row} key="level2" ref="row" columns={columns}/>

    }

    update(row, columns) {
        if (row !== this.row || columns !== this.columns) {
            this.refs.row.update(row, columns);
            this.row = row;
            this.columns = columns;
        }
    }

    shouldComponentUpdate(nextProps) {
        // console.info("l2",nextProps.rows !== this.props.rows
        //     || this.props.columns !== nextProps.columns);

        return this.props.columns !== nextProps.columns;
    }
}
class Level3 extends Component {
    render() {
        let {row, columns} = this.props;
        this.row = row;
        this.columns = columns;
        return

            {columns.map((column, i) => {
                return <Level4 ref={column} value={row[column]} key={i}/>
            })}

    }

    update(row, columns) {
        if (row !== this.row || columns !== this.columns) {

            columns.forEach((column) => {
                this.refs[column].update(row[column]);
            });
            this.row = row;
            this.columns = columns;
        }
    }

    shouldComponentUpdate(nextProps) {
        // console.info("l3",nextProps.row !== this.props.row
        //     || this.props.columns !== nextProps.columns);
        return this.props.columns !== nextProps.columns;
    }
}
class Level4 extends Component {
    render() {
        let {value} = this.props;
        this.value = value;
        return
            {value}

    }

    update(value) {
        if (value !== this.value) {
            this.refs.columnValue.innerHTML = value;
            this.value = value;
        }
    }

    shouldComponentUpdate(nextProps) {
        // console.info("l4",nextProps.value !== this.props.value);
        return false;
    }
}

function getData(cIndex = "C",
                 vIndex = "V") {
    let rows = [],
        columns = [];

    for (let i = 0; i < 24; i++) {
        columns.push(`${cIndex}${i}`);
    }

    for (let row = 0; row < 20; row++) {
        let rowData = {};
        columns.forEach((column) => {
            rowData[column] = `${vIndex}${row}_${column}`;
        })
        rows.push(rowData)
    }
    return {rows: rows, columns: columns};
}

var __ret = getData();
var rows = __ret.rows;
var columns = __ret.columns;

ReactDOM.render(<Level1 rows={rows} columns={columns}/>, document.getElementById('root'));
console.time("a")

for (let i = 0; i < 10; i++) {

    var __ret = getData("C", "b" + i);
    var rows = __ret.rows;

    ReactDOM.render(<Level1 rows={rows} columns={columns}/>, document.getElementById('root'));
}
console.timeEnd("a")

My Computer : macbook pro 2.8Ghz i7 memory 16GB
Browser : chrom 56
A: 260 - 300 ms
B: 30 ms
Browser: IE 11
A: 1000-1100ms
B: 500-630ms
Is there a better way to deal with such a scenario?
The scenario for this example is to update the entire list of data at a time. So, 'shouldComponentUpdate (nextProps) {
         Return nextProps.rows! == this.props.rows
             || this.props.columns! == nextProps.columns;
     } ', Which returns true every time. This is not wrong.
The key point is that the implementation of B program does not have to be executed each time, shouldComponentUpdate the call stack. I think there is a better way to solve this problem.


text:
Q: I am trying to delete an item in my list after making changes to it but it won't delete and I dont understand why The aim of my code is to take an input from the user and to check if each character could be a string or an integer. It would then put the character into different lists.
Also if you know a better way to do this please say. This is only thing I could think of.
user_inp = input("please give me an input")

def split_func():
    for i in user_inp:
        user_inp_split.append(i)

def check():

    for i in user_inp:
        try :
            temp = int(i)
            items2.append(temp)
            del user_inp_split[i]
            # the line that wont work

            print (user_inp)

            print (user_inp_split)

        except:
            print ("get to stage 2")

A: Welcome to StackOverflow, the problem that you have is that you do not have an organized code, i reorganized your code in order to make the task that you want:
user_inp = input("please give me an input: ")
user_inp_split = list(user_inp) #user input converted to list
items2 = [] #Character list
items1 = [] #integer list

def check():
    for i in user_inp_split: #iterates over the user_input list
        try :
            items1.append(int(i,10)) #Convert the items to an integer with base on 10
        except ValueError:
            items2.append(i) #if not, append to the items2 list
    print ("User input {}".format(user_inp))
    print ("Characters {}".format(items2))
    print ("Integers {}".format(items1))
check() #call the function, otherwise it wont work

First of all, you must declare the list to be appended to (line 3 and 4), then we must iterate, and check if they are integer, if they can be converted with the built-in function int(), they are integers, otherwise, they are not (lines 8 to 11), finally we print the user input to check that everything is OK.


text:
Q: Adding an scroll eventlistener in lwc Hi Everyone I am new to salesforce and lwc.I want to build a go to top button in my lwc component and i am stuck in a place .I want to make the button visible after user has scrolled to a certain distance but the problem i am facing is i am not able to understand how to add an event listener that fires a function whenever scroll event takes place can u help me. In general i want to ask how to add an event listener in salesforce ?
window.onscroll  = function     () {
/*Something happens*/
}

I tried to add this but it throws error in the js file and I tried to write this in rendered callback but i am not able to fire a function that is written outside the rendered callback using this.func(); inside the function of window.onscroll


text:
Q: How to convert the size selector to a swatch? I'm using Magento2 and I'm pretty noob at it.
I wanted to change this select dropdown in catalog_product_view.xml ----->

and convert it to this ------>

this is the configurable.phtml in which the select is ----->
<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes 2020-present. All rights reserved.
 * This product is licensed per Magento install
 * See https://hyva.io/license
 */

use Magento\ConfigurableProduct\Block\Product\View\Type\Configurable;
use Magento\Framework\Escaper;

/** @var Configurable $block */
/** @var Escaper $escaper */

$product = $block->getProduct();
$productId = $product->getId();
$attributes = $block->decorateArray($block->getAllowAttributes());
?>
<?php if ($product->isSaleable() && count($attributes)):?>

    <?= $block->getChildHtml('options_configurable_js') ?>

    <div x-data="initConfigurableDropdownOptions_<?= (int) $productId ?>()"
         x-init="init();"
         @private-content-loaded.window="onGetCartData($event.detail.data)"
         class="mb-6 diomannaro"
    >

            <?= $escaper->escapeHtml(__('Options')) ?>

        <?php foreach ($attributes as $attribute): ?>

                <select name="super_attribute[<?= $escaper->escapeHtmlAttr($attribute->getAttributeId()) ?>]"
                        id="attribute<?= $escaper->escapeHtmlAttr($attribute->getAttributeId()) ?>"
                        class="form-select super-attribute-select"
                        x-on:change="changeOption(<?= (int) $attribute->getAttributeId() ?>, event.target.value)"
                        required="required">
                    <template
                        x-for="(item, index) in getAllowedAttributeOptions(<?= (int) $attribute->getAttributeId() ?>)"
                        :key="item.id"
                    >
                        <option
                            :value="item.id"
                            x-html="item.label"
                            :selected="selectedValues[<?= $escaper->escapeHtmlAttr($attribute->getAttributeId()) ?>] ===
                                item.id">
                        </option>
                    </template>
                </select>

        <?php endforeach; ?>

<?php endif;?>

I tried using a radio input wrapped in a label, but i t didn't work. Should I change this from admin? If you can help guys it would be awesome.
If you need more info I will provide them quickly.
Thanks.


text:
Q: Is there a rational function $f$ satisfying $f(x) =f\left( \frac{1}{1-x} \right)$ for all $x$? I would like to find a pair of relatively prime polynomials $p,q \in k[x]$ (where $k$ is a field) such that $$\frac{p(x)}{q(x)} = \frac{p \left( \frac{1}{1-x} \right)} {q\left( \frac{1}{1-x} \right)} .$$
I believe that $p$ and $q$ should have at most degree 3.
A similar situation is the following:
Take $f(x) = \frac{x^2+1}{x} \in k(x)$.  Then
$$f(x) = f\left( \frac{1}{x} \right).$$
This problem I am currently dealing with seems much more elusive.

A: Let $r(x) = 1/(1-x)$. Note that $r(r(r(x))) = x$. Therefore, the rational function $$f(x) = x + r(x) + r(r(x)) = \frac{-x^3 + 3x - 1}{x(x-1)}$$ satisfies $$f\left(\frac{1}{1-x} \right) = r(x) + r(r(x)) + r(r(r(x))) = r(x) + r(r(x)) + x = f(x)$$ as desired.


text:
Q: Moving IDE Log menu item in NetBeans RCP How can we move menuitem "IDE Log" of NetBeans RCP from "View" menu to other menu ?

A: Hiding existing menu

*

*Use the layer.xml file (add if not there) and _hidden suffix to hide the required menu

*Refer the answer https://stackoverflow.com/a/10291239/446251 for detailed explanation

Adding menu like existing menu

*

*Note the action class for the current menu in the layer file

*Add your own menu where needed and set the action class to the earlier noted action

Example Layer file
<filesystem>
<folder name="Menu">
    <folder name="View">
        <file name="Separator2.instance_hidden"/>
        <file name="org-netbeans-core-actions-LogAction.shadow_hidden"/>
    </folder>
    <folder name="Other">
        <file name="org-netbeans-core-actions-LogAction.shadow">
            <!--org.netbeans.core.actions.LogAction-->
            <attr name="originalFile" stringvalue="Actions/View/org-netbeans-core-actions-LogAction.instance"/>
            <attr intvalue="500" name="position"/>
        </file>
    </folder>
</folder>
</filesystem>

Example Project code
You can check the bare minimum NetBeans Platform application here https://archive.org/download/application1_201601/application1.zip


text:
Q: How to change default path for "save the figure" in python? I have a python code to create a figure. After showing it with plt.show(), I want to save the figure.
To avoid messing up the aspect ratio, resolution, etc, I do not want to use the savefig-command in the code. Instead, I want to use the "save the figure" button from the figure window.
However, by default, it prompts my home folder as location for the save. I would like the save to automatically be in the directory where the code was executed.
How/where can I change this window default path for saving to the current folder (or somewhere else)?
I tried this command from  Change directory to the directory of a Python script at the beginning but it did not help, even though gives the filename correctly:
os.chdir(os.path.dirname(__file__))

A: It looks like you may be able to set this by changing the defaults file matplotlibrc, check out the guidance under http://matplotlib.org/users/customizing.html
where the important lines are under the savefig parameters:
# the default savefig params can be different from the display params

...

savefig.directory   : ~        # default directory in savefig dialog box,
                               # leave empty to always use current working directory

It seems this was introduced in matplotlib 1.3. I guess you could set this using,
matplotlib as mpl
mpl.rcParams["savefig.directory"] = os.chdir(os.path.dirname(__file__))

at the top of a script or by changing the matplotlibrc file.
For the dialog to default to cwd instead of script location (thanks to jjcf89 for this)
matplotlib as mpl
mpl.rcParams["savefig.directory"] = ""

A: For a non-code solution, you can create a file called matplotlibrc with the following contents:
savefig.directory:

This sets the value of savefig.directory to the empty string, causing it default to the current working directory.
You can put this matplotlib file in the current working directory, or in a location specified in the documentation. For example, on Linux it should be in .config/matplotlib/ (don't be worried if there's no matplotlibrc file there already, there wasn't one on my machine either).


text:
Q: FileNotFoundError writing to Azure DFS in Python When using this code
with open('/dbfs/FileStore/tables/jenks_tweets.txt', 'w') as f:
   for item in final_tweets:
     f.write('%s\n' % item)

I get this error:
FileNotFoundError: [Errno 2] No such file or directory: '/dbfs/FileStore/tables/jenks_tweets.txt'
FileNotFoundError                         Traceback (most recent call last)
 in
16
17
---> 18 with open('/dbfs/FileStore/tables/jenks_tweets.txt', 'w') as f:
19    for item in final_tweets:
20      f.write('%s\n' % item)
FileNotFoundError: [Errno 2] No such file or directory: '/dbfs/FileStore/tables/jenks_tweets.txt'

A: It turns out the slashes were facing in the wrong direction
with open('\dbfs\FileStore\tables\jenks_tweets.txt', 'w') as f:
   for item in final_tweets:
     f.write('%s\n' % item)


text:
Q: PHP double arrow notation for instances of an class(es) I would be grateful if someone explained to me the use of double arrow notation in PHP. I suggest is a double classes and instantiation of that classes, but I am not sure. Some examples will be good. Thanks.
Something like this:
$obj->prop->methd();

A: As an example, take for instance two classes:
<?php

class a {
    function test() {
        echo "test";
    }
}

class b {
    var $prop = null;
    function __construct() {
        $this->prop = new a();
    }
}

$obj = new b();
var_dump($obj);
$obj->prop->test();

?>

http://codepad.org/aEeRs45A
Class a gives $prop a method when b is instantiated and the constructor is called. $prop in b is an object of class b.

A: As long as your method returns an object you can call the methods of that object too, and so on.
So here's an example of how you can chain methods of a class.
<?php
class MyTest {
    public function Hello() {
        echo "Hello ";
        return $this;
    }

    public function World() {
        echo "World!";
    }
}

$h = new MyTest();
$h->Hello()->World();
?>

A: This just indicates that $obj has a property that is a class of some kind rather than an atomic variable.  The inner class has a method method() which is called from the second arrow operator.  You could also access properties of the inner class via the second arrow.
// Access the inner property
echo $obj->prop->inner_property
// 1234

// Call the inner method
$obj->prop->method();
// I'm the method!

The class definitions might be something like:
class obj
{
   // Will hold an instance of class Something
   public $prop;

   public function __construct() {
      $this->prop = new Something();
   }
}

class Something
{
   public $inner_property = 1234;

   public function method() {
     echo "I'm the method!";
   }
}

A: prop is a property of $obj which is also an object. Therefore, to access prop's method, you must use the arrow operator again.

A: $obj->prop is variable defined like
class class1{
    public $prop = new class2;
}

class2{
    function methd(){
        echo "methd function called";
    }
}

$obj->prop->methd();


text:
Q: PHPUnit output text is messed up I don't know if I should be asking this here since this is not entirely programming-related but please pardon me in advance.
How do I correct the highlighted text in the screenshot below?
The "<-[" texts.
Also, how do I run PHPUnit in Windows that will show show the usual green/red bar when passing/failing tests? I tried Git Bash console but it also displays messed up output and no bar.

A: You're looking at ANSI colour codes, which don't work in cmd.exe.
The configuration file can be used to set the colors directive to false. Alternatively, you should be able to use the --colors command line option.


text:
Q: EEPROM Emulation utility fails during "PageTransfer" function (XCUBE-EEPROM V3.0.0 and 4.0.0) on STM32G474 MCU I have incorporated the EEPROM emulation utility in a project based on STM32G474CE MCU. So far the read/write functionality works fine. The problem comes when a page is full and the pag transfer function is called. At the end of this function no variables were copied from the "valid" page to the "receive" page. All my variables were lost after page swap.
Upon debugging, i found out that the transfer "for" loop, is trying to read all virtual addresses from 1 to "NO_OF_VARIABLES", and transfer them to the "receive" page. In my case however, there are only 200 variables so NO_OF_VARIABLES = 200, but the virtual addresses are scattered along ranges 0xA000, 0xB000 0xC000 and so on. Therefore, the FOR loop never looks for these variable at all and hence also does not copy them. This looks like a bug to me unless there is something that i am missing or doing wrong. The example application provided with the utility works fine becaue in that aplication, variables are assigned virtual adresses sequentially from 0x0001 onwards so this does not case a problem for "PageTransfer" function. Logically, according to the refrence manual, there is no limitation or requirement to assign virtual addresses to variables except the values of 0xFFFF and 0x0000. Please provide a solution to this. We are stuck in the middle of a project becaue of this problem.
Here is the code snippet for the FOR loop for transferring variables.

/* First element in receive page can be any one, the following elements are */

/* ordered from the beginning. */

/* In case of recovery, Pre-Last element in receive page could be */

/* corrupted if reset occured during write of this element, */

/* and last element is dummy value that we have just written. */

/* Transfer shall then resume from (uhNbWrittenElements-3) variable index */

for (varidx = (uhNbWrittenElements >= 3U?(uhNbWrittenElements-3U+1U):1U); varidx < NB_OF_VARIABLES+1; varidx++)

{

 /* Check each variable except the one passed as parameter */

 if (varidx != VirtAddress)

 {

  /* Read the last variable updates */

  status = ReadVariable(varidx, &DataValue);

  if (status == EE_OK)

  {

   /* In case variable corresponding to the virtual address was found */

   /* Transfer the variable to the new active page */

   /* If program operation was failed, a Flash error code is returned */

   #ifdef DUALCORE_FLASH_SHARING

   status = VerifyPagesFullWriteVariable(varidx, DataValue, EE_TRANSFER);

   #else

   status = VerifyPagesFullWriteVariable(varidx, DataValue);

   #endif

   if (status != EE_OK)

   {

    return status;

   }

  }

  else

  {

   if (status != EE_NO_DATA)

   {

    /* In case variable is not found , do nothing */

    /* Any other status is error code occurs during variable read */

    return status;

   }

  }

 }

}


text:
Q: C# starting remote service on a virtual machine I have a host that runs several virtual machines, on every virtual machine runs a service wich works fine locally but when i try to execute it remote from the host i get accces denied.
i have searched google for a while now, impersonate doesnt work because the host account is very different than the virtual machine accounts.
i use the folowing code to start the remote service.
ServiceController sc = new ServiceController("ExecuterService", "servername");
sc.Start(id);

now my question is: is there a way to authenticate my C# app so it can start the remote service by for example just giving in the user credentials for that machine?

A: If the host application have correct access rights, then you could workaround and use process call to NET console comands:
ProcessStartInfo processInfo = new ProcessStartInfo("NET", "start ExecuterService");
Process process = Process.Start(processInfo);
p.WaitForExit();

But it is ugly.


text:
Q: Spark spark-sql-kafka - java.lang.NoClassDefFoundError: org/apache/kafka/common/serialization/ByteArraySerializer I am experimenting with spark reading from a kafka topic through "Structured Streaming + Kafka Integration Guide".
Spark version: 3.2.1
Scala version: 2.12.15
Following their guide on the spark-shell including the dependencies, I start my shell:
spark-shell --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.2.1

However, once I run something like the following in my shell:
val df = spark.readStream.format("kafka").option("kafka.bootstrap.servers","http://HOST:PORT").option("subscribe", "my-topic").load()

I get the following exception:

java.lang.NoClassDefFoundError: org/apache/kafka/common/serialization/ByteArraySerializer`

Any ideas how to overcome this issue?
My assumption was with using --packages, all dependencies should be loaded as well. But this does not seem to be the case. From the logs I assume that the package gets loaded successfully, including the kafka-clients dependency:
org.apache.spark#spark-sql-kafka-0-10_2.12 added as a dependency
resolving dependencies :: org.apache.spark#spark-submit-parent-3b04f646-471c-4cc8-88fb-7e32bc3226ed;1.0
confs: \[default\]
found org.apache.spark#spark-sql-kafka-0-10_2.12;3.2.1 in central
found org.apache.spark#spark-token-provider-kafka-0-10_2.12;3.2.1 in central
found org.apache.kafka#kafka-clients;2.8.0 in central
found org.lz4#lz4-java;1.7.1 in central
found org.xerial.snappy#snappy-java;1.1.8.4 in central
found org.slf4j#slf4j-api;1.7.30 in central
found org.apache.hadoop#hadoop-client-runtime;3.3.1 in central
found org.spark-project.spark#unused;1.0.0 in central
found org.apache.hadoop#hadoop-client-api;3.3.1 in central
found org.apache.htrace#htrace-core4;4.1.0-incubating in central
found commons-logging#commons-logging;1.1.3 in central
found com.google.code.findbugs#jsr305;3.0.0 in central
found org.apache.commons#commons-pool2;2.6.2 in central

A: The logs seem fine, but you can try to include kafka-clients dependency in --packages argument as well
Otherwise, I'd suggest creating an uber jar instead of downloading libraries every time you submit the app


text:
Q: Calling srand() twice in the same program why is it when i call srand() at 2 very different points it cause numbers to not be random? Once i remove one of them it goes back to normal.

A: It depends on how you call it. The purpose of srand() is to seed the pseudo-random number generator used by rand(). So when you call srand(i), it will initialise rand() to a fixed sequence which depends on i. So when you re-seed with the same seed, you start getting the same sequence.
The most common use case is to seed the generator just once, and with a suitable "random" value (such as the idiomatic time(NULL)). This guarantees makes it likely that you'll get different sequences of pseudo-random numbers in different program executions.
However, occasionally you might want to make the pseudo-random sequence "replayable." Imagine you're testing several sorting algorithms on random data. To get fair comparisons, you should test each algorithm on the exact same data - so you'll re-seed the generator with the same seed before each run.
In other words: if you want the numbers simply pseudo-random, seed once, and with a value as random as possible. If you want some control & replayability, seed as necessary.

A: srand (seed);

Two different initializations with the same seed will generate the
  same succession of results in subsequent calls to rand.
If seed is set to 1, the generator is reinitialized to its initial
  value and produces the same values as before any call to rand or
  srand.
Each time rand() is seeded with srand(), it must produce the same
  sequence of values.

http://www.cplusplus.com/reference/cstdlib/srand/
http://en.cppreference.com/w/cpp/numeric/random/srand

A: Are you initializing the srand? You have to initialize it in the beginning of you function/code like this:
srand(time(NULL));

It should work :)

A: You may read about pseudo random numbers generators, standard library srand-rand functions are implementation of one of them.
The core idea is that pseudo random generator is initialized with the special number - seed.
srand() is used to set seed. For every seed pseudo random generator generate exactly the same sequence of numbers ever. By using different seeds you'll get different sequences of numbers.
So if you want to get different random numbers everytime you start you program, you need everytime to set new seed.
The one of simpliest way to do this is to use time for seed.
#include <time.h>

srand((unsigned int)time(0));


text:
Q: Add the \in (is a member of the set) notation into qplot I have a simple code as below. I would like to create the x-lable with the math notation "x \in [1,10]" to demonstrate that x is continuous and is a member of a particular interval/set. Is there anyway to set that?
cat("\014")
require(ggplot2)
n=10
x=seq(1,n,0.01)
y=x*x-2*x-30
x;y
m <- qplot(x, y, xlim=c(0,n),  xlab = "x in [1, 10]", ylab="", axis = FALSE)
m

A: You need to use an expression; see ?plotmath for a list and examples
require(ggplot2)
n=10
x=seq(1,n,0.01)
y=x*x-2*x-30
qplot(x, y, xlim=c(0,n),  xlab = expression(x %in% '[1, 10]'), ylab="", axis = FALSE)


text:
Q: How to create pagination with PDO PHP how to create pagination using mysql pdo and php
im create code like this, but got some error msg
<?php
$halaman = 2; //batasan halaman
$page = isset($_GET['halaman'])? (int)$_GET["halaman"]:1;
$mulai = ($page>1) ? ($page * $halaman) - $halaman : 0;
$result = $db->query("SELECT * FROM kategori");
$result->execute();
$total = $result->fetchAll();
$pages = ceil(count($total/$halaman));
$query = $db->prepare("SELECT * FROM kategori LIMIT $mulai, $halaman");
    $query->execute();
    $data = $query->fetchAll();
    $no =$mulai+1;
?>
<?php foreach ($data as $value): ?>

      <?php echo $no++; ?>
      <?php echo $value['nama_kat']; ?>
<?php
  endforeach;
  ?>

A: Here is a simple approach to pagination:
<?php
$limit = 2;
$query = "SELECT count(*) FROM kategori";

$s = $db->query($query);
$total_results = $s->fetchColumn();
$total_pages = ceil($total_results/$limit);

if (!isset($_GET['page'])) {
    $page = 1;
} else{
    $page = $_GET['page'];
}

$starting_limit = ($page-1)*$limit;
$show  = "SELECT * FROM kategori ORDER BY id DESC LIMIT ?,?";

$r = $db->prepare($show);
$r->execute([$starting_limit, $limit]);

while($res = $r->fetch(PDO::FETCH_ASSOC)):
?>

<?php echo $res['id'];?>

<?php echo $res['nama_kat'];?>

<?php
endwhile;

for ($page=1; $page <= $total_pages ; $page++):?>

<a href='<?php echo "?page=$page"; ?>' class="links"><?php  echo $page; ?>

<?php endfor; ?>


text:
Q: Jasypt spring boot starter not working with bootstrap.propetites I have added jasypt spring boot starter 1.18 version in pom as my spring boot version is 1.5.16. I am trying to encrypt bootstrap.properties which is used to access spring cloud config server URL, username and password. The password is in jasypt encrypted format however while connecting to the spring cloud config server it's not sending decrypted value. Does anyone know how to encrypt the value of bootstrap.propetites using Jasypt? I tried all the available options.

A: It was a problem of jasypt.encryptor.* properties. In latest version which is 3.0.2 as of now jasypt.encryptor.iv-generator-classname is supported however in 1.18 it is not supported (Jasypt git 1.18). The encrypted password was generated with 3.0.2 version by mistake and decryption was done in 1.18 version hence It was not matching and It was unable to decrypt it. Answer is use the same version for encryption and decryption and always check the properties available in the version which is been used here .It was my bad due to working on parallel microservices which use different version of jasypt!


text:
Q: Error in App Delegate iOS 8 programming I'm getting an error in my app delegate file and I"m not sure what is causing it. The build succeeds but crash as soon as it opens and this is the message I get:
2015-01-07 10:31:20.043 Youth Xplosion[4386:672604] Could not load the "(null)" image referenced from a nib in the bundle with identifier "com.example.Youth-Xplosion"
2015-01-07 10:31:20.085 Youth Xplosion[4386:672604] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key day.'
I was messing around with my launch screen so I'm not sure if I messed up something there or somewheres else in my storyboard.
Here is my app delegate file:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

return true
}

func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    let notification: UILocalNotification = UILocalNotification()
    notification.timeZone = NSTimeZone.defaultTimeZone()

    let dateTime = NSDate()
    notification.fireDate = dateTime
    notification.alertBody = friday1

    UIApplication.sharedApplication().scheduleLocalNotification(notification)

    let notification1: UILocalNotification = UILocalNotification()
    notification.timeZone = NSTimeZone.defaultTimeZone()

    let dateTime1 = NSDate()
    notification1.fireDate = dateTime
    notification1.alertBody = saturday1

    UIApplication.sharedApplication().scheduleLocalNotification(notification1)
    */

}

func applicationWillEnterForeground(application: UIApplication) {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//Notification Messages
let friday1 = "First Service of YX 2015 begins in 1 hour!"
let friday2 = "First Service in 10 minutes!"

let saturday1 = "WAKE UP DEVOTIONS START IN 1 HOUR"

}


text:
Q: Integrate $\frac{f(x)}{x^{n+1}}$ on $S_{\epsilon}^{+}$
Let $f(z)$ be a holomorphic complex function that has $0$ as a root with multiplicity $n$
Denote by $S_{\epsilon}^{+}=\{x+yi| x,y \geq 0 , \sqrt{x^2+y^2} = \epsilon\}$.
What is $\lim\limits_{\epsilon \to 0} \int\limits_{S_{\epsilon}^+} \frac{f(z)}{z^{n+1}} dx$ where we integrate clockwise?

Could someone give me a hint? (Using $\min$ and $\max$ considaration I was able to prove that the absolute value of the limit equals to the absolute value of $2Res_f(0)$ , in the particular case I had to deal with, $f(z) = \cos(az)-\cos(bz)$ where $a,b>0$ are integers).


text:
Q: iOS Parse Inner Json Hi I have the following json that i need to parse, however, I'm struggling to parse the inner array. What I have currently just prints each of the inner arrays but I'd like to print say each title and add the titles to an array. Thank you for any help!
JSON
{"nodes":[{
    "node":{
        "nid":"1420857",
        "title":"Title 1",
        "votes":"182",
        "popular":"True",
        "teaser":"Teaser 1"
    }},
    {"node":{
        "nid":"1186152",
        "title":"Title 2",
        "votes":"140",
        "popular":"True",
        "teaser":"Teaser 2"
    }},
    {"node":{
        "nid":"299856",
        "title":"Title 3",
        "votes":"136",
        "popular":"True",
        "teaser":"Teaser 3"
    }}
]}

Json Parser
    NSError *error = nil;
    NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.somefilename.json"]];
    if (jsonData) {
        id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        if (error) {
            NSLog(@"error is %@", [error localizedDescription]);
            return;
        }
        NSArray *keys = [jsonObjects allKeys];
        for (NSString *key in keys) {
            NSLog(@"%@", [jsonObjects objectForKey:key]);
        }
    } else {
        // Handle Error
    }

A: Just typecast it:
NSArray *nodes = (NSArray*)[jsonObjects objectForKey:@"nodes"];
for (NSDictionary *node in nodes){
     // do stuff...
}

Methods that return id (like -[objectForKey:], and -[objectAtIndex:]) can return any objective-c object. You'll need to know ahead of time what to typecast it into to perform the appropriate operations on it. JSON is converted to the NSObject equivalents:

*

*object -> NSDictionary

*array -> NSArray

*string -> NSString

*number -> NSNumber

*boolean -> NSNumber

*float -> NSNumber

*null -> NSNull
To differentiate between the various NSNumbers, you'll have to call the appropriate type method: -[intValue], -[boolValue], -[floatValue]. Check out the NSNumber docs for more info.

A: You can use my method for json parsing,
Parse Method:
    -(void)jsonDeserialize:(NSString *)key fromDict:(id)content completionHandler:(void (^) (id parsedData, NSDictionary *fromDict))completionHandler{
    if (key==nil && content ==nil) {
        completionHandler(nil,nil);
    }
    if ([content isKindOfClass:[NSArray class]]) {
        for (NSDictionary *obj in content) {
          [self jsonDeserialize:key fromDict:obj completionHandler:completionHandler];
        }
    }
    if ([content isKindOfClass:[NSDictionary class]]) {
        id result = [content objectForKey:key];
        if ([result isKindOfClass:[NSNull class]] || result == nil) {
            NSDictionary *temp = (NSDictionary *)content;
            NSArray *keys = [temp allKeys];
            for (NSString *ikey in keys) {
             [self jsonDeserialize:key fromDict:[content objectForKey:ikey] completionHandler:completionHandler];
            }
        }else{
            completionHandler(result,content);
        }
    }
}

Method Call:
 NSData *content = [NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"Sample" ofType:@"json"]];
    NSError *error;

//to get serialized json data...

   id dictionary = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:&error];

//get data for key called GetInfo

     [self jsonDeserialize:@"GetInfo" fromDict:dictionary completionHandler:^(id parsedData, NSDictionary *fromDict) {
            NSLog(@"%@ - %@",parsedData,fromDict);
        }];


text:
Q: Pandas - df.loc assigning NaN when used to replace columns based on a different df I'm trying to assign values of some columns based on another column mapping them by one single key. The problem is that I don't think the mapping is being used correctly, because it is assigning NaN to the columns.
I should be mapping them by 'SampleID'.
Here is the DF I want to assign values to
>>> df.ix[new_df['SampleID'].isin(pooled['SampleID']), cols]
        Volume_Received  Quantity  massug
88280               2.0      15.0     1.0
88282               3.0      55.0     5.0
88284               2.5      46.2     3.0
88286               2.0      98.0     5.0
229365              2.0       8.4     3.0
229366              3.0      15.9     3.0
229367              1.5       7.7     2.0
233666              1.5      50.8     3.0
233667              4.0      60.2     5.0

This is the new value I have for them
>>> numerical
           Volume_Received  Quantity  massug
SampleID
sample8             10.0      75.0     5.0
sample70            15.0     275.0    25.0
sample72            12.5     231.0    15.0
sample89             6.0     294.0    15.0
sample90             4.0      16.8     6.0
sample96             6.0      31.8     6.0
sample97             3.0      15.4     4.0
sample99             3.0     101.6     6.0
sample100            8.0     120.4    10.0

I'm using this command to assign the values:
df.ix[df['SampleID'].isin(pooled['SampleID']), cols] = numerical[cols]

Where pooled is basically pooled = df[df['type'] == 'Pooled'] and cols is a list with the three columns shown above. After I run the code above I receive NaN in all the values. I think I'm telling pandas to get values where it does not exist because of the mapping and it's returning something null which is being converted to NaN (assumption).

A: index does not match,
you can use
df.ix[df['SampleID'].isin(pooled['SampleID']), cols] = numerical[cols].values

only if the size are exactly the same!


text:
Q: MPI_Gather Error Buffer overflow - changing size of buffer I've stuck at one point during testing my parallel program. Whenever I create 'pS' arrays, my program crashes on MPI_Gather() function with error "MPIDI_CH3_Receive_data_found(129) ... 4998 bytes recived but buffer size 4996". The values are exemplary however first number is always higher than second. I suppose that MPI_Bcast causes this error, but I have no idea how to resolve it. Additionally, program works purely correctly when the 'pS' arrays have the same size on each process.
EDIT.
After removing MPI_Bcast the problem still exist.
EDIT.
When I defined constant recvcount greater than the greatest sendcnt size it works properly but idk why my primary conception doesn't work.
int main(int argc, char *argv[]){

    MPI_Init (&argc, &argv);

    //Start the timer
    MPI_Barrier(MPI_COMM_WORLD);

    int myRank = 0;
    int numProcs = 1;
    MPI_Comm_rank (MPI_COMM_WORLD, &myRank);
    MPI_Comm_size (MPI_COMM_WORLD, &numProcs);

    int size_s = atoi(argv[1]);
    bool *S;
    if(myRank == 0){
        S = new bool[size_s+1];
    }

    unsigned long lowValue = BlockLow (myRank, numProcs, maxNumber);

    unsigned long highValue = BlockHigh (myRank, numProcs, maxNumber);

    ...

    unsigned long size = (highValue - lowValue)/2 + 1;

    ...

    bool *pS = new bool[size];

    ...

    while(...){
        ...
        MPI_Bcast(&var, 1, MPI_INT, 0, MPI_COMM_WORLD);
    }

    //here I've been getting pS array with diffrent size because I create in processes 'pS' arrays with diffrent sizes
    MPI_Gather(pS, size, MPI_C_BOOL, S, size, MPI_C_BOOL, 0, MPI_COMM_WORLD);
    MPI_Finalize();
    return 0;
}

unsigned long BlockLow(unsigned int procId, unsigned int numProcs, unsigned long maxNumber){
    unsigned long low = ((maxNumber-1) / numProcs)*procId + 3;
    if((low & 1) == 0) low--;
    return low;
}

unsigned long BlockHigh(unsigned int procId, unsigned int numProcs, unsigned long maxNumber){
    return((BlockLow(procId+1,numProcs,maxNumber)) - 2);
}


text:
Q: Would a Displayport-Thunderbolt cable unlock better performance from my external display than an HDMI 2.0 cable? I just bought a new monitor (an Asus XG35VQ), but when I try to use my MacBook (Pro 13", mid-2014) with it, I can only get 30Hz on the native 3440x1440 resolution.
At first I thought there was something wrong either with the monitor or with macOS (running Big Sur), but then I realized the issue is probably with the connection.
I want to avoid using the DisplayPort on the monitor to connect to the Mac because there is only one of them in the monitor and it's being used to connect to a different machine. All I have left is an HDMI 2.0 port. I'm using the cable that was supplied with the monitor.
Would it help me get a better refresh rate if I used a Thunderbolt->HDMI cable instead of an HDMI->HDMI cable? Or would it not make any difference?
And what about a Thunderbolt->DisplayPort? Or a HDMI->DisplayPort?
My monitor supports up to 100Hz, but if I can get it to 60Hz I'll be super happy already.
Thanks!

A: For this connection you could have four bottlenecks:

*

*Input connector on your monitor

*Output connector on your Mac/PC

*faulty cable/lower-spec cable

*GPU (graphics processing unit) limitation

*

*As you state, the input connector on your monitor is an HDMI 2.0
port, which is capable of 4k@60fps.

*A mid 2014 13" MBP does only support 3840x2160@30fps output over the HDMI port. This may be at least one of the reasons you are not getting the higher refresh rate.

*You can simply test the cable with another device. I also would not really suspect it, unless you have a reason to believe it is physically damaged.

*The MBP specs also state that the output is too limited for your high refresh rate monitor. There has also been a similar question on AD:

Simultaneously supports full native resolution on the built-in display and up to 2560 by 1600 pixels on up to two external displays, both at millions of colors

What this means for you
You will not be able to get a higher refresh rate, since you are using an older HDMI port and the MBPs video output is too limited. So even if you would get a Mini-DP → HDMI 2.x cable, you shouldn't  be able to get a higher refresh rate.

Note: On your machine the Thunderbolt 2 connector can act as a Mini-DP connector, which is capable of higher resolution/refresh rates than some older HDMI ports. Yet, this depends on the exact comparison. Have a look at the Wikipedia page about the different HDMI specifications and Display Port connections.
Double check which MacBooks support what monitor resolutions and refresh rates on Everymac.

A: You are unlikely to see a difference in quality on the screen, but DP does over higher data throughput than HDMI 2.0 and on my mini I eliminated a problems of my HMDI connected screen not coming back after idle (some of the time) by replacing the cable with a DP -> USB-C.
As long as HDMI is involved, you are limited to the behavior and limits of the HDMI port.

A: Thunderbolt to display port could offer a better performance in refresh rate like you said, however I would believe it to be quite minimal. I recently switched from HDMI to thunderbolt for my monitor and I don't notice a difference.


text:
Q: where do shader "static" variables reside in memory? I want to write a simple hlsl shader that renders a 2D textured quad onto a render target.
For this purpose, I wrote the following vertex shader:
struct VertexData
{
    float2 position;
    float2 uv;
};

// 2 2D triangles that cover the whole render target
static VertexData vertices[6] =
{
    {float2(-1.0, 1.0), float2(0.0, 0.0)},
    {float2(-1.0, -1.0), float2(0.0, 1.0)},
    {float2(1.0, 1.0), float2(0.0, 1.0)},
    {float2(1.0, 1.0), float2(0.0, 1.0)},
    {float2(-1.0, -1.0), float2(0.0, 1.0)},
    {float2(1.0, -1.0), float2(1.0, 1.0)}
};

struct VSOutput
{
    float4 position : SV_POSITION; // position in normalized device coordinates
    [[vk::location(0)]] float2 uv : TEXCOORD0;
};

VSOutput main(uint vertexIndex : SV_VertexID)
{
    VSOutput output = (VSOutput)0;
    output.position = float4(vertices[vertexIndex].position, 0.0, 1.0);
    output.uv = vertices[vertexIndex].uv;
    return output;
}

I am trying to understand whether this is the 'best' or 'simplest' approach.
Specifically:

*

*Where does the memory for the vertices array reside? constant memory? global memory? is it cached? is it read only?

*Is this the optimal approach? asking ChatGPT, it claims I should use a constant buffer. but AFAIK constant buffers are optimized for uniform access across the shader. Which is not the case here.

A:
Where does the memory for the vertices array reside?

That is implementation-dependent. It lives where it needs to live to serve the requirements imposed by being declared as static.

is it read only?

You did not declare it const, so as far as the language is concerned, the array can be written to. The compiler can see that you never actually write to it, so it could do something with that information. But it doesn't have to.

Is this the optimal approach?

"Optimal" in terms of what? Declaring the array const will give the compiler more information to do what it needs to with the array. But outside of that, there's really nothing more that you can do.


text:
Q: How to show a popup or dialog on click of menu tab of salesforce? I am new to salesforce and there is a requirement to show a popup or dialog box (vf page) on click of menu tabs.
Please guide me if this can be done.

A: If you are using JQuery on visual force page then you can use JQuery Dialog to have pop up.
Please refer this link.


text:
Q: Add cumulative sum column to attribute table I have an attribute table in QGIS in which I would like to calculate the cumulative sum. The table is sorted by N (number of fatalities) and I would like to calculate the cumulative sum on F (frequency of accident), i.e. F_cumulative should be a sum of the current row and the rows above. How should I do this? Can I use a formula in the field calculator?

A: It can be done with an expression. Bear in mind this only works if the original table is already ordered with N descending as feature IDs increase. Since the result field is empty, we need to get past NULL values ruining the calculation. We'll use a conditional statement to fill the first line with a different value than the rest, so subsequent calculations can be based a numerical value. In the field calculator, write this expression (modifying the relevant layer/field names):
if($id = 1, attribute($currentfeature, 'your_frequency_field'), attribute($currentfeature, 'your_frequency_field') + attribute(get_feature_by_id('your_layer', $id-1), 'your_cumulative_field'))
This will calculate a cumulative sum in order of feature IDs by fetching the frequency field attribute value of the currently evaluated feature and adding the cumulative frequency field attribute value of the previous feature (with the exception of feature ID = 1 which will fetch its own value: 0).
With a quick mockup of your data, this was my result summing on F and F_cum:


text:
Q: Can`t get value of member of derived class I have:
VirtualClass : public QObject
{
public:
    int m_number;
}

DerivedClass : public VirtualClass
{
public:
    DerivedClass(int number) : m_number(number) {};
    int m_number;
    // some content goes here..
}

client code:
f(VirtualClass* instance)
{
std::cout << instance->m_number;
}

DerivedClass der(100);

I want f(der) to return m_number that relates to DerivedClass , but *I get m_number of VirtualClass*.
What I am doing wrong?!!

A: Remove int m_number; from the DerivedClass. Otherwise you have to different m_number members. One is from VirtualClass and other is from DerivedClass.
When you add int m_number; in the DerivedClass you hide m_number; of VirtualClass
Here is an example how it works:
struct Foo
{
    int a;
};

struct Bar : Foo
{
    int a; //another a
};

int main()
{
    Bar *f = new Bar();
    f->a = 10; //Bar::a

    Foo *b = f;
    b->a = 20; //Foo::a

    cout << f->a << endl; //prints 10
    cout << b->a << endl; //prints 20
}

A: You have declared int m_number; twice. You should only declare it once.

A: spin_eight:
You can keep your initializer list, if you want to by providing an appropriate constructor on the VirtualClass, and calling it from the derived initializer list, like so:
VirtualClass : public QObject
{
 public:
 VirtualClass(int number) : m_number(number) { }
 int m_number;
}

DerivedClass : public VirtualClass
{
 public:
 DerivedClass(int number) : VirtualClass(number) {};
 // some content goes here..
}


text:
Q: Backup directory with all Files and Folders I'm trying to copy one directory to another path and rename it...
I have a location like: C:\Backups
I have multiple locations such as (in a textbox):
C:\Users\xy\AppData\Local\....
C:\ProgramData\Test
C:\Tests\Test

I want now store all directory with all Files and Folders to the Backup Path..
Output Folder must looks like ->
C:\Backups\05.07.2018_17;00_FullFolderName

I Have this, but this isnt ideal...
    this.CopyAll(new DirectoryInfo(@"C:\Test"), new DirectoryInfo(@"C:\Backups"));

    private void CopyAll(DirectoryInfo oOriginal, DirectoryInfo oFinal)
    {
        foreach (DirectoryInfo oFolder in oOriginal.GetDirectories())
            this.CopyAll(oFolder, oFinal.CreateSubdirectory(oFolder.Name));

        foreach (FileInfo oFile in oOriginal.GetFiles())
            oFile.CopyTo(oFinal.FullName + @"\" + oFile.Name, true);
    }

A: I had this for myself, hope helps:
void Main()
{
    string baseFolder = @"c:\Backups";
    string source = @"C:\Tests\Test";
    string target = Path.Combine(baseFolder, DateTime.Now.ToString("yyyyMMddHHmmss"));
    if (!Directory.Exists(baseFolder))
    {
        Directory.CreateDirectory( baseFolder );
    }
    CopyFolder( source, target );
}

private void CopyFolder(string source, string destinationBase)
{
    CopyFolder( new DirectoryInfo( source ), destinationBase );
    foreach (DirectoryInfo di in new DirectoryInfo(source).GetDirectories("*.*", SearchOption.AllDirectories))
    {
      CopyFolder( di, destinationBase );
    }
}

private void CopyFolder( DirectoryInfo di, string destinationBase )
{
   string destinationFolderName = Path.Combine( destinationBase, di.FullName.Replace(":",""));
   if ( !Directory.Exists( destinationFolderName ) )
   {
      Directory.CreateDirectory( destinationFolderName );
   }
   foreach (FileInfo fi in di.GetFiles())
   {
      fi.CopyTo( Path.Combine(destinationFolderName, fi.Name), false);
   }
}


text:
Q: How can the root file system be accessed to launch cryptsetup to allow access to the root file system? I have got laptop with full disk encryption. There is a /boot partion which is not encrypted and the other partition /dev/sda5 is.
In order to decrypt, it asks me for the passphrase which is then passed to the command
/sbin/cryptsetup luksOpen ${name} ${device}.
How can it decrypt the partition if the command /sbin/cryptsetup is on the encrypted partition, which is not accessible. I thought maybe there is copy of the command in the /boot partition, but I have not found any.
Can somebody shed some light on this?

A: Many Linux distributions use an in-memory filesystem as a temporary root filesystem when booting. There are two forms of such in-memory filesystems: initrd, the traditional form, which is a RAM drive, and initramfs, the modern form, which is a filesystem filled by data from an archive.
The job of the programs on the initrd (or initramfs, the difference is irrelevant here) is to do everything that is necessary to mount the root filesystem. This includes loading modules for the relevant drivers (for the hard disk, for the root filesystem type, and for any other data layer such as RAID and volume encryption). This also includes making the root volume ready for use. Prompting the user for the encryption password is one of these tasks.
The initrd is loaded by the bootloader (Grub, Lilo, …) at the same time as the kernel. It is generally stored in the same directory as the kernel, in /boot.
Most distributions arrange to regenerate the initrd whenever the kernel is upgraded. You may also need to regenerate the initrd in other circumstances such as a change in the location of the root filesystem or of the type of volume. If the root filesystem is encrypted, the distribution will make sure that the initrd contains cryptsetup and crypttab (these are copies from the root filesystem made when the initrd is generated).