text:
Q: Performance of MDX Qyery working fine for one year, how can we run same query for two year Performance of  MDX Qyery working fine for one year, how can we run same query for two year
WITH

MEMBER [Measures].[Metric] AS Round(sum(({[Year].[Year].&[2015]}),[Measures].[PurchaseSum]),2)
SET CustYear as exists([DIMCustomer].[Level 02].allmembers,({[Year].[Year].&[2015]}),"sales")
  SET [BusinessSet] AS { filter((
              EXISTS(CustYear, [DIMCustomer].[HierarchyCategory].&[UnitHierarchy],"sales")
     ),([Measures].[Metric] or [Measures].[Metric]=0) )}

  SET [SellerFilterCustomerID] AS EXISTS([DIMSeller].[CustId].ALLMEMBERS,{[DIMSeller].[CustId].[All]}, "sales")
  SET [SellerFilterCustomerType] AS  EXISTS([DIMSeller].[CustId].ALLMEMBERS,[DIMSeller].[CustomerType].[All])
  SET [SellerFilterCompanyName] AS EXISTS([DIMSeller].[CustId].ALLMEMBERS,{[DIMSeller].[Name].[All]},  "sales")
  SET [SellerFilterCompanyLoc] AS EXISTS([DIMSeller].[CustId].ALLMEMBERS,[DIMSeller].[Organization].[All])
  SET [FinalSellerFilter] as (intersect(intersect(intersect([SellerFilterCustomerID],[SellerFilterCustomerType]),[SellerFilterCompanyName]),[SellerFilterCompanyLoc]))
  SET Name     AS  {[DIMCustomer].[Name].[All]}
  SET Code    AS  {[DIMCustomer].[Code].[All]}
  SET CustType    AS  {[DIMCustomer].[CustomerType].[All]}
  SET OrgLoc      AS  {[DIMCustomer].[Organization].[All]}
  SET CustFilters AS (Name,Code,CustType,OrgLoc)
  SET ICP as {{[DimProduct].[ICP].[All]}}
  SET ProdICP as (ICP)

  //creating year filter
  SET CrYear as  {[Year].[Year].&[2015]}

  SET Others AS (CrYear,ProdICP)
  SET [SalesSet] AS exists([BusinessSet],[FinalSellerFilter],"sales")
  //creating final set
  SET FINALSET as exists([SalesSet],CustFilters,"sales" )
  SET Geo as exists([DIMCustomer].[ParentPostalNumber].[ParentPostalNumber],({[Year].[Year].&[2015]}),"sales")
  SET [FIPS] AS  Except(EXISTS(Geo,[SalesSet], "sales"),{[DIMCustomer].[ParentPostalNumber].&[0],[DIMCustomer].[ParentPostalNumber].&[]})

  MEMBER [Measures].[Sales] AS round(sum(([FINALSET],Others),[Measures].[Metric]),2)

  MEMBER [Measures].[Count] as  (exists(([FINALSET],Others,[SalesType].[SalesType].&[3]),[DIMCustomer].[ParentPostalNumber].currentmember, "sales")).count
SELECT
non empty  {
 [Measures].[Sales],[Measures].[Count]
  } ON 0,
  NON EMPTY{
    FIPS
  } ON 1
FROM [cube]**

A: To run it for 2 years just swap all instances of this:
{[Year].[Year].&[2015]}

for this...
{[Year].[Year].&[2014], [Year].[Year].&[2015]}

Partitioning in your warehouse is most likely to be the cause - the Exists function refers back to the fact tables. Although maybe you can avoid using Exists in this sort of context and find an alternative:
EXISTS([DIMSeller].[CustId].ALLMEMBERS,{[DIMSeller].[CustId].[All]}, "sales")

Sourav has noticed that you might be using EXISTS instead of NonEmpty - if you can use the later function as it is more efficient.


text:
Q: Hiding closed proposals on Area51 I would like to see a view on Area51 that hides all [closed] proposals - right now, they're cluttering-up many pages, and I'd like to be able to see the live proposals without the clutter.
As of 1138EDT on 18-May-2011:
I see 29 on the front page of All looking at "newest" (set to view 50/page).
Subtotals:

*

*Arts: 8

*Business: 2

*Culture: 5

*Life: 13

*Professional: 1

*Recreation: 13

*Science: 2

*Technology : 39

Total [closed] currently:

*

*84

Total proposals:

*

*508

[Closed] as a percentage:

*

*16.5%

That's some serious clutter, imho :)

A: "Proposals" are a lot like "questions" in Stack Exchange (hint — they're derived from the same code base). I think it would become very confusing if we started changing the expected behaviors between the two systems.
Area 51 is supposed to work as much like a Stack Exchange Q&A as possible. "Hiding" a closed proposal would be much like hiding a closed question. We've all become accustomed to the behavior that a "closed" question is not deleted. It can be re-opened by voting. Same goes for a closed proposal.
And much like a closed question in Stack Exchange, if you feel that a proposal does not belong on the site, you should vote to deleted it (with the appropriate reputation requirements, of course). Closed proposals will be deleted automatically if they receive no further activity for a month, anyway.
I would rather NOT see the behavior of Area 51 drift too far away from the core functionality of Stack Exchange. Then you would just have two sets of behaviors to learn.

redpajama_set_name: RedPajamaStackExchange


text:
Q: flutter can't fetch data from api , dio error So I'm working on a NewsApp and I could successfully manage to fetch data and display it, however the search function wasn't working!
yesterday it just stuck with that error! I've every solution that I came across SOF and git but ended with failure.
I provide images of every related code below. please, help

*

*base URL: https://newsapi.org/

*method  : v2/top-headlines?

*queries : country=us&category=business&apiKey=65f7f556ec76449fa7dc7c0069f040ca

for search purpose:
https://newsapi.org/v2/everything?q=tesla&apiKey=65f7f556ec76449fa7dc7c0069f040ca

DioError [DioErrorType.other]: SocketException: Failed host lookup:
'newsapi.orgv2' (OS Error: No address associated with hostname, errno
= 7)

Here's the error
dio code
cubit code
main class
dio code
class DioHelper {
  static late Dio dio;

  static init() {
    dio = Dio(
      BaseOptions(
        baseUrl: 'https://newsapi.org',
        receiveDataWhenStatusError: true,
      ),
    );
  }

  static Future<Response> getData({
    required String url,
    required Map<String, dynamic> query,
  }) async {
    return await dio.get(
      url,
      queryParameters: query,
    );
  }
}

Cubit code
class NewsCubit extends Cubit<NewsStates> {
  NewsCubit() : super(NewsInitialStates());

  static NewsCubit get(context) => BlocProvider.of(context);

  int currentindex = 0;
  List<BottomNavigationBarItem> bottomItems = [
    const BottomNavigationBarItem(
        icon: Icon(Icons.add_business_outlined), label: 'Business'),
    const BottomNavigationBarItem(
        icon: Icon(Icons.sports_football_outlined), label: 'Sports'),
    const BottomNavigationBarItem(
        icon: Icon(Icons.science_outlined), label: 'Science'),
  ];

  List<Widget> screens = [
    const BusinessScreen(),
    const SportsScreen(),
    ScienceScreen(),
  ];

  void changeBottomNavBar(int index) {
    currentindex = index;
    if (index == 1) getSports();
    if (index == 2) getScience();
    emit(NewsBottomNavState());
  }

  List<dynamic> business = [];

  void getBusiness() {
    emit(NewsGetBusinessLoadingState());
    DioHelper.getData(
      url: '/v2/top-headlines',
      query: {
        'country': 'eg',
        'category': 'business',
        'apiKey': '65f7f556ec76449fa7dc7c0069f040ca',
      },
    ).then((value) {
      // print(value.data['articles'][0]['title']);
      business = value.data['articles'];
      print(business[0]['title']);
      emit(NewsGetBusinessSuccessState());
    }).catchError((e) {
      print(e.toString());
      emit(NewsGetBusinessErrorState(e.toString()));
    });
  }

  List<dynamic> sports = [];

  void getSports() {//sports code just like business
  }

  List<dynamic> science = [];

  void getScience() {//science code just like business
  }

  List<dynamic> search = [];

  void getSearch(String value) {
    emit(NewsGetSearchLoadingState());
    search = [];
    DioHelper.getData(
      url: '/v2/everything',
      query: {
        'q': '$value',
        'apiKey': '65f7f556ec76449fa7dc7c0069f040ca',
      },
    ).then((value) {
      // print(value.data['articles'][0]['title']);
      search = value.data['articles'];
      print(search[0]['title']);
      emit(NewsGetSearchSuccessState());
    }).catchError((e) {
      print(e.toString());
      emit(NewsGetSearchErrorState(e.toString()));
    });
  }
}

Main class
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  Bloc.observer = MyBlocObserver();
  HttpOverrides.global = MyHttpOverrides();
  DioHelper.init();
  await CacheHelper.init();

  bool? isDark = CacheHelper.getBoolean(key: 'isDark');

  runApp(MyApp(isDark));
}

class MyApp extends StatelessWidget {
  bool? isDark;
  MyApp(this.isDark);
  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (context) => NewsCubit()
            ..getBusiness()
            ..getSports()
            ..getScience(),
        ),
        BlocProvider(
          create: (context) => AppCubit()
            ..ChangeAppMode(
              fromShared: isDark,
            ),
        )
      ],
      child: BlocConsumer<AppCubit, AppState>(
        listener: (context, state) {},
        builder: (context, state) {
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
              primarySwatch: Colors.deepOrange,
              scaffoldBackgroundColor: Colors.white,
              floatingActionButtonTheme: const FloatingActionButtonThemeData(
                backgroundColor: Colors.deepOrangeAccent,
              ),
              appBarTheme: const AppBarTheme(
                titleSpacing: 20,
                iconTheme: IconThemeData(
                  color: Colors.black,
                ),
                // backwardsCompatibility: false,
                systemOverlayStyle: SystemUiOverlayStyle(
                  statusBarColor: Colors.white,
                  statusBarIconBrightness: Brightness.dark,
                ),
                backgroundColor: Colors.white,
                elevation: 0.0,
                titleTextStyle: TextStyle(
                  color: Colors.black,
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
              bottomNavigationBarTheme: const BottomNavigationBarThemeData(
                type: BottomNavigationBarType.fixed,
                selectedItemColor: Colors.deepOrangeAccent,
                unselectedItemColor: Colors.grey,
                elevation: 50,
                backgroundColor: Colors.white,
              ),
              textTheme: const TextTheme(
                bodyText1: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
              ),
            ),
            darkTheme: ThemeData(
              scaffoldBackgroundColor: HexColor('333739'),
              primarySwatch: Colors.deepOrange,
              backgroundColor: Colors.white,
              floatingActionButtonTheme: const FloatingActionButtonThemeData(
                backgroundColor: Colors.deepOrangeAccent,
              ),
              appBarTheme: AppBarTheme(
                titleSpacing: 20,
                iconTheme: const IconThemeData(
                  color: Colors.white,
                ),
                // backwardsCompatibility: false,
                systemOverlayStyle: SystemUiOverlayStyle(
                  statusBarColor: HexColor('333739'),
                  statusBarIconBrightness: Brightness.light,
                ),
                backgroundColor: HexColor('333739'),
                elevation: 0.0,
                titleTextStyle: const TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
              bottomNavigationBarTheme: BottomNavigationBarThemeData(
                type: BottomNavigationBarType.fixed,
                selectedItemColor: Colors.deepOrangeAccent,
                unselectedItemColor: Colors.grey,
                elevation: 50,
                backgroundColor: HexColor('333739'),
              ),
              textTheme: const TextTheme(
                bodyText1: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
            themeMode:
                AppCubit.get(context).isDark ? ThemeMode.dark : ThemeMode.light,
            home: Directionality(
              child: NewsLayout(),
              textDirection: TextDirection.ltr,
            ),
          );
        },
      ),
    );
  }
}

class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)
      ..badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
  }
}

A: try to put / after org in your baseUrl

A: i figure it out> just added connectTimeout, receiveTimeout in my Dio(baseoptions) and it worked for me!
class DioHelper {
  static late Dio dio;
  static init() {
    BaseOptions options = BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: 20 * 1000,
      receiveTimeout: 20 * 1000,
      receiveDataWhenStatusError: true,
    );
    dio = Dio(options);
  }

  static Future<List<dynamic>> getData(
      {required Map<String, dynamic> query}) async {
    try {
      Response response =
          await dio.get('v2/top-headlines', queryParameters: query);
      return response.data['articles'];
    } catch (e) {
      print(e.toString());
      return [];
    }
  }
}


text:
Q: How to change to directory when I click on link in PHP? I want to run the hello.php from input/index.php to input/output/hello.php when the link on index.php was clicked. I have googled it but cannot find the solution? Any solution for this?

A: Just put a / in the URL.
<a href="output/hello.php">

A: Sometimes, i have a problem when just using (with your example) "output/hello.php" so i use "./output/hello.php", maybe it could work for you.

A: What you are asking I think is more about URLs, you have to create a file called:
.htaccess

Just like that, with the dot at the beginning. You can use this code inside of it:
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^.*$ ./index.php?u=$1

Now, all the requests are going to go to the index.php file, ALL!! no matter if you write /lalala, is still going to go to index.php, so you have to parse the URL, that way, you can know what are you receiving and be able to execute any method that you want.
Example:
$url = 'http://' . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
$parsedUrl = parse_url($url);
$parsedUrl['path'] // Is the var that has the info after yourdomain.com/

Once you have that, you can separate that with explode('/', $parsedUrl['path']) and analize the data.
So you can write /input/output/hello.php and you can receive the data in index.php


text:
Q: Minecraft launcher Won't Work On ubuntu 20.04 lts I have Minecraft 1.15.2 java edition
When I press The Play Button, Then a Window Opens saying:
GLFW error 65543: GLX: Failed to create context: GLXBadFBConfig

Please make sure you have up-to-date drivers (see aka.ms/mcdriver for instructions).

I Dont Know Why That But I Now You can Help Me
And Thank You

A: On terminal, run :-
export MESA_GL_VERSION_OVERRIDE=4.5

...and then run Minecraft. Should solve it.


text:
Q: How to forward request to Node.js from nginx with tcp_proxy_module? Now, I had patched nginx with the nginx_tcp_proxy_module, and it is running OK on port 8080.
How do I connect the clients to port 80 of nignx, not port 8080 of Node.js,
so that having the nginx forward the request to Node.js?

A: Just change 8080 to 80. But TCP and HTTP on the same port is not possible.
Aleternative solution:

*

*Use HAProxy on port 80

*Set up nginx to listen on port 81

*Run your node.js app on port 8080

*Configure HAProxy to

*

*forward Host: your.nodejs.socketio.com to 127.0.0.1:8080

*forward everything else to 127.0.0.1:81

If you go down this route you will probably want to preserve client IPs:

*

*Configure HAproxy

*Use RealIP module in nginx

*Use X-Forwarded-For in socket.io
socketio.handshakeData = function(data) {
    var d = socketio.Manager.prototype.handshakeData(data);
    d.ip = data.request.headers['x-forwarded-for'] || data.request.connection.remoteAddress;
    return d;
};


text:
Q: iframe [src]="videoUrl | sanitize" - when page reloading causes 404 iframe of my website I'm trying to load a videoUrl from a database and assigning it to the iframe [attr.src] to show a youtube video.  The data has to come from a database, there's no other way around that for me besides uploading the video and displaying that, which we can't do at the moment.
The problem is that it is constantly refreshing every couple of seconds making the video flash briefly.
Is there anyway to avoid this?
This is the code I have referring to the iframe and method that returns the url.
<iframe
  class="courseVideo row col-md-12 col-sm-12 col-xs-12 text-center"
  height="300"
  id="introVideoUrl"
  [src]="getIntroVideoUrl(section.introVideoUrl)"
  frameborder="0" allow="autoplay; encrypted-media"
  allowfullscreen
  style="margin-top: 15px;">
</iframe>

getIntroVideoUrl(url) {
  return this.sanitizer.bypassSecurityTrustResourceUrl(
    "https://www.youtube.com/embed/" + url
  );
}

-- EDIT AFTER @JeremyW's SUGGESTION --
OK, so I managed to get what @JeremyW was mentioning below.  As such, it no longer constantly refreshes.  I had to make some adjustments and instead of doing it that way, I just made a custom 'Sanitizer' pipe.
But I did recreate it the way he was mentioning and the result is the same as the pipe, the pipe was just a way I can constantly re-use it and not have to worry about rewriting that every time.
I am however now coming across and issue where if I refresh the page, sometimes a Iframed version of my website leading to page 404 is shown instead of the youtube video.
Any reason why this happens or can someone point me to a source that explains it? I could't find a reason for it.
Thanks!

A: I suspect that it's due to the way Angular's property bindings work. I wasn't able to easily find a source to verify my suspicion, but I think that each time Angular checks the value of the src attribute, to see if it's changed, it will re-call the function... causing it to refresh the value of the attribute - causing the restart you're seeing.
I've accomplished something similar in the past, here are a few snippets of my code to help you along. Long story short, rather than calling the function from your HTML, point the [src] attribute to a variable, and then use a function in the TS file to set the proper value of that variable:
HTML:
<iframe
  *ngIf="homeVideo"
  [src]="homeVideo"
  frameborder="0"
  gesture="media"
  allow="encrypted-media"
  allowfullscreen>
</iframe>

TS:
export class HomeComponent implements OnInit {
    // Video Url
    homeVideo;

    ngOnInit() {
        // Pull updated content from Firebase
        this.getContent();
    }

    getContent() {
        this.contentService.getPageContent('homePage').then( pageContent => {
            this.homeVideo = this.sanitizer.bypassSecurityTrustResourceUrl(pageContent.homeVideo);
        }
    }
}


text:
Q: Confidence interval for difference of means in regression Suppose I have a quadratic regression model
$$
Y = \beta_0 + \beta_1 X + \beta_2 X^2 + \epsilon
$$
with the errors $\epsilon$ satisfying the usual assumptions (independent, normal, independent of the $X$ values). Let $b_0, b_1, b_2$ be the least squares estimates.
I have two new $X$ values $x_1$ and $x_2$, and I'm interested in getting a confidence interval for $v = E(Y|X = x_2) - E(Y|X=x_1) = \beta_1 (x_2 - x_1) + \beta_2 (x_2^2 - x_1^2)$.
The point estimate is $\hat{v} = b_1 (x_2 - x_1) + b_2 (x_2^2 - x_1^2)$, and (correct me if I'm wrong) I can estimate the variance by $$\hat{s}^2 = (x_2 - x_1)^2 \text{Var}(b_1) + (x_2^2 - x_1^2)^2 \text{Var}(b_2) + 2 (x_2 - x_1)(x^2 - x_1^2)\text{Cov}(b_1, b_2)$$ using the variance and covariance estimates of the coefficients provided by the software.
I could use a normal approximation and take $\hat{v} \pm 1.96 \hat{s}$ as a 95% confidence interval for $v$, or I could use a bootstrap confidence interval, but is there a way to work out the exact distribution and use that?

A: The general result you are looking for (under the stated assumptions) looks like this:
For linear regression with $p$ predictor variables (you have two, $X$ and $X^2$) and an intercept, then with $n$ observations, $\mathbf{X}$ the $n \times (p+1)$ design matrix,  $\hat{\beta}$ the $p+1$ dimensional estimator and $a \in \mathbb{R}^{p+1}$
$$ \frac{a^T\hat{\beta} - a^T \beta}{\hat{\sigma}
  \sqrt{a^T(\mathbf{X}^T\mathbf{X})^{-1}a}} \sim t_{n-p-1}.$$
The consequence is that you can construct confidence intervals for any linear combination of the $\beta$ vector using the same $t$-distribution you use to construct a confidence interval for one of the coordinates.
In your case, $p = 2$ and $a^T = (0, x_2 - x_1, x_2^2 - x_1^2)$. The denominator in the formula above is the square root of what you compute as the estimate of the standard error (provided that this is what the software computes ...). Note that the variance estimator, $\hat{\sigma}^2$, is supposed to be the (usual) unbiased estimator, where you divide by the degrees of freedom, $n-p-1$, and not the number of observations $n$.


text:
Q: Missing assemblies that aren't described anywhere I've just reinstalled the operating system and suddenly my legacy project from early 2013's won't compile.
The warnings I'm getting are:

Found conflicts between different versions of
  "System.Windows.Interactivity" that could not be resolved.  These
  reference conflicts are listed in the build log when log verbosity is
  set to detailed.

-

Could not resolve this reference. Could not locate the assembly
  "Microsoft.VisualStudio.Shell.Connected, Version=12.0.0.0,
  Culture=neutral,
  processorArchitecture=MSIL". Check to make sure the assembly exists on
  disk. If this reference is required by your code, you may get
  compilation errors.

-

The type 'LocalReport' is defined in an assembly that is not
  referenced. You must add a reference to assembly
  'Microsoft.ReportViewer.WinForms, Version=10.0.0.0, Culture=neutral.

The last one won't let me ALT+ENTER the issue, the reference simply doesn't add.
I've tried googling all of these to get things I have to install, but surprisingly I found nothing, so I would appreciate any input.


text:
Q: Socket.IO chat example made with Node.JS is not working on Azure in "transport mode"=websocket Following issue:
I have Azure free tier and created a web app based on Node.JS 12 LTS runtime. The web app source code is the Socket.IO chat example which can be found here.
The chat example works perfectly on my local machine. -> Socket.IO uses the transport=websocket.
I deployed the same source code via Visual Studio Code to Azure. There I configured under General settings -> Web sockets: On.
On the first glance the chat example works. But when I switch to the development console in Chrome I get following message:

socket.io-1.2.0.js:2 WebSocket connection to
  'wss://*.azurewebsites.net/socket.io/?EIO=3&transport=websocket&sid=tWzTFtk3ABb3jeCWAAAE'
  failed: Error during WebSocket handshake: Unexpected response code:
  503

I found something here under WebSockets Connection Limits fits to my error message. But I testet the chat example with less than 5 clients. :-/  I also started a remote debug seassion where I inspect the Socket.IO instance and there where always less than 5 clients connected to the server.
What I want: A Socket.IO communication which is using transport=websocket and runs in Azure (under free tier).


text:
Q: Animate CC "pressmove" issues in Safari 10.0.1 Using the easeljs tutorial here I created a drag and drop "test" in Animate CC using symbols and "pressmove", "pressup". It works fine in all the browsers (and Ipad) except for Safari on my mac. When starting to move the "draggers" they "jump" to a different location. They also move closer and further from the mouse when dragging.
The test page is located here:
Any help would be greatly appreciated.  Thanks!


text:
Q: List of objects, Fastest way to sort by key (one of its members) (complexity comparison) Given a list of objects in a container that can not be modified
/* It's a map<>. sort order is based on 'name' */
struct Obj {
    // those and some other data is stored here
    string name;
    int key; // unique index
};

Need to get them ordered by the key. Which way is faster?
I can:

*

*Insert them to std::set and then iterate over to get the order.
Per the C++ standard, iteration over the elements in an std::set proceeds in sorted order as determined by std::less or by the optional comparison predicate template argument.

*Or insert them to an array, std::vector, and sort it. (expected std sort is O(n*log(n)) )

*Can you think if any other faster way? In initial container they are sorted by name, which is irrelevant to the key index values.

Number of objects can be from 100 to 10000.
I think it is faster to use method 1. Even though the analysis below (if correct) indicates they have same complexity of O(n*log(n)).
Complexity of inserting N objects to a set:
log(1)+log(2)+log(3)+....+log(n)
=log(n!)
=O(n*log(n)-n + O(log(n)))
=O(n*log(n))

A: In my experience, the best solution to your problem is something like:
vector<set<Obj>::const_iterator> vec;
vec.reserve(set_of_obj.size());
insert into vector;
sort the vector using a custom comparator.

Some explanations:

*

*Sort set::const_iterator guarantees to be faster than sort Obj. Iterator is pointer based.

*Inserting to a vector and sort the vector guarantees to be faster than inserting into a set.

*Reserve the vector size ahead of time to avoid dynamic memory reallocations.


text:
Q: MVC3 parameter use by layout I have a custom section that uses a custom layout. This section is dynamic and all the actions will receieve a YEAR parameter. I don't want setup navigation via section from inside the views. What would be the best way to get this parameter in a navigation action utilized by the layout? If the year is in the URL as ?year=2012 then I can get it via query string. My problem is that this may be in there as controller/action/2012. How can I get the year now in navigation action?

A: controller/action?year=2012 and controller/action/2012 are basically same if you have defined your route as
{controller}/{action}/{year}

In the action
public class MyController:Controller
{
    public ActionResult MyAction(int year)
    {
     :
     :
     :
    }
}

If you have defined above route along with the default route ( {controller}/{action}/{id} )
Both the url MyController/MyAction?year=2012 and MyController/MyAction/2012 will be treated equally.


text:
Q: error: class, interface, or enum expected - Android Studio error: class, interface, or enum expected - Android Studio

package com.android.wowowowo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

public class MainActivity extends AppCompatActivity {

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

        Handler h = new Handler() ;
        h.postDelayed(new Runnable() {
            public void run() {
                startActivity(new Intent(MainActivity.this, MainActivity2.class));
            }

        }, 3000);
    }
    }
}

I wanted to wait 3 seconds and change activity

A: It looks like you have one extra curly bracket. Try this instead.

package com.android.wowowowo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

public class MainActivity extends AppCompatActivity {

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

        Handler h = new Handler() ;
        h.postDelayed(new Runnable() {
            public void run() {
                startActivity(new Intent(MainActivity.this, MainActivity2.class));
            }

        }, 3000);
    }
}


text:
Q: spfx webpart Canvas size on Modern Page I've created an spfx webpart using the react-office-ui-fabric DetailsList. It works fine, but the details list is quite wide. On a modern page the framework is rendeing my webpart in a div that is set to max-width 1280ox which causes a horizontal scroll bar to appear.

It seems to do that for all webparts.
Is there a way to override the max-width on a modern page? Works fine on a classic page/

A: I have added the following styles in my module.scss file and it worked perfectly for me.
 :global {
      #workbenchPageContent, .CanvasComponent.LCS .CanvasZone {
        max-width: 100% !important;
      }

    }

A: If you increase CSS Specificity you can set your own max-width:
.Canvas.Canvas{
    max-width:initial;
}

or
.Canvas.Canvas{
    max-width:100vw;
}

See: https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/

A: you could use a script Editor for modern pages form bitalus.com in example and input:
<style>
   .Canvas{
       max-width:100% !important;
   }
</style>

this is working for me like a cham!


text:
Q: Sharepoint and its template/master pages I'm trying to learn how to customize a sharepoint site. I've seen a lot of examples and they all seem to have one thing in common, the navigation are all the same. Ie the left nav with the different pages and docs. top nav with mostly links to sub-sites or other sites.
Does anyone know of a good tutorial or example i can grab that has a horizontal layout of the left nav? i haven't found any.

A: You need to set properties on the aspmenu control in the master page. Aside from the data source it's just a standard asp.net menu.
If you need complete control, look into the css friendly control adapters - that will let you render an aspmenu (used by sharepoint for both top and left nav) as an unordered list and apply whatever css you need. If you are using SharePoint 2010 you can get the same effect with the SimpleRendering property.

A: First See here to customize the Display of Quick Launch
and here to Add fly-out menus to SharePoint navigation. For Horizonal layout, Change  Orientation="Vertical" to "Horizontal" in SharePoint:AspMenu.
See following to customize the site
http://www.idratherbewriting.com/2009/01/28/customizing-a-sharepoint-site/


text:
Q: How to read json file in java I want to read Json file. My Json File has Content as follow
[
  {
    "arguments" : [
      {
        "IsEnabled" : "false",
        "class" : "UITextField",
        "width" : 238,
        "parent" : {
          "class" : "UIView",
          "height" : 101,
          "Y" : 192,
          "width" : 280,
          "X" : 20
        },
        "name" : "Enter UserName",
        "X" : 40,
        "isRightOf" : "NA",
        "Recording Device" : "NA",
        "Y" : 0
      },
      {
        "data" : "Enter UserName",
        "type" : "string"
      }
    ],

  }
]

I also tried GSON library to read JSON file.but fails . Please help

A: The JSON you provided is invalid (there is an invalid comma)
[
  {
    "arguments" : [
      {
        "IsEnabled" : "false",
        "class" : "UITextField",
        "width" : 238,
        "parent" : {
          "class" : "UIView",
          "height" : 101,
          "Y" : 192,
          "width" : 280,
          "X" : 20
        },
        "name" : "Enter UserName",
        "X" : 40,
        "isRightOf" : "NA",
        "Recording Device" : "NA",
        "Y" : 0
      },
      {
        "data" : "Enter UserName",
        "type" : "string"
      }
    ], <-- this comma makes the json invalid

  }
]

A: Your input json was wrong there is a comma missing as suggested.
Json objects are very hard to parse but if you once get the concept of how to parse the json data it is really easy.
You need to see if the property you are trying to access is a json array or an object. This is the basic rule if you are a beginner.
Here is the code::
OUTOUT IS::
arguments>>>>>>>>> [{"parent":{"width":280,"X":20,"Y":192,"class":"UIView","height":101},"Recording Device":"NA","IsEnabled":"false","width":238,"name":"Enter UserName","X":40,"isRightOf":"NA","Y":0,"class":"UITextField"},{"data":"Enter UserName","type":"string"}]
{"parent":{"width":280,"X":20,"Y":192,"class":"UIView","height":101},"Recording Device":"NA","IsEnabled":"false","width":238,"name":"Enter UserName","X":40,"isRightOf":"NA","Y":0,"class":"UITextField"}
{"data":"Enter UserName","type":"string"}

So, here in the code you can see that I have taken json array sometimes and object sometime, you need to differentiate between them.
import java.io.FileReader;
import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class test {

    public static void main(String[] args) throws IOException, InterruptedException {
        JSONParser parser = new JSONParser();
        try {
            Object obj = parser.parse(new FileReader("test.json"));
            JSONArray jsonObject = (JSONArray) obj;
            JSONObject arr = (JSONObject) jsonObject.get(0);
            JSONArray arguments = (JSONArray) arr.get("arguments");
            System.out.println("arguments>>>>>>>>> "+arguments);
            for(int i = 0 ; i< arguments.size() ;i++){
                JSONObject object = (JSONObject) arguments.get(i);
                System.out.println(object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
Q: Confused by Javascript's variable scope I'm finding myself by Javascript's variable scope, could someone explain to me why the first example doesn't work but the second does?
function test() {
  return typeof(the_variable) !== 'undefined' && the_variable;
}

(function () {
   var the_variable = "doesn't work";
   console.log(test());
}());

var the_variable = "does work";
console.log(test());

Output I get in my log:
false
does work

Also I would like to know how to do something similar to the first example.

A: Explained in comments:
function test() {
  return typeof(the_variable) !== 'undefined' && the_variable;
}

// The variable in this function is scoped to the anonymous function.
// It doesn't exist outside that function, so `test` cannot see it
(function () {
   var the_variable = "doesn't work";
   console.log(test());
}());

// This variable exists in a scope that wraps the `test` function, so it can see it.
var the_variable = "does work";
console.log(test());

A: In Javascript, functions define scope. In your first example the_variable is outside of the scope of test. On the other hand, in the second example, the_variable is defined in the global scope and is available everywhere.
EDIT
Catch the_variable in a closure if you want it to be available to test.
var foo = (function () {
   var the_variable = "does work";
   function test() {
       return typeof(the_variable) !== 'undefined' && the_variable;
   }
   return {test : test};
}());
console.log(foo.test());

Output:
does work


text:
Q: Rhombs/diamonds with questions marks instead of swedish characters in MySQL I recently moved the content of a database from one host to another. And after that I get strange character like two rhombs or diamonds with questions marks inside instead of the swedish character ä.
I had this problem before at the first host and then I added this code and it worked fine
$query1 = "SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'";

$query2 = "SELECT * FROM arkitekturobjekt2 WHERE filnamn='{$namn}';";

$result = $db->query($query1);
$result = $db->query($query2);

If I remove the line with the $query1 I only get one rhomb. How can I fix this?
EDIT:
This is my code and here is the strings puts together with the content from the DB in a loop. I tested to use utf8_encode(string) around ($row->byggnadstyp) but then I get other strange character. But finally I tested to remove the strtolower then it's perfect, apart from that the first character isn't small. But I can live with that, but I would be interesting to know why I get this diamonds when I use strtolower. I use utf8 everywhere and the files are set to utf8 without BOM.
$buildingInfo .= "
Byggnadstyp: " . strtolower ($row->byggnadstyp) . "
";

A: You could try to add this to your mysql config:
[client]
default-character-set=utf8

[mysql]
default-character-set=utf8

[mysqld]
default-character-set = utf8
collation-server = utf8_general_ci
init-connect='SET NAMES utf8'
character-set-server = utf8
skip-character-set-client-handshake=1

The last line (skip-character-set-client-handshake=1) may not be needed.
If you don't have access to the config file, you could check out this help page. It basically boils down to send the command
SET NAMES 'UTF8';

at the beginning of a connection. This is however similar to what you do already.


text:
Q: Is 'That is why' formal? When I want to say that it is the reason of my previous work, in an official article, is it recommended to use the following or not?
That is why we used this object in the previous work.

A: Yes, you can use it formally. See the following examples:

I want to be involved in town government, and that is why I'm running for mayor.

And

"That is why you help out people in need."

Merriam Webster Learner's Dictionary says more about "that is why".
Of course, it depends more on context as you can use "therefore" instead of it. I am not a native speaker and they can give you better replacements for "that is why", but I don't think that it is recommended to use in official article. "that is why" is particularly useful for conversation like- "that is why I decided to go", "that is why you went there", etc. So, it is a conversational phrase.
I would prefer to write the above sentence as:

That is the reason for which we used this object in the previous work.

After all, you need to be more formal in an official article, right?
Hope this would help.


text:
Q: How is the variance equivalent to the following? I am working through a problem that asks if the set, $P$ is convex.
Note that $P$ is a set of pdfs.  Each member $p \in P$ describes a pdf - a vector of real numbers that are probabilities.  The assignment is to determine if the set of all pdfs (all $p$'s) subject to a restriction on the variance, is a convex set.
These are the restrictions on $p$, including the inequality for the variance of all of all of the $p$'s:

*

*$p$ is a vector of probabilities, $p \in \mathbb{R}^+$

*probability simplex, which is of course a restriction on $p$
$P = \{p \,  \vert \sum_{i=1}^{n}{p_i} = 1 , p \ge 0\}$

*$p_i$ is the probability that random variable $x$ is $x=a_i$ with $x \in \mathbb{R}$

*$var(x) \ge \alpha\ $and$ \,\,var(x) = \sum_{i=1}^n{(x_i-E[x])^2}\}$

*$\alpha \in \mathbb{R}$ and $var(x) = \sum_{i=1}^n{(x_i-E[x])^2}$ and $E[x]=\sum_{i=1}^np_ix_i$
Now, in the Solutions to the homework I see
In the solutions to my homework, it says that that "$var(x) \ge \alpha$ can be reformulated as $\sum_{i=1}^np_ia_i^2+(\sum_{i=1}^np_ia_i)^2 \le \alpha$".
This is obviously convex...so I can see the answer from there.
But, my question is how can this inequality $var(x) \ge \alpha$ be reformulated as $\sum_{i=1}^np_ia_i^2+(\sum_{i=1}^np_ia_i)^2 \le \alpha$ ?
EDIT
Here is the homework question in full.  I am particularly asking about parts (f) and (g):

And here is the solution:

If you'd like any more information, please let me know.

A: First we know that
$$
\mathbf{Var}(x) = Ex^2 - (E(x))^2 = \sum_{i=1}^np_i a_i^2 - (\sum_{i=1}^np_ia_i) ^2 \geq \alpha
$$
The set  is equilvalent to
$$
- \sum_{i=1}^np_i a_i^2 + (\sum_{i=1}^np_ia_i) ^2 \leq \alpha
$$
Define $b = [-a_1^2,-a_2^2,...,-a_n^2], A = aa^T $, then  it is equilvalent to
$$
-b^Tp + p^TAp \leq \alpha
$$
With $-b^p, p^TAp$ are both convex function about $x$,  $f(p) = -b^Tp + p^TAp $ is also convex. With the image of $f$ with $f(x) \leq \alpha$, the image of $f$ is convex. Then the inverse image $p$ is also convext.
Proof done.
Note: A is positive semidefinite, such that $p^TAP$ is convex .

A: This question cannot be answered as is, because we lack a proper definition of "convex" in this setting.
For a complete answer, the full homework text is needed.
Setup
Let's write in here all the assumptions ans appreciations:
Definitions:

*

*$\mathscr P$ is a infinite set of discrete pdfs, for a fixed set of numbers $a_i \in \mathbb{R}$,

*$f_j$ is a discrete pdf for the random variable $x_j$, described through the vector $p_j \in \mathbb{R}^n$, $j=1...m$:
$$
f_j(x)=\sum_{i=1}^np_{ij}\delta(x-a_{i}), \sum_{i=1}^np_{ij}=1, p_{ij}\ge 0
$$

Constraint:

*

*$\text{var}(x) \ge \alpha, \alpha \gt 0$

Applying the definition of variance to the $j$th pdf:
$$
\text{var}\{f_j\}= \sum_{i=1}^np_{ij}a_{i}^2-\left(\sum_{i=1}^np_{ij}a_{i}\right)^2 \ge \alpha
$$
Question
To determine if the set of all $p \in \mathscr P$ subject to a restriction on the variance, is a convex set.
Possible Interpretations

*

*Over the set $\mathscr P$ it is trivial to apply convex combinations, if we assume $\mathscr P$ is infinite,

*Over the domain $\mathbb{R}$, for the area defined by each function $f_j(x)$ it is not possible to interpolate a line, because each pdf is discrete, made of delta impulses, hence the interpolations, if valid, are always above the area, hence not being convex.

Best interpretation
A Convex Combination over a set of pdfs or also called a Mixture Distribution is the pdf obtained by weighting every pdf through non-negative numbers with sum equal to 1:
$$
f_m(x)=\sum_{j=1}^mb_jf_j(x), \sum_{j=1}^mb_j=1, b_j\ge 0
$$
Hence:
$$
f_m(x)=\sum_{i=1}^n \left(\sum_{j=1}^m b_jp_{ij} \right) \delta(x-a_{i})
= \sum_{i=1}^n \beta_{ij} \delta(x-a_{i})
$$
Note that $\sum \beta_{ij}>1, \beta_{ij}>0$ (why?).
Thus, it is possible to build convex combinations from elements of $\mathscr P$ with or without the given constraint, by definition.
Assuming also than the set $\mathscr P$ is not finite, but $p_i \in \mathbb{R}$ we found from the given operation that $\mathscr P$ is closed under convex combinations, hence $\mathscr P$ is convex trivially. But this is independent on the given constraint, and keeps being a void question.
Main Comment
EDIT:
 - As pointed out, the expression is equivalent to:
$$
\text{var}\{f_j\}= \sum_{i=1}^np_{ij}a_{i}^2-\left(\sum_{i=1}^np_{ij}a_{i}\right)^2 \ge \alpha
\\
 \sum_{i=1}^np_{ij}a_{i}^2+\left(\sum_{i=1}^np_{ij}a_{i}\right)^2 \ge \alpha + 2\left(\sum_{i=1}^np_{ij}a_{i}\right)^2 \ge \alpha
$$
Which is the opposite to the given answer in (g), hence the set is not convex.

A: I think there might be a mistake in the solutions you were given (in fact, I suspect this problem is from a class I TA'd, EE364A, due to the similarities in formatting, etc).
The idea is that we can write $\text{var}(x)$ as
$$
\text{var}(x) = \sum_i p_ia_i^2 - \left(\sum_i p_ia_i\right)^2
$$
but note that your expression in this case is wrong in both the inequality direction and sign, since you can't sum both of the terms to get an expression for variance. Additionally, note that we're asking for convexity w.r.t. $p$. This is now not a convex function, but rather a concave one. Both notions should be easy to prove from here.


text:
Q: I- Net Crystal Clear Report I need consultation.
I have next  problem.
In report page i have
-header
-details
-footer
In every page i have different counts of records. In header i want show id of first record and id of last record in page. How i can make this? Because last record in page i can get only in last iteration in details or in footer of page. But main problem that i need to know last record in page in header of page. The way to put some number for every page - i can not make this, because differents records have different size of information(some records have 3 lines, some 4 lines) and it can be free space in page


text:
Q: Assembly Mips - convert two Strings (containing Float) and find the Gap between them I have to create a function that returns the difference between two floats.
Example: User A's lat is 22.00, and User B's lat is 20.00 (or 24.00) the result must be 2.00.
This is a easy subtraction yeah...... I Found a way to store the floats without \n and the point but i can't find a way to use the array in an arithmetical operation. That's very frustating.
I hope somebody help me
.data

dot: .asciiz "."
aCapo: .asciiz "\n"

A: .word    nome1, cognome1, lat1, long1
nome1: .asciiz "Paolo\n"
cognome1: .asciiz "Bonomi\n"
lat1: .asciiz "69.31\n"
long1: .asciiz "45.00\n"

B: .word    nome2, cognome2, lat2, long2
nome2: .asciiz "Xhoni\n"
cognome2: .asciiz "Lara\n"
lat2: .asciiz "40.02\n"
long2: .asciiz "90.00\n"

array: .space 256

.text
.globl main

main:

la $a1, A
la $a2, B

la $t8, array

lw $s1, 8($a1)
lb $t0, 0($s1)
sb $t0, 0($t8)
lb $t0, 1($s1)
sb $t0, 1($t8)
lb $t0, 3($s1)
sb $t0, 2($t8)
lb $t0, 4($s1)
sb $t0, 3($t8)

EDIT: i just find a way to do this
this function works great, btw i know is not functional at all.. there is so much redundancy but i dont have so much time so.. thanks so much for the tips and help
diff_geo:
array: .word 1
array2: .word 1

risultatoLat: .word 1
empty: .word 1

risultatoLong: .word 1
empty2: .word 1

#
# this fuction takes two utentiR in $a1 and $a2
# and return the difference by  lat and long from the two user
#

try_lat:
lw $s1, 8($a1)  # put in s1 adress lat1
la $t8, array

lb $t0, 4($s1) #
sb $t0, 0($t8) #
lb $t0, 3($s1) #
sb $t0, 1($t8) #
lb $t0, 1($s1) #
sb $t0, 2($t8) #
lb $t0, 0($s1) #
sb $t0, 3($t8) #
lw $s0, 0($t8) # put in s0 lat1 without "." and "\n"

lw $s2, 8($a2) # put in s2 address lat2
la $t9, array2 #

lb $t0, 4($s2) #
sb $t0, 0($t9) #
lb $t0, 3($s2) #
sb $t0, 1($t9) #
lb $t0, 1($s2) #
sb $t0, 2($t9) #
lb $t0, 0($s2) #
sb $t0, 3($t9) #
lw $s1, 0($t9)  # put in s1 lat2 without "." and "\n"

blt $s0, $s1, switch_utenti     # if latA < latB goto switch
beq $s0, $s1, return_equal      # if latA = latB return "00.00"

j do_sub_lat    # else do sub

return_equal:
la $a0, str_diffLat # stamp "Differenza Latitudine: "
li $v0, 4
syscall

la $a0, str_same # stamp "00.00\n"
li $v0, 4
syscall

j try_long # goto process long

switch_utenti:
move $a0, $a1
move $a1, $a2
move $a2, $a0

do_sub_lat:
lw $s1, 8($a1)          # put in s1 adress lat1
lw $s2, 8($a2)          # put in s2 adress lat2
lb $t0, 0($s1)          # load first number of lat1
lb $t1, 0($s2)          # load first number of lat2
sub $t2, $t0, $t1       # t2 = t0 - t1 (decimal)
lb $t0, 1($s1)          # load second number lat1
lb $t1, 1($s2)          # load second number lat2
bge $t0, $t1, jEDLat    # if (T0 >= T1) jump exception
li $t7, 1               # load 1 in t7
li $t6, 9               # load 9 in t6
sub $t2, $t2, $t7       # sub 1 from first number of the result
add $t0, $t0, $t6       # add 9 to t0
sub $t1, $t1, $t7       # sub 1 to t1 (i have to made this because if i try to ad 10 to t0, 10 will be like "a" no "10")
jEDLat:
sub $t3, $t0, $t1       # T0 - T1 risultato DECIMALE in T3
lb $t0, 3($s1)          # carico secondo numero di A
lb $t1, 3($s2)          # carico secondo numero di B
bge $t0, $t1, jETLat    # if (T0 >= T1) salta eccezione
li $t7, 1               # carico 1 in T7
li $t6, 9               # carico 10 in T6
sub $t3, $t3, $t7
add $t0, $t0, $t6
sub $t1, $t1, $t7
jETLat:
sub $t4, $t0, $t1       # T0 - T1 risultato DECIMALE in T4
lb $t0, 4($s1)          # carico quarto numero di A
lb $t1, 4($s2)          # carico quarto numero di B
bge $t0, $t1, jEQLat    # if (T0 >= T1) salta eccezione
li $t7, 1               # carico 1 in T7
li $t6, 9               # carico 10 in T6
sub $t4, $t2, $t7
add $t0, $t0, $t6
sub $t1, $t1, $t7
jEQLat:
sub $t5, $t0, $t1       # T0 -T1 risultato DECIMALE in T5

addi $t2, $t2, 48
addi $t3, $t3, 48
addi $t4, $t4, 48
addi $t5, $t5, 48

la $t8, risultatoLat
la $t7, aCapo
lb $t7, 0($t7)
sb $t7, 5($t8)
sb $t5, 4($t8)
sb $t4, 3($t8)
la $t7, dot
lb $t7, 0($t7)
sb $t7, 2($t8)
sb $t3, 1($t8)
sb $t2, 0($t8)

la $a0, str_diffLat
li $v0, 4
syscall

la $a0, risultatoLat
li $v0, 4
syscall

try_long:
lw $s1, 12($a1) # Metto in S1 la parola puntata da A1
la $t8, array

lb $t0, 4($s1) #
sb $t0, 0($t8) #
lb $t0, 3($s1) #
sb $t0, 1($t8) #
lb $t0, 1($s1) #
sb $t0, 2($t8) #
lb $t0, 0($s1) #
sb $t0, 3($t8) #
lw $s0, 0($t8)  # IN S0 LONGITUDINE A

lw $s2, 12($a2) # Metto in S2 la parola puntata da A2
la $t9, array2

lb $t0, 4($s2) #
sb $t0, 0($t9) #
lb $t0, 3($s2) #
sb $t0, 1($t9) #
lb $t0, 1($s2) #
sb $t0, 2($t9) #
lb $t0, 0($s2) #
sb $t0, 3($t9) #
lw $s1, 0($t9)  # IN S1 LONGITUDINE B

blt $s0, $s1, switch_utenti2    # se latA < latB inverto
beq $s0, $s1, return_equal2     # se latA = a latB ritorno 00.00

j do_sub_long

return_equal2:
la $a0, str_diffLong # stampo "Differenza Longitudine: "
li $v0, 4
syscall

la $a0, str_same # stampo "00.00\n"
li $v0, 4
syscall

jr $ra # fine funzione

switch_utenti2:
move $a0, $a1
move $a1, $a2
move $a2, $a0

do_sub_long:
lw $s1, 12($a1)         # Metto in S1 la parola puntata da A1
lw $s2, 12($a2)         # Metto in S2 la parola puntata da A2
lb $t0, 0($s1)          # carico primo numero di A
lb $t1, 0($s2)          # carico primo numero di B
sub $t2, $t0, $t1       # T0 - T2 risultato DECIMALE in T2
lb $t0, 1($s1)          # carico secondo numero di A
lb $t1, 1($s2)          # carico secondo numero di B
bge $t0, $t1, jEDLong   # if (T0 >= T1) salta eccezione
li $t7, 1               # carico 1 in T7
li $t6, 9               # carico 10 in T6
sub $t2, $t2, $t7
add $t0, $t0, $t6
sub $t1, $t1, $t7
jEDLong:
sub $t3, $t0, $t1       # T0 - T1 risultato DECIMALE in T3
lb $t0, 3($s1)          # carico secondo numero di A
lb $t1, 3($s2)          # carico secondo numero di B
bge $t0, $t1, jETLong   # if (T0 >= T1) salta eccezione
li $t7, 1               # carico 1 in T7
li $t6, 9               # carico 10 in T6
sub $t3, $t3, $t7
add $t0, $t0, $t6
sub $t1, $t1, $t7
jETLong:
sub $t4, $t0, $t1       # T0 - T1 risultato DECIMALE in T4
lb $t0, 4($s1)          # carico quarto numero di A
lb $t1, 4($s2)          # carico quarto numero di B
bge $t0, $t1, jEQLong   # if (T0 >= T1) salta eccezione
li $t7, 1               # carico 1 in T7
li $t6, 9               # carico 10 in T6
sub $t4, $t2, $t7
add $t0, $t0, $t6
sub $t1, $t1, $t7
jEQLong:
sub $t5, $t0, $t1       # T0 -T1 risultato DECIMALE in T5

addi $t2, $t2, 48
addi $t3, $t3, 48
addi $t4, $t4, 48
addi $t5, $t5, 48

la $t7, aCapo
lb $t7, 0($t7)
la $t8, risultatoLong
sb $t7, 5($t8)
sb $t5, 4($t8)
sb $t4, 3($t8)
la $t7, dot
lb $t7, 0($t7)
sb $t7, 2($t8)
sb $t3, 1($t8)
sb $t2, 0($t8)

la $a0, str_diffLong
li $v0, 4
syscall

la $a0, risultatoLong
li $v0, 4
syscall

la $a0, aCapo
li $v0, 4
syscall

jr $ra

i have omitted that lat and long format is the same for all
ctrl_geo:
#
# questa funzione prende come argomento in $a0 una indirizzo ad una stringa
# la funzione contolla se il formato è corretto cioè rispetta il formato "xx.xx\n" con x compreso tra 0 e 9
# restituisce in $a0 1 se l'inserimento è avvenuto correttamente altrimenti stampa a video una stringa di errore
# e restituisce in $a0 0
#

lb $t0, 0($a0) # carico numero decine in $t0
lb $t1, min
blt $t0, $t1, errore_geo # controllo se è minore di 0
lb $t1, max
bgt $t0, $t1, errore_geo # controllo se è maggiore di 9

lb $t0, 1($a0) # carico numero unità in $t0
lb $t1, min
blt $t0, $t1, errore_geo # controllo se è minore di 0
lb $t1, max
bgt $t0, $t1, errore_geo # controllo se è maggiore di 9

lb $t0, 2($a0) # carico punto in $t0
lb $t1, dot
bne $t0, $t1, errore_geo # se non c'è un punto in t0 mando ad errore

lb $t0, 3($a0) # carico numero dopo punto decine in $t0
lb $t1, min
blt $t0, $t1, errore_geo # controllo se è minore di 0
lb $t1, max
bgt $t0, $t1, errore_geo # controllo se è maggiore di 9

lb $t0, 4($a0) # carico numero dopo punto unità in $t0
lb $t1, min
blt $t0, $t1, errore_geo # controllo se è minore di 0
lb $t1, max
bgt $t0, $t1, errore_geo # controllo se è maggiore di 9

lb $t0, 5($a0) # a capo in $t0
lb $t1, aCapo
bne $t0, $t1, errore_geo # se in t0 non ho aCAPO mando a errore

li $a0, 1
jr $ra # fine funzione

errore_geo:
la $a0, str_erroreNumerico
li $v0, 4
syscall

li $a0, 0
jr $ra # fine funzione

this is so unfunctional i know that... maybe if i store lat and long values like float and not like ascii that would prevented a great deal of trouble.

A: I'm not sure what you mean:

can't find a way to use the array in an arithmetical operation

As in Assembly there's not even a well defined thing like "array", but you probably mean some amount of consecutive bytes.
Arithmetic instructions like sub can work only over registers (and only with word size).
So if you have two ASCII "numbers" in strings with removed decimal dot and newline, like:
num1: .byte '1', '2', '7', '8', 0  # was "12.78\n"
num2: .byte '5', '6', '3', '4', 0  # was "56.34\n"
res:  .space 16  # should be plenty for lat/lon difference

Get indices of last digit for both n1i = 3, n2i = 3 and set resi = max(n1i, n2i).
Now as you want absolute value of sub, you can check which number is smaller and subtract that one from the greater one.
num1bigger = (n2i < n1i) || (n1i == n2i && first_different_digit_is_bigger_in_n1);
// equal numbers will produce "false"

EDIT: actually this would produce wrong result for one special case: num1 = "0012" vs num2 = "345" would produce num1bigger = true;, the described thing works only when leading zeroes are not part of considered ASCII numbers.
This nicely (in unplanned way) illustrates why you should unit-test your algorithms with as many corner cases as you can figure out (including things like empty data and null data, when applicable), and how even "trivial" tasks can be coded with bugs easily. Well, not just coded, but already designed with bug on the high level.

Now subtraction algorithm (in C-like pseudo language, if you don't know C, then sorry):
    init:
      already set: n1i, n2i, num1bigger, num1, num2, res, resi
      borrow = false, res[resi+1] = 0

    sub_loop:
  *1  r1 = (0 <= n1i) ? num1[n1i--] : '0'
      r2 = (0 <= n2i) ? num1[n2i--] : '0'
      if (!num1bigger) swap(r1,r2)
      // r1 is byte-part of bigger number, r2 of smaller
      if (borrow) ++r2
  *2  r3 = r1 - r2       // ASCII - ASCII = numeric value
      borrow = (r3 < 0)
      if (borrow) r3 += 10  // adjust negative into 0-9
      r3 += '0'          // add ASCII encoding back
  *3  res[resi--] = r3
      if (0 <= resi) jump sub_loop
      // as the smaller number is subtracted from larger, borrow=0 at end
      // so no need to patch the result in sign flip way

      // but you may want to remove leading zeroes
      // (but keep at least three of them for "0.00" result)

This is per-byte ASCII absolute value subtraction algorithm. (both inputs [22, 20] and [22, 24] will produce +02 result!).
BTW, for non absolute subtraction it's actually almost the same, but when !num1bigger, the minus sign has to be added ahead of result => 22-24 = -02 (now the leading zero looks quite bad :) ).
For my example array the value inside loop will be like:
init:
num1bigger = false, borrow = false, res[4] = 0
  Loop first iteration:
  *1 fetching, swapping, borrow adjust: r1 = '4', r2 = '8'
  *2 subtraction, adjustment: r3 = '6', borrow = true
  *3 store result: res[3] = '6', n1i == n2i == resi == 2
  (0 <= resi (2)) -> loop again
  *1 fetching, swapping, borrow adjust: r1 = '3', r2 = '8'
  *2 subtraction, adjustment: r3 = '5', borrow = true
  *3 store result: res[2] = '5', n1i == n2i == resi == 1
  (0 <= resi (1)) -> loop again
  *1 fetching, swapping, borrow adjust: r1 = '6', r2 = '3'
  *2 subtraction, adjustment: r3 = '3', borrow = false
  *3 store result: res[1] = '3', n1i == n2i == resi == 0
  (0 <= resi (0)) -> loop again
  *1 fetching, swapping, borrow adjust: r1 = '5', r2 = '1'
  *2 subtraction, adjustment: r3 = '4', borrow = false
  *3 store result: res[0] = '4', n1i == n2i == resi == -1
  !(0 <= resi (-1)) -> exit loop
  // here res bytes are set to '4', '3', '5', '6', 0
  // which can be formatted as result 43.56 (== 56.34 - 12.78)

... I'm not going to try to write it in MIPS assembly, as I never did coding in it, plus I can't steal all the fun from you. I hope this above gives you idea, how you can do arithmetic operations upon ASCIIZ strings of digits.
Basically you should write it on paper, and focus what you would do when you can manipulate single digit only per step. And write that down as an algorithm.
Try it on few values (make sure there are some corner cases, like my "first_different_digit_is_bigger_in_n1", or two equal values, or 123.45 - 7.89, 0.00 input and maybe even empty string).
And if it looks solid, just write the instructions between those steps (I tried to break my algorithm into so many simple tiny steps, that most of them should be resolved by 1-2 instructions at most, maybe sometimes 3-4 when I missed the MIPS architecture too much. I'm used to x86 instructions, so I tried to follow more RISC-like logic (avoiding flags usage for example), but still...).


text:
Q: Lambda function errorMessage": "Cannot read property 'bucket' of undefined I have a lambda function that is triggered whenever something is saved in my s3 bucket,
the aim is to read the metadata of a JSON file and insert rows in a dynamoDB table;
for instance
a training period starts on the june the 1st and end june 8th
and training days are Monday, Wednesday and Friday
thus the lambda should insert 4 rows ( 1st, 3rd, 5th, 8th of june)
so far only one row is inserted and then the error occurs and it crashes
The function is triggered well but this error message occurs sometimes.
{
    "errorType": "TypeError",
    "errorMessage": "Cannot read property 'bucket' of undefined",
    "stack": [
        "TypeError: Cannot read property 'bucket' of undefined",
        "    at Runtime.exports.handler (/var/task/index.js:26:44)",
        "    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
    ]
}

here is my function
let AWS = require('aws-sdk');
let s3 = new AWS.S3();
let moment = require('moment');
let uuid = require('node-uuid');

let apiSportmTrainingTableName = process.env.API_SPORTM_TRAININGTABLE_NAME
let dynamodb = new AWS.DynamoDB.DocumentClient();

exports.handler =  async (event, context) => {
  //eslint-disable-line
  const Bucket = await event.Records[0].s3.bucket.name;

  const Key = await event.Records[0].s3.object.key;
  const objectHead = await s3.headObject({Bucket, Key}).promise();

  let start = moment(new Date(objectHead.Metadata.trainingstart), "YYYY-MM-DD");
  let end = moment(new Date(objectHead.Metadata.trainingend), "YYYY-MM-DD");
  let days = JSON.parse("[" + objectHead.Metadata.trainingdays + "]");

  try {
    for (let m = moment(start); m.diff(end, 'days') <= 0; m.add(1, 'days')) {

      for (const e of days) {

        if (moment(m).day() === e) {
          let params = {
            TableName: apiSportmTrainingTableName,
            Item: {
              "id": uuid.v1(),
              "trainingDate": moment(m).format('YYYY-MM-DD'),
              "statut": true,
              "athleteCategory": objectHead.Metadata.trainingmembercategory,
              "trainingTime": objectHead.Metadata.trainingtime
            }
          };
          return await dynamodb.put(params).promise();
        }
      }
    }
  } catch (err) {
    console.error('Error', err);
    return;
  }
  context.done(null, 'Successfully processed DynamoDB record'); // SUCCESS with message
};

when the event logs it looks like that
Records: [
    {
      eventVersion: '2.1',
      eventSource: 'aws:s3',
      awsRegion: 'us-east-1',
      eventTime: '2020-05-29T18:34:53.250Z',
      eventName: 'ObjectCreated:Put',
      userIdentity: [Object],
      requestParameters: [Object],
      responseElements: [Object],
      s3: [Object]
    }
  ]
}
```

that a part of logs it fails and then works and then it keeps trying and fail

[logs][1]

  [1]: https://i.stack.imgur.com/Sj5C7.png

A: You are using return after inserting data into DynamoDB:
return await dynamodb.put(params).promise();

This returns the result of the DynamoDB operations as the result of the Lambda function, which terminated the execution. This explains why only one record is inserted into DynamoDB. I'd try to remove the return and see if that also removes the error (best guess on my part: the returned value somehow causes another execution with it, but this time missing the S3 event, thus event.Records[0].s3 will be undefined).


text:
Q: How to display json formatted string NSTextview I want to display a formatted JSON string in an NSTextView.
If I set it directly it will display as continues string, but I need it as formatted like
{
    "0":"N",
    "J":5
}

Is there any inbuilt method or 3rd party opensource library to format json?

A: A lot of JSON parsing frameworks have the option of pretty printing.
For instance SBJsonWriter. It has a  humanReadable property.

If set to YES, generates human-readable JSON with linebreaks after
  each array value and dictionary key/value pair, indented two spaces
  per nesting level.

If you just want the indentation logic you can dig in and just use that part and strip your project of unnecessary SBJson files.
EDIT:
From OS X 10.7, NSJSONSerialization is available natively in Cocoa.
You can pass the NSJSONWritingPrettyPrinted as an option to
+dataWithJSONObject:options:error: class method of NSJSONSerialization to achieve what you want.


text:
Q: Virtuemart call add to cart function I'm new to Virtuemart development. I have my own template for the product details page:
templates/myTemplate/html/com_virtuemart/productdetails/myProductDetails.php

I also added a custom field (string) for the product (I will have only one product that can be configured). The configuration for that product will be done on the product details page. I have developed a configuration process using jQuery.
I also added the virtuemart "Add to cart"-Button using the following code:
echo shopFunctionsF::renderVmSubLayout('addtocart',array('product'=>$this-
>product));

If the user clicks the "Add to cart"-Button i have to check the configuration. If the configuration is valid then it should be stored in the custom field i have created for the product. I'd like to store the data to the custom field as a JSON-string. After the data has been saved to the custom field, I'd like to add the product to the cart. Then the usual popup dialog should be shown. The custom field value should be shown as cart attribute. If the configuration is not valid then there should be some sort of an error output. The product should not be added to the cart.
How can i use the virtuemart "Add to cart" functionality to do this?
I also have to check the submitted data in the custom field on the server side. What is the best approach to do this? (Maybe using the checkout page?)

A: I found the solution to add Items to cart and check the configuration:
$('#myaddtocart').click(function() {

  var data = "quantity[]="+20+"&virtuemart_product_id[]="+1;

  $.ajax({

    type: "GET",
    dataType: 'json',
    url: "index.php?option=com_virtuemart&nosef=1&view=cart&task=addJS",
    data: data,
    success: function(data) {

    }

  });

});

This snippet calls the addJS() function located in /com_virtuemart/controllers/cart.php - only quantity and product id must be provided. Also I used my own button (#myaddtocart) to trigger the click event and add the item to the cart.


text:
Q: Should I Use a Separate UIViewController for a Popup Menu? A rather theoretical or abstract question...
I have a view controller  (let's call it viewControllerA) with a view (obviously). While the view is displayed, should the user press a specific button a popup menu will appear (think of a grid of buttons). The user can press a button in the popup menu to transition to another view (controlled by another view controller).
Should I have a separate view controller to handle/manage the popup menu or should I "simply" implement the popup menu as a view which is controlled by the same view controller (i.e. viewControllerA)?
Reasons for and against each approach would be greatly appreciated.

A: Should I have a separate view controller to handle/manage the popup menu?
I believe, this is the better option. You can create a container view on storyboard which will have a separate controller which is much easier to work with, then a huge file with different views.
What you will gain:

*

*Nicely structured files with a single responsibility

*Easier to test and adjust both elements

Should I "simply" implement the popup menu as a view which is controlled by the same view controller?
There are no advantages in this approach as it looks to me.
In this case you will:

*

*Violate a single responsibility principle.

*"simply" - will mean that you will have 2 different views with their lifecycles managed in one controller (simply becomes harder)

*most probably it will be Massive View Controller

If you don't use any particular architecture pattern, maybe you should take a look here.

A: Yes, you can use UIViewController as a Popup.
Step1: Take a new UIViewController on the storyboard and create a class associated with it.
Step 2: You said that after clicking on the button that Popup has to show, then take a button on the first ViewController and write below code
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
PopupViewController *popupVC = [storyboard instantiateViewControllerWithIdentifier:@"popId"];

BIZPopupViewController *popupViewController = [[BIZPopupViewController alloc] initWithContentViewController:popupVC contentSize:CGSizeMake(300, 300)];

[self presentViewController:popupViewController animated:NO completion:nil];

It will show PopupViewController as a popup view in your view.
Here is the link for BIZpopViewController copy the class into your project, it will work.


text:
Q: Why is reachabilityForInternetConnection not working after I remove internet connection after launching the application? + (BOOL) networkAvailable {
    Reachability *reachability = [Reachability reachabilityForInternetConnection];

    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    if (internetStatus != NotReachable) {

        return YES;
    }
    return NO;
}

I am using Tony Million's Reachability class. I have made a static utility method to check for current reachability. however it only works for the first time when app is launched.
If I remove the LAN cable from my iMac (I am connected to my office's shared LAN) after starting the app in the simulator,
this method still returns YES.
Also, Same behaviour happens when I test it with the device and remove the wifi connection and try making an API call.
It never detects that internet is no more available.
I don't want any notification of reachability changing. I just want to be able to check if the connection is available before making an API call.
EDIT:
This is how I use it.
if(![MyUtilities networkAvailable])
{
   // network not there. show a message.
}
else {
  // make the API call
}


text:
Q: R - Call a function from function name that is stored in a variable? I'm writing some R code and I want to store a list of Function names and what they are for in a dataframe, and then query that dataframe to determine which function to call, but I can't figure out how to do this, or if it's even possible.
As a basic example, let's assume the function name is just stored as a string in a variable, how do I call the function based on the function name stored in that variable?
MyFunc <-function() {
    # Do some stuff...
    print("My Function has been called!!!")
    return(object)
}

FuncName <- "MyFunc()"
Result <- FuncName

I need to make
Result <- FuncName

Work the same as
Result <- MyFunc()

Also, passing objects, or other variables, to the functions is not a concern for what I am doing here, so those () will always be empty.  I realize passing variables like this might get even more complicated.

A: To get a function from its name, try match.fun, used just like get in the answer provided by @Alex:
> a <- function(x) x+1
> f <- "a"
> match.fun(f)(1:3)
[1] 2 3 4

To call a function directly using its name, try do.call:
> params <- list(x=1:3)
> do.call(f, params)
[1] 2 3 4

The advantage to do.call is that the parameters passed to the function can change during execution (e.g., values of the parameter list can be dynamic at run time or passed by the user to a custom function), rather than being hardwired in the code.
Why do I suggest match.fun or do.call over get?  Both match.fun and do.call will make sure that the character vector ("a" in the above examples) matches a function rather than another type of object (e.g., a numeric, a data.frame, ...).
Consider the following:
# works fine
> get("c")(1,2,3)
[1] 1 2 3

# create another object called "c"
> c <- 33
> get("c")
[1] 33

#uh oh!!
> get("c")(1,2,3)
Error: attempt to apply non-function

# match.fun will return a function; it ignores
# any object named "c" that is not a function.
> match.fun("c")(1,2,3)
[1] 1 2 3

# same with do.call
> do.call("c", list(1,2,3))
[1] 1 2 3

A: You could use get() with an additional pair of ().
a<-function(){1+1}
var<-"a"

> get(var)()
[1] 2


text:
Q: TextGen generate different programming langugages code from one concept I have a concept (let's call it A) that is being generated into a Ruby class using TextGen. I want to have the possibility to generate the same concept into other languages e.g Python. Could someone describe how to do it or some hint?

A: I recommend you use plaintextgen plugin (https://plugins.jetbrains.com/plugin/8444-com-dslfoundry-plaintextgen) for this. You can then just use reduction rules to generate the text. A tutorial for this can be found here: https://dslfoundry.com/plaintextgen-tutorial/
Using textgen aspect is also possible, but is much more involved for your use case, because it requires either that you have an existing MPS language for each text-based target language (Python, Ruby, C#, etc.) or that you implement a minimum version (at least containing the concepts and textgen aspects for the constructs you need in your generation result) of such a target language yourself.


text:
Q: how to include Android gradle dependencies in Eclipse I have created  simple android eclipse project. Then I added build.gradle file.
buildscript {
  repositories {
    mavenCentral()
  }

  dependencies {
    classpath 'com.android.tools.build:gradle:0.4'
  }
}

task listJars << {
    configurations.compile.each { File file -> println file.path }
}

apply plugin: 'android'

android {
  compileSdkVersion 17
  buildToolsVersion '17'

  repositories {
    mavenCentral()
    }

  sourceSets {
    main {
      manifest.srcFile 'AndroidManifest.xml'
      java.srcDirs = ['src']
      resources.srcDirs = ['src']
      renderscript.srcDirs = ['src']
      res.srcDirs = ['res']
      assets.srcDirs = ['assets']
    }

    instrumentTest.setRoot('tests')
    instrumentTest {
      java.srcDirs = ['tests/src']
      res.srcDirs = ['tests/res']
      assets.srcDirs = ['tests/assets']
      resources.srcDirs = ['tests/src']
    }
  }

  dependencies {
    compile 'org.roboguice:roboguice:2.0'
    compile fileTree(dir: 'libs', include: '*.jar')
  }
}

As you can see, I want to use RoboGuice from maven. Gradle downloads it, but does not add to the lib folder for eclipse. So I cannot use it in eclipse when writing code. Do I need to manually copy them over? I added a task to display them:
$ gradle -q listJars
/Users/xxx/Documents/codepath2/SampleAndroidGradle/libs/android-support-v4.jar
/Users/xxx/.gradle/caches/artifacts-24/filestore/org.roboguice/roboguice/2.0/jar/727ccb8f376109d0b5c44abca6f791dccc5c5dbc/roboguice-2.0.jar
/Users/xxx/.gradle/caches/artifacts-24/filestore/javax.inject/javax.inject/1/jar/6975da39a7040257bd51d21a231b76c915872d38/javax.inject-1.jar
/Users/xxx/.gradle/caches/artifacts-24/filestore/aopalliance/aopalliance/1.0/jar/235ba8b489512805ac13a8f9ea77a1ca5ebe3e8/aopalliance-1.0.jar
/Users/xxx/.gradle/caches/artifacts-24/filestore/asm/asm/3.1/jar/c157def142714c544bdea2e6144645702adf7097/asm-3.1.jar
/Users/xxx/.gradle/caches/artifacts-24/filestore/org.sonatype.sisu.inject/cglib/2.2.1-v20090111/jar/7ce5e983fd0e6c78346f4c9cbfa39d83049dda2/cglib-2.2.1-v20090111.jar
/Users/xxx/.gradle/caches/artifacts-24/filestore/com.google.inject/guice/3.0/jar/28586dc97c525501329d9a242fc3402041e3572d/guice-3.0-no_aop.jar

A: That is correct. Gradle won't put the jars in the lib directory. The assumption is that your lib directory is for manual changing jars. You can probably create a Gradle task to copy them to your lib directory if thats what oyu want to do.
I don't think there is official support for gradle in eclipse, and if you're just starting out a new project, consider using Android Studio (http://developer.android.com/sdk/installing/studio.html)

A: The following post includes two Groovy fragments which can be added to build.gradle. Either of them makes gradle dependencies available to Eclipse.
See Add dependencies via gradle to eclipse in android project


text:
Q: Using a python script to run a shell script (containing a make file and an executable for fortran) I am trying to execute a shell script using python. The shell script contains variables (which I want to set in the python script itself), a make file and an executable file for fortran. Is it possible to be done using python?
I tried with the following python code but unfortunately it does not work:
import subprocess import os import shutil

os.environ['FLUID'] ="MDM"
os.environ['TTYPE'] = str(0)
os.environ['FLIBRARY'] = "RefProp"
HSPACE=[0.01, 0.009, 0.008, 0.007]

os.chdir(tmesh_dir)

subprocess.call(['./testfile3', str(FLUID), str(TTYPE), str(FLIBRARY)]
+ [str(n) for n in HSPACE])

testfile3 is a shell script which has the following contents:
fluid=$1; shift
ttype=$2; shift
flibrary=$3; shift
hspace=( "$@" )

make clean
make -j2

./vls.exe <<<"$fluid, $flibrary"

for i; do

cd Db

awk -v a="$i" 'NR==8 {$1="     " a }1' spacingcontrol.vls > tmp.vls && mv tmp.vls spacingcontrol.vls
awk -v b="$i" 'NR==8 {$2="  " b "      "}1'  spacingcontrol.vls > tmp.vls && mv tmp.vls spacingcontrol.vls

done

cd ..
umg/mcrv.exe
umg/bgrid.exe
umg/umg2d.exe

#make clean

A: You can use subprocess.Popen, which allows you to pass in a set of environment variables to the process.  You can also specify the working directory for the subprocess instead of changing the current one.
env = dict(os.environ)
env['FLUID'] ="MDM"
env['TTYPE'] = str(0)
env['FLIBRARY'] = "RefProp"
HSPACE=[0.01, 0.009, 0.008, 0.007]

cmd = ['./testfile3', env['FLUID'], env['TTYPE'], env[FLIBRARY]]
cmd.extend([str(n) for n in HSPACE])

p = subprocess.Popen(cmd, env=env, cwd=tmesh_dir)


text:
Q: Slide effect for drop menu with css and jquery I got a menu which I try to make responsive for smartphones.
I successfully did the drop down menu, but right now it doesn't have any effect and it just pop up when you press the bar icon.
I want to have the effect of slide down as you press on the bar icon.
pictures to explain better:

html and css:

html {
  font-family: Verdana, Geneva, Tahoma, sans-serif;
}

body {
  padding: 0;
  margin: 0;
  background: #eee;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  margin: 0;
  padding: 0;
}

ul,
ol {
  padding: 0;
  margin: 0;
}

nav {
  background: #cecece;
  display: flex;
}

.logo {
  flex-grow: 2;
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo .bar {
  display: none;
}

nav ul {
  flex-grow: 10;
  list-style: none;
  display: flex;
}

nav ul li {
  flex-grow: 1;
}

nav a {
  text-decoration: none;
  padding: 30px;
  display: block;
  text-align: center;
  color: black;
}

nav a:hover {
  background: #8d8d8d;
  color: #ffff;
}

@media (max-width: 768px) {
  nav {
    flex-direction: column;
  }

  .logo {
    padding: 20px;
    background: rgb(122, 122, 122);
    justify-content: space-between;
  }

  .logo .bar {
    display: block;
  }

  .logo .bar:hover {
    cursor: pointer;
  }

  nav ul {
    height: 0;
    flex-direction: column;
    overflow: hidden;
    transition: 0.5s;
  }

  nav ul.active {
    height: auto;
  }

  nav ul li a {
    padding: 10px;
    text-align: left;
  }
}

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <link rel="stylesheet" href="test2.css" />

    <link
      rel="stylesheet"
      href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"
    />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
    />

TestLogo

link

link

link

link

link

link

appreciate any help!

A: set height value of ul modificator '.active' in pixels
css transition does not understand auto parameter
for deeper understanding of this problem read an article https://css-tricks.com/using-css-transitions-auto-dimensions/
here is a quoute from it:

auto values have been intentionally excluded from the CSS transitions
  spec. It looks like it's been requested by a few people, but when you
  think about it, it makes at least a little sense that it hasn't been
  included. The browser process that re-calculates the sizes and
  positions of all elements based on their content and the way they
  interact with each other (known as "reflow") is expensive. If you were
  to transition an element into a height of auto, the browser would have
  to perform a reflow for every stage of that animation, to determine
  how all the other elements should move. This couldn't be cached or
  calculated in a simple way, since it doesn't know the starting and/or
  ending values until the moment the transition happens. This would
  significantly complicate the math that has to be done under the hood
  and probably degrade performance in a way that might not be obvious to
  the developer.

Anyway the best solution for your situation is manipulating transform: scaleY css property from 0 to 1 because this will do not trigger browser reflows


text:
Q: IShellDisptach: Why does FolderItemVerbs::Release() + CoUninitialize() crash? I'm having a very bizarre problem with the IShellDispatch COM interface, more specifically with the FolderItemVerbs object, that drives me nuts!
Calling FolderItemVerbs::Release() followed by CoUninitialze() will result in crash. It's clearly reproducible, but only happens 1 out of 10 times.
The crash is an "0xC0000005: Access Violation" error. Running the problematic code in a loop 100% reproduces the crash sooner or later :-(
Please see the example program:
static int TestProc(const TCHAR *pcDirectoryName, const TCHAR *pcFileName)
{
    int iSuccess = 0;

    IShellDispatch *pShellDispatch = NULL;
    Folder *pFolder = NULL; FolderItem *pItem = NULL;
    FolderItemVerbs *pVerbs = NULL;

    HRESULT hr = CoCreateInstance(CLSID_Shell, NULL, CLSCTX_INPROC_SERVER, IID_IShellDispatch, (void**)&pShellDispatch);
    if(FAILED(hr) || (pShellDispatch ==  NULL))
    {
        iSuccess = -3;
        return iSuccess;
    }

    variant_t vaDirectory(pcDirectoryName);
    hr = pShellDispatch->NameSpace(vaDirectory, &pFolder);
    if(FAILED(hr) || (pFolder == NULL))
    {
        iSuccess = -4;
        pShellDispatch->Release();
        return iSuccess;
    }

    variant_t vaFileName(pcFileName);
    hr = pFolder->ParseName(vaFileName, &pItem);
    if(FAILED(hr) || (pItem == NULL))
    {
        iSuccess = -5;
        pFolder->Release();
        pShellDispatch->Release();
        return iSuccess;
    }

    hr = pItem->Verbs(&pVerbs);
    if(FAILED(hr) || (pVerbs == NULL))
    {
        iSuccess = -6;
        pItem->Release();
        pFolder->Release();
        pShellDispatch->Release();
        return iSuccess;
    }

    /* Here we would do something with the FolderItemVerbs */

    pVerbs->Release(); pVerbs = NULL; //If this line is commented out, we don't get a crash, but a massive memory leak!
    pItem->Release(); pItem = NULL;
    pFolder->Release(); pFolder = NULL;
    pShellDispatch->Release(); pShellDispatch = NULL;

    iSuccess = 1;
    return iSuccess;
}

//-----------------------------------------------------------------------------

static unsigned __stdcall ThreadProc(void* pArguments)
{
    HRESULT hr = CoInitialize(NULL);
    if((hr == S_OK) || (hr == S_FALSE))
    {
        threadParam_t *params = (threadParam_t*) pArguments;
        params->returnValue = TestProc(params->pcDirectoryName, params->pcFileName);
        CoUninitialize();
    }
    else
    {
        if(threadParam_t *params = (threadParam_t*) pArguments)
        {
            params->returnValue = -10;
        }
    }

    return EXIT_SUCCESS;
}

Please download the complete example code is here:
http://pastie.org/private/0xsnajpia9lsmgnlf2afa
Please also note that I unambiguously tracked down to crash to FolderItemVerbs, because if I never create the FolderItemVerbs object, the crash is gone immediately.
Also if I never call "pVerbs->Release()" before CoUninitialize() the crash is gone too, but this will result in a massive memleak, obviously.
Another strange thing is that the crash will NOT happen, if I run the program under the Debugger! But I can run the program, wait for the crash and then let the Debugger handle the crash.
Unfortunately the Stack Trace that I get then doesn't help much:
http://pastie.org/private/cuwunlun2t5dc5lembpw
I don't think I'm doing anything wrong here. I have checked the code over and over again in the last two days. So this all seems to be a bug in FolderItemVerbs!
Has anybody encountered this before and/or can confirm that this is a bug in FolderItemVerbs? Also, is there any workaround for the problem?
Thanks in advance !!!

A: Thanks everybody!
Here is the "corrected" code which performs explicit message dispatching:
void DispatchPendingMessages(void)
{
    const DWORD uiTimeout = GetTickCount() + 10000;
    const HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    unsigned int counter = 0;
    if(hEvent)
    {
        for(;;)
        {
            MSG Message;
            while(PeekMessage(&Message, NULL, WM_NULL, WM_NULL, PM_REMOVE))
            {
                TranslateMessage(&Message);
                DispatchMessage(&Message);
            }
            const DWORD nWaitResult = MsgWaitForMultipleObjects(1, &hEvent, FALSE, 250, QS_ALLINPUT | QS_ALLPOSTMESSAGE);
            if((nWaitResult == WAIT_TIMEOUT) || (nWaitResult == WAIT_FAILED) || (GetTickCount() >= uiTimeout)) break;
        }
        CloseHandle(hEvent);
    }
}

//-----------------------------------------------------------------------------

static int TestProc(const TCHAR *pcDirectoryName, const TCHAR *pcFileName)
{
    int iSuccess = 0;

    IShellDispatch *pShellDispatch = NULL;
    Folder *pFolder = NULL; FolderItem *pItem = NULL;
    FolderItemVerbs *pVerbs = NULL;

    HRESULT hr = CoCreateInstance(CLSID_Shell, NULL, CLSCTX_INPROC_SERVER, IID_IShellDispatch, (void**)&pShellDispatch);
    if(FAILED(hr) || (pShellDispatch ==  NULL))
    {
        iSuccess = -3;
        return iSuccess;
    }

    variant_t vaDirectory(pcDirectoryName);
    hr = pShellDispatch->NameSpace(vaDirectory, &pFolder);
    if(FAILED(hr) || (pFolder == NULL))
    {
        iSuccess = -4;
        pShellDispatch->Release();
        return iSuccess;
    }

    variant_t vaFileName(pcFileName);
    hr = pFolder->ParseName(vaFileName, &pItem);
    if(FAILED(hr) || (pItem == NULL))
    {
        iSuccess = -5;
        pFolder->Release();
        pShellDispatch->Release();
        return iSuccess;
    }

    hr = pItem->Verbs(&pVerbs);
    if(FAILED(hr) || (pVerbs == NULL))
    {
        iSuccess = -6;
        pItem->Release();
        pFolder->Release();
        pShellDispatch->Release();
        return iSuccess;
    }

    /* Here we would do something with the FolderItemVerbs */

    pVerbs->Release(); pVerbs = NULL;
    pItem->Release(); pItem = NULL;
    pFolder->Release(); pFolder = NULL;
    pShellDispatch->Release(); pShellDispatch = NULL;

    iSuccess = 1;
    return iSuccess;
}

//-----------------------------------------------------------------------------

static unsigned __stdcall ThreadProc(void* pArguments)
{
    HRESULT hr = CoInitialize(NULL);
    if((hr == S_OK) || (hr == S_FALSE))
    {
        threadParam_t *params = (threadParam_t*) pArguments;
        params->returnValue = TestProc(params->pcDirectoryName, params->pcFileName);
        DispatchPendingMessages(); //This is required before CoUninitialize() to avoid crash with certain Shell Extensions !!!
        CoUninitialize();
    }
    else
    {
        if(threadParam_t *params = (threadParam_t*) pArguments)
        {
            params->returnValue = -10;
        }
    }

    return EXIT_SUCCESS;
}

Couldn't reproduce the crash with that code so far :-)


text:
Q: Django Haystack index on multiple fields from same model I am trying to embed elasticsearch in my Django app using django-haystack. I am trying to implement a user search. My user model is this:
class MyUser(AbstractBaseUser):
    username = models.CharField(max_length=255, unique=True)
    name = models.CharField(max_length=63, blank=True)
    email = models.EmailField(blank=True, unique=True)
    status = models.CharField(max_length=255, blank=True, null=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    joined = models.DateTimeField(auto_now_add=True, null=True)

Now, I want to search on name and username fields. I have created the following search_indexes.py:
class UserIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.EdgeNgramField(document=True, model_attr='name')
    username = indexes.CharField(model_attr='username')

    def get_model(self):
        return MyUser

    def get_updated_field(self):
        return "joined"

However, when I perform a search, I only get the results matching the name field. What am I doing wrong here? Is there some other way to do this?
Thanks in advance.

A: The way django-haystack works, the data inside the document=True field is used for a general search, and any other fields are used for individual filtering. So in your case, a search will only use the name field. To fix this, you'll need to use a template that specifies all the fields to be used in a search. First of all, use:
text = indexes.EdgeNgramField(document=True, use_template=True)

Then you'll need to create a new template inside your template directory called search/indexes/myapp/myuser_text.txt and place the following inside:
{{ object.username }}
{{ object.name }}

See http://django-haystack.readthedocs.org/en/latest/tutorial.html#handling-data for full reference


text:
Q: How to get a list of leafs in this tree? Problem in OCaml We are given a tree with the type:
type ('nonterminal, 'terminal) parse_tree =
  | Node of 'nonterminal * ('nonterminal, 'terminal) parse_tree list
  | Leaf of 'terminal

and the form of:
let t = (Node ("+", [Leaf 3; Node ("*", [Leaf 4; Leaf 5])])

And we are asked to write a function that takes a tree as an argument and returns a list of leafs that it finds (form left to right) so leaves t = [3;4;5]
Now this is what I have but it gives me an error and I am unsure on how should I approach this problem:
let rec getleaf tree =
  match tree with
  |Leaf a -> [a]
  | Node (a, Leaf (h)::t) -> h::getleaf t;;

Thank you in advance.

A: A list pattern h :: t binds h to the head of the list (a single element) and t to the tail of the list (which is itself a list). So the name t in your code is going to match a list of parse trees. But getleaf is expecting a single parse tree as its argument.
Update
The usual thing to do would probably be to have getleaf accept a single tree. In the code for Node you would have to have an arbitrary number of recursive calls that you then combine to produce the result for that one node.
The most idiomatic way to handle the multiple recursive calls would be with a fold (IMHO). You can also use List.map (which would give a list of lists), then List.concat to get back to a single list. This is easier to think about (IMHO) but it does some unnecessary computation.
You might want to think about whether you need to maintain the order of the leaves.


text:
Q: Random Selection of value in a dynamic dropdown list using robot framework Is it possible to randomly select a value from a dropdown list using robot framework?
My scenario is as follows:

*

*I have this element with xpath of //*[@id='companyName']. All values here are populated upon creation of company, so all created companies are listed in that Dropdown list.

*That element belongs to another form/page which is the creation of facility, is it possible to create a facility wherein selected company can be randomized?

Sorry for the noob question, just a newbie in robot framework :D


text:
Q: Nested JSON and Pandas Normalise I have some JSON data returned as below: (I cannot change the structure)
[
  {
    "id": "d6aca8ac",
    "owner": "test",
    "sections": {
      "summary": {
        "id": "d417cd0e",
        "notes": "",
        "created_at": "2018-11-26T19:02:06Z"
      },
      "weather": {
        "id": "7ef34660",
        "notes": ""
      },
      "task": {
        "id": "255d86dc",
        "tasks": [
          {
            "id": "t1",
            "total_hours": 176.0,
            "updated_at": "2018-11-26T19:02:06Z",
            "created_at": "2018-11-26T19:02:06Z"
          },
          {
            "id": "t2",
            "total_hours": 176.0,
            "updated_at": "2018-11-26T19:02:06Z",
            "created_at": "2018-11-26T19:02:06Z"
          }
        ]
      }
    }
  }
]

I am trying to use json_normalise from pandas to get the tasks into a dataframe like this:
+----+-------------+----------------------+----------------------+
| id | total_hours |      updated_at      |      created_at      |
+----+-------------+----------------------+----------------------+
| t1 |         176 | 2018-11-26T19:02:06Z | 2018-11-26T19:02:06Z |
| t2 |         176 | 2018-11-26T19:02:06Z | 2018-11-26T19:02:06Z |
+----+-------------+----------------------+----------------------+

I have a script that iterates over hundreds of JSON files in a folder applying a different record path depending on the filename and this works for them all except this one structure so I would really like to see if I can get this result using something similar (this doesn't work obviously):
normalised_data = json_normalize(data=json_data, record_path=['sections', 'task', 'tasks'], meta=['id'], meta_prefix='parent_' , errors='ignore')

If that style of command cant be used then what would be my best option? So I'll have to think about separating out this particular file.
Thanks,

A: By not using a nested list for your record_path, all of the following paths are actually trying to index the keys returned by the first path, which are strings, so I'm assuming you're getting a TypeError.
You must define the entire path in its own sublist:
pd.io.json.json_normalize(json_data, record_path=[['sections', 'task', 'tasks']])

             created_at  id  total_hours            updated_at
0  2018-11-26T19:02:06Z  t1        176.0  2018-11-26T19:02:06Z
1  2018-11-26T19:02:06Z  t2        176.0  2018-11-26T19:02:06Z


text:
Q: RedirectMatch file not found So, I have in my web root an admin.php file and I want every time someone writes /admin to be redirected to that /admin.php.
I wrote in my htaccess

RedirectMatch 301 ^/admin$ /admin.php

However, I get an error from apache "file not found".
I created an empty /admin folder and it works...

Then I try to have an other (also non existant folder) to redirect to admin.php. So I write

RedirectMatch 301 ^/blah$ /admin.php

and it works...

Finally I delete the admin.php and I have the thing redirected to another .php

RedirectMatch 301 ^/admin$ /index.php

and it works again...

I understand that for some reason apache messes things up when the folder to be redirected from has the same name with the .php
With Rewrite I can do the redirection without any problems but I was wondering if it was also possible with just a Redirect... Maybe I am missing something here...

A:
apache messes things up when the folder to be redirected from has the same name with the .php

This is due to Apache's content negotiation module that runs before mod_rewrite, mod_alias and makes Apache web server match extensions of files. e.g. /file can be in URL but it will serve /file.php.
To fix this behavior disable MultiViews by placing this rule on top of your .htaccess:
Options -MultiViews


text:
Q: Gulpfile end of task with two different operations I am kind of lacking imagination on that one.
My goal is to retrieve a json object so I can run a replace string on all the files I want to translate, I have looked into a lot of translation libraries but this way is the best i can think of for my use.
Anyway my issue here is Once I got my json object, I have to run on all the files and when it is done, finish the task 'trad'.
I have done some research and tried a lot of things but there is something that I miss, something that I didn't understood about the good way to do that ?
Please help !
    gulp.task('trad', gulp.series( 'createTradFile', 'copyBeforeTrad',  function( done ) {
    var data = require('gulp-data');
    var path = require('path');
    var fs = require('fs');
    var replace2 = require('gulp-string-replace');
    var transObj = null;

    var translateAll = function()
    {
        var files = gulp.src(['fr/**/*.html', 'fr/**/*.js']);

        for (var k in transObj)
        {
            if (transObj[k].ID)
            {
             console.log("TRAD " + transObj[k].ID + " TO " + transObj[k].LANG1);

                files.pipe(replace2(new RegExp('\\+' + transObj[k].ID + '\\+', 'g'),
                                    transObj[k].LANG1,
                                    {'logs': {'enabled': true}}))
                .pipe(chmod(755));
            }
        }
        files.pipe(gulp.dest("fr"))
             .on('end', done);
    };

    gulp.src('distTemp/wording.json')
                .pipe(data(function(file) {
                    transObj = JSON.parse( fs.readFileSync('distTemp/' + path.basename(file.path)));
                    console.log("TRAD first part OK");
                    translateAll();
                 }));
   }));

So this code will translate like I want it too, but the task does not end :
[16:38:34] The following tasks did not complete: trad, <anonymous>
[16:38:34] Did you forget to signal async completion?

A: So, after a bit of research I found this ( almost crappy ) solution, which do the trick ( please answer if you hava a better solution )
var transObj = null;

gulp.task("retrieveTradObject", function(){
var data = require('gulp-data');
var path = require('path');
var fs = require('fs');

return gulp.src('distTemp/wording.json')
            .pipe(data(function(file) {
                transObj = JSON.parse( fs.readFileSync('distTemp/' + path.basename(file.path)));
                console.log("TRAD first part OK");
             }));
});

gulp.task('trad', gulp.series( 'createTradFile', 'copyBeforeTrad', 'retrieveTradObject',  function( done ) {

var replace2 = require('gulp-string-replace');

var files = gulp.src(['fr/**/*.html', 'fr/**/*.js']);

for (var k in transObj)
{
    if (transObj[k].ID)
    {
     console.log("TRAD " + transObj[k].ID + " TO " + transObj[k].LANG1);

        files = files.pipe(replace2(new RegExp('\\+' + transObj[k].ID + '\\+', 'g'),
                            transObj[k].LANG1,
                            {'logs': {'enabled': true}}))
        .pipe(chmod(755));
    }
}
files.pipe(gulp.dest("fr"));
return files;
}));

So main idea here was to separate the two promises into task ( mainly for a better understanding of the code for later ) and then to do the files = files.pipe( ... ) Which is explained here : How to create repeating pipe in gulp?
Hope this can help !

A: I'm not sure I understand the question 100% so I'll take the dv's, but are talking about something like gulp-run-sequence?
You can do all sorts of tasking stuff like this
var gulp = require('gulp');
//webp images for optimization on some browsers
const webp = require('gulp-webp');
//responsive images!
var responsive = require('gulp-responsive-images');
//gulp delete for cleaning
var del = require('del');
//run sequence to make sure each gulp command completes in the right order.
var runSequence = require('run-sequence');
// =======================================================================//
// !                Default and bulk tasks                                //
// =======================================================================//
//default runs when the user types 'gulp' into CLI
//first clean is ran, then webp, then the rest are ran async.
//If you want something ran after, you can add something like 'example'
gulp.task('default',function(callback){
    runSequence('clean','webp',['responsive-jpg','responsive-webp','copy-data','copy-sw'],'example'),callback
});
// =======================================================================//
//                  Images and fonts                                      //
// =======================================================================//
gulp.task('responsive-jpg',function(){
    gulp.src('src/images/*')
    .pipe(responsive({
        '*.jpg':[
        {width:1600, suffix: '_large_1x', quality:40},
        {width:800, suffix: '_medium_1x', quality:70},
        {width:550, suffix: '_small_1x', quality:100}
    ]
    }))
    .pipe(gulp.dest('build/images'));
});
gulp.task('responsive-webp',function(){
    gulp.src('src/images/*')
    .pipe(responsive({
        '*.webp':[
        {width:1600, suffix: '_large_1x', quality:40},
        {width:800, suffix: '_medium_1x', quality:70},
        {width:550, suffix: '_small_1x', quality:80}
    ]
    }))
    .pipe(gulp.dest('build/images'));
});
gulp.task('webp', () =>
    gulp.src('src/images/*.jpg')
        .pipe(webp())
        .pipe(gulp.dest('src/images'))
);
gulp.task('copy-data', function () {
    gulp.src('./src/data/*.json')
        .pipe(gulp.dest('./build/data'));
});
gulp.task('copy-sw', function () {
    gulp.src('./src/sw.js')
        .pipe(gulp.dest('./build/'));
});

In my example here, I clear out old files, then I convert any images that need to be converted to webp, then I async the tasks that can be run together. You can do this in any arrangement you need. You could create then a gulp task that even points to two gulp run sequence tasks to double down on the effectiveness.