text:
Q: How to reorder rows by a condition in pandas? I have two dataframes and one of their orders is correct for me. I want to make the other's order the same as the correct one. Here is the point, it's not about index numbers, order depends on a variable. Like this
df1
A   B
13  2
20  5
15  3
.   .
.   .

df2
A   B
15  3
13  2
20  5
.   .
.   .

I want the order of df2 to be same as df1, I put them in a for loop but it took long time (my real data is much greater than reproducible example)
Is there any easier way to make my wish real ? Thanks in advice.

A: The best way I can think is to replace the index of df2 by column A and then call it with loc:
df1 = pd.DataFrame({"A": [13,20,15], "B": [2,5,3]})
df2 = pd.DataFrame({"A": [15,13,20], "B": [3,2,5]})
df2 = df2.set_index("A")
print(df2.loc[df1["A"]])

output is:
    B
A
13  2
20  5
15  3

Is this ok for you?


text:
Q: Валидация данных передаваемых в процедуру Имеется сторонняя система, которая вызывает процедуру на SQL Server.
Проблема в том, что данные могут содержать одинарную кавычку, что вызовет ошибку.
Имеется ли способ от этого защититься (валидировать), чтобы не получать ошибки?
Пример:
execute PRC @abc = '{"code": "500 Internal Server Error","status": "'Unable to complete the operation')"}'

Разумеется возвратит
Msg 102, Level 15, State 1, Line 1

Incorrect syntax near 'Unable'.

A: Просто перед передачей строки выполните функцию ЗАМЕНЫ одной одинарной кавычки на две одинарных кавычки.
Например @abc = ЗАМЕНИТЬ(@abc, "'", "''")
execute PRC @abc = '{"code": "500 Internal Server Error","status": "''Unable to complete the operation'')"}'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android refresh IMediaPlaybackService current song content I make a simple example to let you understand what I need to do:
1) I open an unknown song (a song where I deleted all ID3 Tags) so IMediaPlaybackService don't have an user-friendly information
2) I update song information adding ID3 file
3) Current IMediaPlaybackService service don't have updated information about the current song and will always display old data, if I go to next song and than to prev song, it will have updated information.
But, is there a way to not use that workaround and tell to IMediaPlaybackService to refresh current song information?


text:
Q: how to have list of all tables in a database with dbo schema? i do this with filter table in object explorer but i want do this with query
and when i execute the query,returns all tables with dbo schema and their fields.

A: Returns from sys.tables , use schema_id to filter
SELECT '['+SCHEMA_NAME(schema_id)+'].['+name+']'
AS TableName
FROM sys.tables where SCHEMA_NAME(schema_id) = 'dbo'

To Include Views in Schema
SELECT '['+SCHEMA_NAME(schema_id)+'].['+name+']'
AS TableName
FROM sys.tables where SCHEMA_NAME(schema_id) = 'dbo'

UNION

SELECT '['+SCHEMA_NAME(schema_id)+'].['+name+']'
AS TableName
FROM sys.views where SCHEMA_NAME(schema_id) = 'dbo'

A: Are you trying to get this information?
SELECT * FROM sys.tables WHERE schema_id = 1
--SchemaId 1 is for 'dbo' schema

If you want columns as well, then try this.
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo'

A: To get All the Table, Schema, Columns and data Type in database use below query.
select TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,DATA_TYPE from INFORMATION_SCHEMA.COLUMNS


text:
Q: OpenGL vertex at NDC (-1.0, -1.0) is at what sub-pixel position? If in a shader I create a 2D vertex at position (x: -1.0 y: -1.0) directly in NDC, does that create the vertex at the center of the bottom-left pixel on screen, or at the bottom-left corner of that pixel?
I'm trying to align a quad to be drawn with perfect pixel position and size and can't figure out where the vertex is placed in the sub-pixel, the center or the edge.

A: (-1,-1) is at the bottom-left corner of the bottom-left pixel.
(+1,+1) is at the top-right corner of the top-right pixel.


text:
Q: UI5: VizFrame - are dashed lines possible? Are dotted or dashed lines possible with VizFrame [sap.viz.ui5.controls.VizFrame] (in case of line charts, in my case timeseries_line)? If yes, how? If no, are there workarounds or alternatives?
Is it possible to change between solid and dashed over time?

A: Yes it is possible, please look here, choose plotArea and after that dataPointStyle. You should set lineType property to "dotted".


text:
Q: Function objects with variadic template How can I define a function object that can be passed to apply? Ultimately, I want a function F f that can take all the elements of the tuple and push them back t a vector.
template <class F, size_t... Is>
constexpr auto index_apply_impl(F f, index_sequence<Is...>) {
    return f(integral_constant<size_t, Is> {}...);
}

template <size_t N, class F>
constexpr auto index_apply(F f) {
    return index_apply_impl(f, make_index_sequence<N>{});
}

template <class Tuple, class F>
constexpr auto apply(Tuple t, F f) {
    return index_apply<tuple_size<Tuple>{}>(
        [&](auto... Is) { return f(get<Is>(t)...); });
}

Thanks :)

A: You can use the expander trick.  This needs C++14 though.  I don't know what your byte array format looks like, so I just took a generic struct with a string member and convert everything to string in the constructor.
#include <iostream>
#include <string>
#include <tuple>
#include <vector>

template < typename T, typename F, size_t ... Is >
void for_each_impl(T&& t, F&& f, std::index_sequence<Is...>)
{
  using expand_type = int[];
  (void) expand_type { 0, ( (void) f(std::get<Is>(t)), 0) ... };
}

template < typename... Args, typename F >
void for_each(std::tuple<Args...> const& t, F&& f)
{
  for_each_impl(t, f, std::make_index_sequence<sizeof...(Args)>{});
}

struct Bytes {
  std::string str;
  Bytes(char const * c) : str(c) {};
  Bytes(int i) : str(std::to_string(i)) {};
  Bytes(char c) : str(1, c) {};
};

int main()
{
  auto t = std::make_tuple(12, "abc", 10, 'c', 1);
  std::vector<Bytes> v;
  for_each(t, [&v](auto&& x){ v.push_back(x); });

  for (auto const& e : v)
    std::cout << e.str << ' ';
  std::cout << '\n';
}

Live example

In C++17 it is much easier, thanks to variadic lambda, fold expression, and std::apply.
#include <iostream>
#include <string>
#include <tuple>
#include <vector>

struct Bytes {
  std::string str;
  Bytes(char const * c) : str(c) {};
  Bytes(int i) : str(std::to_string(i)) {};
  Bytes(char c) : str(1, c) {};
};

int main()
{
  auto t = std::make_tuple(12, "abc", 10, 'c', 1);
  std::vector<Bytes> v;
  std::apply([&v](auto&&... x){ (... , v.push_back(x)); }, t);

  for (auto const& e : v)
    std::cout << e.str << ' ';
  std::cout << '\n';
}

Live example

If you cannot use C++11 your life will be painful.  You have to roll your own implementation of index_sequence and you have to define a helper struct with templated call operator to substitute the generic lambda.
#include <iostream>
#include <string>
#include <tuple>
#include <vector>

// https://stackoverflow.com/a/24481400/1944004
template <size_t ...I>
struct index_sequence {};

template <size_t N, size_t ...I>
struct make_index_sequence : public make_index_sequence<N - 1, N - 1, I...> {};

template <size_t ...I>
struct make_index_sequence<0, I...> : public index_sequence<I...> {};

// Call a function for each element in a tuple

template < typename T, typename F, size_t ... Is >
void for_each_impl(T&& t, F&& f, index_sequence<Is...>)
{
  using expand_type = int[];
  (void) expand_type { 0, ( (void) f(std::get<Is>(t)), 0) ... };
}

template < typename... Args, typename F >
void for_each(std::tuple<Args...> const& t, F&& f)
{
  for_each_impl(t, f, make_index_sequence<sizeof...(Args)>{});
}

// "Byte array" emulation

struct Bytes {
  std::string str;
  Bytes(char const * c) : str(c) {};
  Bytes(int i) : str(std::to_string(i)) {};
  Bytes(char c) : str(1, c) {};
};

// Surrogate template lambda

struct Visitor
{
  std::vector<Bytes>& v;
  Visitor(std::vector<Bytes>& vb) : v(vb) {};
  template < typename T >
  void operator() (T&& x) { v.push_back(x); }
};

int main()
{
  auto t = std::make_tuple(12, "abc", 10, 'c', 1);
  std::vector<Bytes> v;
  for_each(t, Visitor(v));

  for (auto const& e : v)
    std::cout << e.str << ' ';
  std::cout << '\n';
}

Live example


text:
Q: git-stitch-import: how to make one master branch? I am trying to merge several git repos into a new repo, with each old repo as a subdirectory in the new repo.  git-stitch-repo appears to be the tool I want.
However, the documentation is less than clear.  I was able to follow it (https://metacpan.org/pod/distribution/Git-FastExport/script/git-stitch-repo) until the part which says "It is now possible to create the master branch and have it point at the right commit, and delete the two master-A and master-B branches."
What is the "right commit", and how do I execute these steps?
Right now I have several branches labeled master-A, master-B, etc., which seem to correspond to the original repos.  What I really wanted was just a master branch that contains everything.  It sounds possible to get there, but I don't know how.

A: I'm the author of git-stitch-repo. Given your description, it is indeed the tool you're looking for.
Here's how the program works:

*

*it looks at all commits obtained from the output of git fast-export for each repository to merge and builds a new stream for git fast-import

*in the new stream, a commit can be given a commit from any of the other repository as a parent

*the program makes sure that if you would filter out all the commits from the other repositories, you'd get back the original repository

Because all repositories can have references with the same name, the program add -A, -B, etc. at the end of the references names, so you can know which repository each reference in the new repository comes from. This is why you get master-A and master-B. Picking the "right" master just means deciding which of master-A and master-B is your new master.
The biggest issue with the current version (I'm currently working on a fix), is that for every branch point in repository A, the system must decide on which side to attach the next commit from repository B (if there is actually an alternative between several valid commits that respect the constraints of the stitching algorithm.
If all options are valid, the choice is basically random. And then master-A and master-B can end on different branches, which is usually not what you want. (This is what RT #70695 is all about.)
As I said above, I'm working on a fix, and I have a good hope that it's going to fix your issue. I expect to be able to do a new release withing a few days.

A: If you don't mind having multiple roots, you can do this (per sub-project):

*

*go into the sub-project - we'll call it project 'foo'

*make a 'foo' folder in there (we want everything contained by project name)

*git mv everything at the root into that root 'foo' folder

*commit the changes

Now in the master project (presuming you want to merge both 'master' branches):

*

*git remote add foo /path/to/foo/project

*git fetch foo

*from the master project's master branch do git merge foo:master
This will create a merge commit, and from that point on you'll have everything from the foo sub-project in a 'foo' folder in the master project. Before that merge point you'll be on either of the two separate trees. It doesn't make sense for their histories to intermingle, so this is a fine way to set things up, wherein the two trees only connect at the point you decided to merge them.
If you want all of the history of each sub-project to merge in...
This is quite a bit more difficult. The basic idea is that you'd choose the latest commit from the master project and rebase the entire sub-project onto that point, so the whole sub-project - i.e. all of its commits - grow out from that point, and then you'd merge the head of the sub-project back into the master project, maybe with --no-ff (no fast-forward) so you could see the whole sub-project in a commit bubble. This requires that all of the history of the sub-project be in the project-name subfolder (i.e. 'foo' from the first section).
This would require a ton of manual work, or something with git filter-branch that I'd have to work on for awhile - I can't come up with it off the top of my head. I'm guessing it would be a --tree-filter, and you'd have to move everything that wasn't in the 'foo' folder into it per commit. I don't know how this handles branches and merges in the project, but I suspect it works. I'll refrain from trying to figure this out in case you're fine with the first suggestion with multiple roots (I think it's the better option of the two).
If you don't mind multiple roots, but want to be able to send work back upstream...
If this is it for the sub-projects - they're going into this repo forever, and will never see the light of day again, either of the first two variations would be fine. If you occasionally want to push things back upstream, you should look into git submodules and subtrees.
Submodules essentially let you clone a repo into a particular folder in your project. Your project only tracks which commit it should be on. When you clone your main repo, the submodule folder won't exist. You can pull it in by doing git submodule init to create the folder, and git submodule update to pull in all the files.
Subtrees go a step further and read the entire sub-project directly into a folder of your choosing in the main repo. From that point on, that folder exists just like any other in your project. Most of the magic here comes from subtree merging, which allows you to pull in changes from the sub-project without all the history, and push changes back out the other way.
Given the option of all 3, I'd prefer to use submodules or subtrees. They're the clean way to handle merging repos together.


text:
Q: Why do I not see changes issued through an update query with Spring Data JPA? I have the following service:
@Service
public class CamelService {

    @Transactional
    public aCamelThing() {

          Camel camel = this.camelRepository.findOne(1);

          System.out.println(camel.getCamelName());  // prints "normalCamel"

          // simple hql set field 'camelName'
          int res = this.camelRepository.updateCamelName(1,"superCamel!");

          Camel camelWithNewName = this.camelRepository.findOne(1);

          System.out.println(camelWithNewName .getCamelName());  // prints "normalCamel" ?!?!?

    }
}

Any idea how can i achieve the goal that the second println will print: "superCamel!" ?
(separating the second call to a new transaction is not ideal).

A: The reason you see this working as it works is quite simple: JPA is defined to work that way.
I am assuming you trigger an update query for updateCamelName(…). The JPA specification states the following for update and delete operations:

The persistence context is not synchronized with the result of the bulk update or delete.
Caution should be used when executing bulk update or delete operations because they may result in inconsistencies between the database and the entities in the active persistence context. In general, bulk update and delete operations should only be performed within a transaction in a new persistence con- text or before fetching or accessing entities whose state might be affected by such operations.

This means, that if you need to see the changes of such an operation you need to do the following things:

*

*Clear the EntityManager after this operation. Spring Data JPA's @Modifying annotation has a clearAutomatically flag defaulting to false. If that is set to true, invoking the query method will clear the EntityManager automatically (as the name suggests. Use that with caution, as it will effectively drop all pending changes that have not been flushed to the database yet!

*Re-obtain a fresh instance of the entity from the EntityManager. Calling findOne(…) on the repository seems like a reasonable way to do this as this roughly translates into EntityManager.find(…). Be aware that this might still hit 2nd level caches configured on the  persistence provider.

The safest way to work around this is - as the spec suggests - to use update queries only for bulk operations and fall back to the "load entity, alter, merge" approach by default.


text:
Q: Compilation error when upgraded from Angular 4 to 5 I have upgraded recently from Angular 4 to 5 and I get the following error on compilation:

The following is how my Package.json file looks after upgrade:
"dependencies": {
    "@angular/animations": "^5.2.9",
    "@angular/common": "^5.2.9",
    "@angular/compiler": "^5.2.9",
    "@angular/compiler-cli": "^5.2.9",
    "@angular/core": "^5.2.9",
    "@angular/forms": "^5.2.9",
    "@angular/http": "^5.2.9",
    "@angular/platform-browser": "^5.2.9",
    "@angular/platform-browser-dynamic": "^5.2.9",
    "@angular/platform-server": "^5.2.9",
    "@angular/router": "^5.2.9",
    "@ng-idle/core": "^2.0.0-beta.12"
    "angular2-moment": "^1.6.0",
    "atob": "^2.0.3",
    "bootstrap": "^3.3.7",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.4.1",
    "file-saver": "^1.3.3",
    "font-awesome": "^4.7.0",
    "intl": "^1.2.5",
    "ng2-toastr": "^4.1.2",
    "primeng": "^4.2.1",
    "primeui": "^4.1.15",
    "quill": "^1.3.0",
    "rxjs": "5.5.2",
    "web-animations-js": "^2.3.1",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "^1.5.0",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/language-service": "^5.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.7.0",
    "typescript": "^2.4.2"
  }

tsconfig.json:
{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  }
}

I have followed all the steps mentioned in the upgrade. I went through some of the issues posted in Git but was of no help.Could you please let me know how I could fix this issue.


text:
Q: How to change this function to get the opendatasource server name dynamically I have the next function created, a simple union from two tables, one from the current server, and the other from a remote server:
ALTER FUNCTION [dbo].[fn_AllData] ()
RETURNS @tmp TABLE
    (
    Id      int,
    Name    varchar(100)
    )
AS
BEGIN
    INSERT INTO @tmp
        SELECT Id, Name
        FROM Table1

    INSERT INTO @tmp
        SELECT Id, Name
        FROM OPENDATASOURCE('SQLOLEDB', 'Data Source=SERVER1;user id=xxx;password=yyy').Database1.dbo.Table1

    RETURN
END

--SELECT * FROM fn_AllData()

The function works fine in this way.
Now I need to obtain the server name dynamically, from another parameters table.
It should be easy like this:
DECLARE @SERVERNAME as varchar(20)

SELECT @SERVERNAME = Value
FROM Parameters
WHERE Name = 'SERVERNAME'
[...]

INSERT INTO @tmp
    SELECT Id, Name
    FROM OPENDATASOURCE('SQLOLEDB', 'Data Source=' + @SERVERNAME + ';user id=xxx;password=yyy').Database1.dbo.Table1

But Opendatasource does not accept parameters.
Is there any way to achieve my goal keeping my code in a function?

A: Try this one, i hope this works
DECLARE @SERVERNAME as NVARCHAR(20)
DECLARE @INSERTQUERY AS NVARCHAR(255)

SELECT @SERVERNAME=Value
FROM Parameters WHERE Name='SERVERNAME'

[...]

SET @INSERTQUERY = 'INSERT INTO @tmp
SELECT Id, Name FROM OPENDATASOURCE(''''SQLOLEDB'''', ''''Data Source=' + @SERVERNAME + ';user id=xxx;password=yyy'''').Database1.dbo.Table1'

EXEC (@INSERTQUERY)


text:
Q: Webdriver new DefaultWait generic I want to have method like this in my IDriver class
this.driver.WaitUntil(x => LoginForm.Displayed, TimeSpan.FromSeconds(5));

this.Driver is a IDriver field

This one does not wait for element displayed:
public void WaitUntil(Func<IDriver, bool> condition, TimeSpan timeout)
{
    var wait = new DefaultWait<IWebDriver>(this.Driver)
    {
        Timeout = timeout
    };

    bool result = wait.Until(condition);

    if (!result)
    {
        throw new Exception();
    }
}

this.Driver is a IWebDriver field in my Driver class

A: public bool WaitForWebElementToBeNotPresent(IWebElement module)
{
    var result = true;
    try
    {
        _driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2));
        if (module.Displayed)
        {
            result = true;
        }
    }
    catch (Exception)
    {
        result = false;
    }
    return result;
}


text:
Q: Check whether the request loaded in UIWebView I have a UIWebview where I'm loading a URL from the server. Everything is working well, but the page is loading slowly in the web view. While it is loading, I have to show an activity indicator.
I have done:
 NSURL *urlStr = [NSURL URLWithString:myURLString];

 NSURLRequest *req = [NSURLRequest requestWithURL:urlStr];

[webView loadRequest:req];

I have added an activity indicator like this:
activityIndicator = [[UIActivityIndicatorView alloc]init];
activityIndicator.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;

activityIndicator.frame=CGRectMake(webView.center.x,webView.center.y - 150, 60, 60);
[webView addSubview:activityIndicator];

When do I have to start and stop animating?

A: For this you will need to implement UIWebView Delegate.
You can start it in -
- (void)webViewDidStartLoad:(UIWebView *)webView

and can finish in either -
if success -
- (void)webViewDidFinishLoad:(UIWebView *)webView

if fail -
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error

A: -(void)webViewDidStartLoad:(UIWebView *)webView
{

    [activityIndicator startAnimating];
    activityIndicator.hidden = NO;

}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{

    [activityIndicator stopAnimating];
    activityIndicator.hidden = YES;

}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{

    [activityIndicator stopAnimating];
    activityIndicator.hidden = YES;

}

I think it will be helpful to you.


text:
Q: Submenu not visible in the even resizes (responsive) I'm making a submenu with jQuery.
I've got it working on screen sizes over 700 pixels wide, but when the viewport goes lower than that and again resize it bigger, the submenu goes and breaks (still works on the width under 700 pixels though).
So basically it seems like the script does not know how to return the responsive submenu back to normal after visiting the lower resolution. What am I doing wrong here?

Resolved with the line: el2.off();

jQuery
jQuery(function( $ ){

$(document).ready(function(){

    /*
    * @name: setDimensions
    * @author: *******
    * @versio: 0.1
    * @description: Vigila el tamaño de la pantalla
    * @date: 2016/04/04
    *
    * @param: none
    * @return: none
    */

    delay = 250,
    throttled = false,
    calls = 0;

    function setDimensions(){
        responsiveMenu();
    };

    // window.resize event listener
    window.addEventListener('resize', function() {
        // only run if we're not throttled
      if (!throttled) {
        // actual callback action
        setDimensions();
        // we're throttled!
        throttled = true;
        // set a timeout to un-throttle
        setTimeout(function() {
          throttled = false;
        }, delay);
      }
    });

    setDimensions();

    /*
    * @name: responsiveMenu
    * @author: *****
    * @versio: 0.1
    * @description:
    * @date: 2016/04/04
    *
    * @param: none
    * @return: none
    */
    function responsiveMenu(){

        var el = $("#menu_principal");
        var el2 = $(".levelFather");

        if (window.matchMedia("(max-width: 700px)").matches) {
            if(!el.hasClass("responsive-menu")){
                el.addClass("responsive-menu").before('

');

                $(".responsive-menu-icon").click(function(){
                    $("#menu_principal").toggleClass("openMenu");
                });
            }
            if(!el2.hasClass("responsive-submenu")){
                el2.addClass("responsive-submenu");

                el2.click(function(){
                    $(this).toggleClass("open");
                });

            }

        }else{

            if(el.hasClass("responsive-menu")){
                el.removeClass("responsive-menu");
                if(el.hasClass("openMenu")){el.removeClass("openMenu");}
                el.prev().remove();
            }

            if(el2.hasClass("responsive-submenu")){
                el2.off(); <----
                el2.removeClass("responsive-submenu");
                if(el2.hasClass("open")){el2.removeClass("open");}
            }

            $("#menu_principal").removeAttr("style");
        }

    }

}); //End $(document).ready

}); //End jQuery function

Fiddle
https://jsfiddle.net/IvanOrtiz/m4payfuo/5/


text:
Q: How to remove Left recursive in this ANTLR grammar? I am trying to parse CSP(Communicating Sequential Processes) CSP Reference Manual. I have defined following grammar rules.
assignment
    : IDENT '=' processExpression
    ;
processExpression
    :   ( STOP
        | SKIP
        | chaos
        | prefix
        | prefixWithValue
        | seqComposition
        | interleaving
        | externalChoice

        ....

seqComposition
    :   processExpression ';' processExpression
    ;
interleaving
    :   processExpression '|||' processExpression
    ;
externalChoice
    :   processExpression '[]' processExpression
        ;

Now ANTLR reports that
seqComposition
interleaving
externalChoice

are left recursive . Is there any way to remove this or I should better used Bison Flex for this type of grammar. (There are many such rules)

A: Define a processTerm.  Then write rules looking like
assignment
    : IDENT '=' processExpression
    ;
processTerm
    :   ( STOP
        | SKIP
        | chaos
        | prefix
        ...
processExpression
    :   ( processTerm
        | processTerm ';' processExpression
        | processTerm '|||' processExpression
        | processTerm '[]' processExpression

        ....

If you want to have things like seqComposition still defined, I think that would be OK as well.  But you need to make sure that the parsing of processExpansion is going to always consume more text as you proceed through your rules.

A: Read the guide to removing left recursion in on the ANTLR wiki.  It helped me a lot.


text:
Q: Key with version number error in YugabyteDB cluster? [Question posted by a user on YugabyteDB Community Slack]
I'm just testing yugabyte under some negative tests and I'm facing a kind of issue. I'm running a 3 node cluster (master and tserver running on same node) When I stop one node and start it up again,  T-server is not booting up under this log
F20220506 06:50:49 ../../src/yb/tserver/tablet_server_main.cc:220] Invalid argument (yb/util/universe_key_manager.cc:73): Could not init Tablet Manager: Failed to open tablet metadata for tablet: eb1e5457022f42c084148ca8fa4ba5c6: Failed to load tablet metadata for tablet id eb1e5457022f42c084148ca8fa4ba5c6: Co
uld not load Raft group metadata from /data/yugabyte/data/yb-data/tserver/tablet-meta/eb1e5457022f42c084148ca8fa4ba5c6: Key with version number c7b91fad-dd60-404f-8846-cab568e52468 does not exist.
    @     0x7fcdace5ee4c  yb::LogFatalHandlerSink::send()
    @     0x7fcdaa5e28ee  google::LogMessage::SendToLog()
    @     0x7fcdaa5dfa7a  google::LogMessage::Flush()
    @     0x7fcdaa5e3169  google::LogMessageFatal::~LogMessageFatal()
    @           0x4124ea  yb::tserver::(anonymous namespace)::TabletServerMain()
    @     0x7fcda6811825  __libc_start_main
    @           0x410f99  _start
    @              (nil)  (unknown)

The only way to start it up is remove the old data.
My steps were:
1.- Cluster up with 3 server
2.- Create a taable with 3 partition on different tablet id confirmed via UI)
3.- Insert 3 different row to diff partition
4.- Select * working fine
5.- Shut down one Table server
6.- Select * working fine
7.- Starting up the table server (error)
We are running using config file:
/usr/local/yugabyte/src/yugabyte-2.11.0.1/bin/./yb-tserver --flagfile /data/yugabyte/etc/tserver.conf

and config:
--tserver_master_addrs=ip1:7100,ip2:7100,ip3:7100
--rpc_bind_addresses=fqdn
--server_broadcast_addresses=ip1
--enable_ysql
--pgsql_proxy_bind_address=ip1:5433
--cql_proxy_bind_address=ip1:9042
--fs_data_dirs=/data/yugabyte/data
--placement_cloud=cloud
--placement_region=reg
--placement_zone=zone
--use_client_to_server_encryption=true
--certs_for_client_dir=/data/yugabyte/ssl
--certs_dir=/data/yugabyte/ssl
--use_node_to_node_encryption=true
--ysql_enable_auth=true
--log_dir=/data/yugabyte/logs
--ssl_protocols=tls12,tls13
--ysql_pg_conf=pgaudit.log='DDL',pgaudit.log_level=notice,pgaudit.log_client=ON,log_min_messages=notice,log_line_prefix='\%m \%r \%u \%d [\%p]'

Looks like the key is not in memory:
/usr/local/yugabyte/src/yugabyte-2.11.0.1/bin/yb-admin -master_addresses $master get_universe_config

{"version":2,"replicationInfo":{"liveReplicas":{"numReplicas":3,"placementBlocks":[{"cloudInfo":{"placementCloud":"cloud","placementRegion":"region","placementZone":"zone"},"minNumReplicas":1}]}},"clusterUuid":"dccea8cb-9790-48ba-8a05-6218a8e875a4","encryptionInfo":{"encryptionEnabled":true,"universeKeyRegistryEncoded":"sZTzNciYu6b1KxZonpJx6v7CDDvexiv1jh/HIEAOkpV4YRrIZbIK9jtajdEMmVEUy706+dmz8bmnZvy6/n33u+qS7fzRSOTPOlpxYI6+k1lSM6bu2DRTTffhZtaiKN15gy8a3ifaZV7xJ9QJ3z9SvFYzb96+KDWw","keyPath":"/data/yugabyte/rest/universe_key","latestVersionId":"c7b91fad-dd60-404f-8846-cab568e52468","keyInMemory":false}}
KeyInMemory: False

We are using encryption at rest but the the file with the key should be there.
Am I doing something wrong?
usr/local/yugabyte/src/yugabyte-2.11.0.1/bin/yb-admin -master_addresses fqdn:7100 all_masters_have_universe_key_in_memory 7e13c99e-5278-4abd-ab78-79f70d6c2679
Error running all_masters_have_universe_key_in_memory: Operation failed. Try again. (yb/tools/yb-admin_client_ent.cc:1027): Unable to check whether master has universe key in memory.: Node fqdn:7100 does not have universe key in memory

A: The above error seems to indicate the tserver is looking for a key - "c7b91fad-dd60-404f-8846-cab568e52468" in order to open the file, but can't find it.
Realizing that there's an actual key file on the masters. That's been deprecated for using more secure in-memory keys. I just did a little digging through the code, and sure enough, we don't actually support sending on-disk keys to tablet servers on restart.
The command you have to run is this one:
yb-admin -master_addresses <master-addresses> add_universe_keys_to_all_masters <key_id> <key_path>

and then right after that it should work:
/usr/local/yugabyte/src/yugabyte-2.11.0.1/bin/yb-admin -master_addresses $master all_masters_have_universe_key_in_memory 1
Node fqdn1:7100 has universe key in memory: 1
Node fqdn2:7100 has universe key in memory: 1
Node fqdn3:7100 has universe key in memory: 1


text:
Q: Could not initialize Xv output I have installed gstreamer-1.0 on my target board.
When I run the below command:

gst-launch-1.0 filesrc location="/home/test.mp4" ! decodebin ! videoconvert ! xvimagesink
I am getting the following output:
Setting pipeline to PAUSED ...
ERROR: Pipeline doesn't want to pause.
ERROR: from element /GstPipeline:pipeline0/GstXvImageSink:xvimagesink0: Could not initialise Xv output
Additional debug info:
xvimagesink.c(1765): gst_xvimagesink_open (): /GstPipeline:pipeline0/GstXvImageSink:xvimagesink0:
Could not open display (null)
Setting pipeline to NULL ...
Freeing pipeline ..

Please suggest some solution to make the pipeline work.
Regards,
Sainath

A: Hm do you have libxv somewhere?
Find
what happens when you check gst-inspect-1.0 xvimagesink ?
Also there is library path mentioned (| grep Filename).. you can ldd it:
ldd /usr/local/lib/gstreamer-1.0/libgstxvimagesink.so

I had some problems with this as well.. try to install libxv-dev or libxv1.. maybe dev is safer.


text:
Q: Pandas fillna from mean with groupby for multiple columns I am trying to groupby multiple columns and fillna multiple columns at the same time. I am attaching a picture of what the data looks like as well as my code that I am having issues with. This is sample data that I have created that reflects that actual data, as it is confidential.
There are 4 columns: name, plant, length and width. There are 3 different types of plant. There is missing data for each of the last 3. My end goal is to create a model to guess which plant types are missing. But to do that, I am first attempting to impute the mean of the length and width for each name/plant combination into the missing values for them.
The below shows an example of calculating the means which is working, where I am failing is inserting them to fill the na values.
lengthmean = df.groupby(['name', 'plant']).length.mean()
print(lengthmean)

I get a results that looks like this
name    plant

Brian   plant 3    2.500000
        plant1     1.850000
        plant2     2.450000
Jeff    plant 3    4.100000
        plant1     2.333333
        plant2     2.100000
Justin  plant 3    2.900000
        plant1     1.900000
        plant2     2.850000
Zach    plant 3    1.750000
        plant1     2.650000
        plant2     3.300000

I am also attempting to do multiple columns at once (both length and width in this case, but in my real data it is more than that). Below is the code that is failing for me.
df[['length','width']] = df.groupby(['name', 'plant'])['length','width']\
    .transform(lambda x: x.fillna(x.mean()))

I am receiving this error 'ValueError: Length mismatch: Expected axis has 32 elements, new values have 40 elements'
I would appreciate any help, thank you!
example of data

A: Thanks for providing a sample data, that really helps!
Looks like the issue is due to your plant column having NaNs.  When I run your code df[['length','width']] = df.groupby(['name', 'plant'])['length','width']\
    .transform(lambda x: x.fillna(x.mean())) on the dataset, I do get your error message.
When I remove nulls in the plant column, it works fine:
df = df.dropna(subset=['plant'])
df_cleaned[['length','width']] = df_cleaned.groupby(['name', 'plant'])['length','width']\
    .transform(lambda x: x.fillna(x.mean()))

You'll need to figure out what you want to do with the empty plant column, if you want to fill it up/drop it/add a new plant value/etc.
hope that helps!


text:
Q: IIF Functions in Access 2013 I am Using MS Access 2013 to create queries at work. I am having issues finding examples writing Iif Functions for the query so let me lay my thought process out.
IF[Table1]=2 and IF[Table2] contains("string") then return that whole row, Else cut the whole row and never show me again.
Basically I have a query where I want all EVENT_TYPE that = 2 to only return the first and last row and cut all the other rows that contain #2 in the middle. Here is a sample of the Query.
http://i.stack.imgur.com/9eXlJ.png


text:
Q: How to prove that there is no integer $n \gt 1$ such that $(\exp n)(\log n)$ is an integer? Comments to this answer on MO suggest the following assertion:

There is no integer $n \gt 1$ such that $(\exp n)(\log\ n)$ is an integer.

Any ideas how this might be proved?


text:
Q: What are the benefits of showing "Your download will begin in x seconds"? Are there technological benefits when presenting a "download page" that gives a message like the following?

Your download should automatically
  begin in a few seconds, but if not,
  click here.

Is there some bandwidth or server efficiencies with this? Or is it for the benefit of the user somehow?  Why not just have your download link href's go straight to the url of the download?
Example page (one of a billion)

A: If the site is telling you to wait a specific number of seconds before continuing, as you describe in the title, then it's likely all about advertising. But that's not the case with the Mozilla Firefox link you posted within your question. Here, I think the main point is to tell the user to be patient if the download doesn't start immediately, which it might not since it's an additional HTTP request that could be delayed for any number of reasons, including the download server being overloaded. That connection could be reset and the download might never happen. The message is trying to set appropriate expectations for the user: the download might not start this instant, but if it has been more than a few seconds and nothing has happened, then there was probably a problem and here's a link you can click.
There's also a lot of JavaScript in this page that tries to help with the download, and if that fails, the "click here" link should act as a failsafe.

A: *

*Advertising

*SEO benefits, you minimize the links to non html pages of your source page

*you can present similar downloaded products ...

*time for your Content Delivery Network to cache the download, if you point the user to a file not-yet-cached by the CDN

A: For once you get additional advertising space. By delaying the download, you give the user some time to recognize and potentially click on the ads.
However a page like this can also be useful when you are offering lots of files. By presenting the user with a message stating exactly what they are going to download shortly, some might actually cancel their downloads by navigating back from that site. If the files you offer are big, this might actually save you some bandwidth.
Moreover you prevent the file from getting indexed directly in search engines, potentially bypassing your site completely. But you can let the search engines index your download pages with all the information about the downloads in them. This is related to the advertising topic, but also helps to keep your internal download structure hidden from the search engine. Should you decide to change it, there will be no broken links in search results.
Often you will also find a mirror selection on these interstitial pages. Users can conveniently use the time they have there to choose a different mirror than your suggested default. Should a link be broken, i. e. the mirror does not have the file (yet/anymore), by just hitting the Back button they can conveniently select a different one and try again.

A: The main reason why getting to a download takes as many steps as it does with most big download providers is indeed gaining page views, and producing ad impressions.
On the other hand, the "please wait" message has a real function IMO: The user is clearly shown that there should now follow a file download, and if redirection to the file download fails - for example because the link's broken, the server is overburdened or whatever - there is a way to try again, or to get help - important especially for less experienced users.

A: Advertising.
Prevents trivial automated downloads (think wget).

A: Advertising space.

A: The benefit is not to the user, but to the site. They are forcing you to stare at their "download landing page" for a few seconds, while they show you ads. Furthermore, with that kind of chicanery, they can prevent the file in question from being directly indexed by search engines, while permitting the download landing page to be indexed.

A: It also provides a soft landing (in the form of a splash screen, instructions, info...and advertising :) in the event that the browser does not react as anticipated.

A: Here are some reasons:
SEO:
Less page bounce & exit rates because you stay longer. (Very important)
Ads:
They want you to click their ads and support them?
Security:
Avoid in some degree auto-clickers, hot-linking and similar activities.
Content:
Allow CDN and server to fully load the page before the button appears.
If you are a publisher the delay have to many benefits. For users that don't like them simply leave the page.

A: Contrary to all the answers above, an async download won't show that it started until "something" is returned from the server.  If you clicked the download button and nothing visual happened for 1.3 seconds, you'd start pumping the download button.  In the example site of the original post, I see the web developer chose to make the download button disappear after it was clicked - meaning even the message wasn't enough to stop users from power-clicking.

A: I recently had to build such a page for a JS RIA. Here's why:

*

*The original idea was to use a hidden iframe inside the RIA. But our company uses a virus scanner/firewall that sends a 302 HTTP response, then using a framebreaker script to present a fullscreen scanning progress page.

*Thus, the download needs to be opened in a new window, since we don't want the RIA to be terminated when a download starts.

*For usability, we don't want blank popup-windows for every download (this is actually a problem others see too), so we need to show the user some HTML content, then redirect to the actual download.

*As @DavidKolar stated, the wording just tells the user to be patient while the download is being prepared.

*We don't use the "click here" part. As for the example page in the question, it's funny to see that Mozilla removed it there too.


text:
Q: Combinatorial definition of Hall–Littlewood polynomials (sum over SSYT?) Hall–Littlewood polynomials $P_\lambda(x;t)$ is an important deformation of Schur polynomials
forming a basis in the ring of symmetric polynomials over $\mathbb Z[t]$.
There are various definitions, including quite explicit
$$
P_\lambda(x;t)=
\sum_{w\in S_n/\lambda} w\left(x^\lambda\prod_{\lambda_i>\lambda_j}\frac{x_i-tx_j}{x_i-x_j}\right)
$$
but I'm interested in a combinatorial description.
Schur polynomial $s_\lambda$ is a sum of monomials corresponding to semi-standard Young tableux of shape $\lambda$ —
so I'm expecting an answer in the form of a weight on SSYT.
P.S. I'm mostly interested in the principal specialization of H-L polynomials — maybe this $(q,t)$-weight on SSYT is easier to describe than the full answer.

A: I'm not sure if this is exactly what you're looking for, but I recently worked on a paper regarding just this question (http://arxiv.org/abs/1403.8139). We were generalizing Tokuyama's deformation formula (http://projecteuclid.org/euclid.jmsj/1230129805) for the Schur polynomial, so we used Gelfand-Tsetlin patterns rather than Young tableaux. Tokuyama's original formula is in terms of strict GT patterns, which are in bijection with standard Young tableaux, but extending to the Hall-Littlewood polynomials required using nonstrict GT patterns (which are in bijection with SSYT).

A: It is also possible to get a combinatorial description using semi-standard augmented fillings, by specializing the combinatorial formula for Macdonald polynomials (see wikipedia on the Macdonald polynomials).
It is also possible to get a formula as sum over SSYT's and the cocharge statistic. This gives the expansion of HL-polys in terms of Schur polynomials.


text:
Q: Select one column by two different names in the same query I have a table named Main that contains two fields id,name.
I want to select the name column by two different names. For example:
Table Main

id:int, name:varchar(20)

I have inserted the following records:

id  | name
----+-------
  1 | Ahmad
  2 | Sami

I want to select the data like this:
select Main.name as n1,Main.name as n2 from Main
where n1='Ahmad' and n2='Sami'

When I execute this query, it gives the following error:

ERROR:  column "n1" does not exist
  LINE 1: select Main.name n1,Main.name n2 from Main where n1='Ahmad' ...`

I use PostgreSQL as my DBMS.

A:  select n1.name as "n1", n2.name as "n2"
 from main n1, main n2
 where n1.name = 'Ahmad'
     and n2.name = 'Sami';


text:
Q: Javascript: Getting undefined on input box that takes a range from 0 to 10 I have two buttons (+ and -) and an input box with a value of 10. The input must take a value from 0 to 10 only and I can't figure out why I'm getting undefined after I reach either 0 or 10 on the input box. I tried using parseInt for the values. But perhaps I'm not doing it on the right place. Would appreciate the help.

var fighterScore1 = document.getElementById("fighterScore1");
fighterScore1.value  = 10;
var fighter1Inc = document.getElementById("fighter1Inc");
var valor = 10;

 fighter1Inc.onclick = function (valor) {
  fighterScore1.value = increaseValue(valor);
 };
 fighter1Dec.onclick = function (valor) {
  fighterScore1.value = decreaseValue(valor.value);
 };
  function decreaseValue() {
  if (valor <= 0 ) {

     } else {
     valor--;
      return valor;
     }
 };
 function increaseValue() {
  if (valor >= 10 ) {
      valor = 10;
     } else {
     valor++;
      valor = valor;
      return valor;
     }

 };

   <button id="fighter1Inc">+</button>
   <input type="text" id="fighterScore1" maxlength="10" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
   <button id="fighter1Dec">-</button>

A: The problem is that you're only returning inside the condition that it is less than 10 or greater than 0. If you don't return in one condition,there is no return value so you end up assigning undefined to a variable. Here is a fixed JSFiddle. You have to return outside the if statements, and valor.value doesn't exist.

var fighterScore1 = document.getElementById("fighterScore1");
fighterScore1.value  = 10;
var fighter1Inc = document.getElementById("fighter1Inc");
var valor = 10;

fighter1Inc.onclick = function (valor) {
 fighterScore1.value = increaseValue();
};

fighter1Dec.onclick = function (valor) {
 fighterScore1.value = decreaseValue();
};

function decreaseValue() {
 if (valor <= 0 ) {
        valor = 0;
 } else {
     valor--;
 }
 return valor;
};

function increaseValue() {
 if (valor >= 10 ) {
     valor = 10;
 } else {
     valor++;
 }
    return valor;
};

 <button id="fighter1Inc">+</button>
 <input type="text" id="fighterScore1" maxlength="10" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
 <button id="fighter1Dec">-</button>

A note: you pass arguments into a function that takes none (JS accepts a varying number of arguments, even if you don't specify). Either you remove the call with arguments, or you use an argument and pass it in, using the argument in place of valor.

A: You're not actually returning any values in your branches for when valor <= 0 or valor >= 10. If you ever forget to return a value in JavaScript, you'll get an implicit return at the end of the function with the value undefined.
To fix this, just add return statements for valor at the end of your function, or in each branch of your if/else.
For example
function decreaseValue() {
    if (valor <= 0 ) {
         return 0;
    }
    else {
        return valor - 1;
    }
}

A: The issue with your code is that not all paths in incriseValue and decreaseValue return something. It means return undefined;. Additionally (to your luck) incriseValue and decreaseValue don't use arguments and work with global varlor. Here is fixed code.

var fighterScore1 = document.getElementById("fighterScore1");
fighterScore1.value = 10;
var fighter1Inc = document.getElementById("fighter1Inc");
var valor = 10;
var fighter1Dec = document.getElementById("fighter1Dec");

fighter1Inc.onclick = function() {
  fighterScore1.value = increaseValue();
};
fighter1Dec.onclick = function() {
  fighterScore1.value = decreaseValue();
};

function decreaseValue() {
  if (valor > 0)
    valor--;
  return valor;
};

function increaseValue() {
  if (valor < 10)
    valor++;
  return valor;

};

  <button id="fighter1Inc">+</button>
  <input type="text" id="fighterScore1" maxlength="10" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
  <button id="fighter1Dec">-</button>


text:
Q: Haskell: Changing an element at a given index in a ByteString I'm trying to change a character at indices x and y in a matrix made of ByteStrings to a different character. Initially, I used [[Char]] to represent the matrix, so I was able to use .~ from Control.Lens.Setter to change the value, but this doesn't seem to work for [ByteString].
Is there any way to use the lens or to modify the element without unpacking the ByteString like I'm doing right now?
The code, right now, is:
render :: [[Char]] -> [Loc Int] -> [[Char]]
render maze []               = maze
render maze (Loc (x,y):locs) = render mutate locs
    where mutate = element y . element x .~ '*' $ maze

Where Loc is just:
newtype Loc a = Loc (a,a) deriving (Show,Eq,Ord)

A: This works for ByteStrings:
import qualified Data.ByteString.Char8 as BS
import Control.Lens

-- change character at position 2 to a space (ASCII code 32)

test = (BS.pack "abcdef") & ix 2 .~ 32

Note that ByteStrings are really containers of Word8 values, so that's we need to use the ASCII code here.
The ix operator works for a lot of other data structures like Text, lists, Sets, Maps, etc -- see here for more details.


text:
Q: phpmailer not working in godaddy , nor in mail() working I am getting following error when trying to mail from godaddy smtp.
I am getting following errors
Warning: require_once(class.phpmailer.php) [function.require-once]: failed to open stream: No such file or directory in filename on line 60
Fatal error: require_once() [function.require]: Failed opening required 'class.phpmailer.php' (include_path='.:/usr/local/php5_3/lib/php')
<?php
if (isset($_POST['email']))
//if "email" is filled out, send email
  {
  //send email

 require_once("class.phpmailer.php");
$mail = new PHPMailer();
//$mail->IsSMTP();
$mail->SMTPDebug = 1; // 1 tells it to display SMTP errors and messages, 0 turns off all errors and messages, 2 prints messages only.
$mail->SMTPAuth = true;
$mail->SMTPSecure = "https";
$mail->Host = "smtpout.asia.secureserver.net";
$mail->Port = 25;

$mail->Username = "test@mydomain.com" ; // this is email on godaddy account
$mail->Password = "password";

$mail->From = "test@mydomain.com" ;
$mail->FromName = "some name" ;

$mail->AddAddress($_POST['email'], $name);
//$mail->AddReplyTo("Email Address HERE", "Name HERE"); // Adds a "Reply-to" address. Un-comment this to use it.
$mail->Subject = "site no. ".$_POST['site1']." ".$_POST['status']." for you " ;
$mail->Body = " Hi, your site  with no. ".$_POST['site1']." in phase ".$_POST['phase1']." has been ".$_POST['status']  ;

if ($mail->Send() == true) {
echo "The message has been sent";
}
else {
echo "The email message has NOT been sent for some reason. Please try again later";
echo "Mailer error: " . $mail->ErrorInfo;
}

  }

?>

A:
It seems the your PHP script is unable to locate the class.phpmailer.php file

*

*Try copying class.phpmailer.php file into the same directory as that of the PHP script

or

*

*Specify the full path to the class.phpmailer.php in the require_once

If at all you don't happen to have the class.phpmailer.php file :

*

*First download it from the PHPMailer website

*Copy it to a location accessible by the script

*Specify its path in the require_once


text:
Q: Select from Ul and LI in css How to select only "About us" from nested ul li in css?
<!DOCTYPE HTML>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, user-scalable=yes">
<title>site map</title>

Home Page

About us

success stories

giving back

tours

contact

membership

dining discout deals

dreamtrips

travel deals discounts

opportunity

work at home oportunuty

careers

our company

out culture

our brands

Blog

               categories

Chnaging lives

experience more

               categories

Chnaging lives

experience more

A: You can use :first-child pseudo-class selector to get the first child among the collection and using direct child(>) selector you can get the direct child which helps to avoid nested children.
.sitemap > li:first-child > a{
   /* define style properties */
}

.sitemap > li:first-child > a {
  color: red;
}

About us

success stories

giving back

tours

contact

membership

dining discout deals

dreamtrips

travel deals discounts

opportunity

work at home oportunuty

careers

our company

out culture

our brands

Blog

               categories

Chnaging lives

experience more

      categories

Chnaging lives

experience more

A:

ul li:nth-child(1) a{color:red}

About us

success stories

giving back

tours

contact

membership

dining discout deals

dreamtrips

travel deals discounts

opportunity

work at home oportunuty

careers

our company

out culture

our brands

Blog

               categories

Chnaging lives

experience more

    categories

Chnaging lives

experience more

use ul li:nth-child(1)

A: Try this code with first child selector
   .sitemap > li:first-child > a{
     background:green;
    }

.sitemap > li:first-child > a{
  background:green;
}

.sitemap li a {
   text-transform: capitalize;
}
.sitemap .blog-sitemap-sub{
   text-decoration: none;
   color: #000;
   cursor: default;
}
Home Page

About us

success stories

giving back

tours

contact

membership

dining discout deals

dreamtrips

travel deals discounts

opportunity

work at home oportunuty

careers

our company

out culture

our brands

Blog

               categories

Chnaging lives

experience more

               categories

Chnaging lives

experience more

A: Try this code

$('.sitemap li a').filter(':contains("About us")').css("background-color","RED")

<!DOCTYPE HTML>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, user-scalable=yes">
<title>site map</title>

Home Page

About us

success stories

giving back

tours

contact

membership

dining discout deals

dreamtrips

travel deals discounts

opportunity

work at home oportunuty

careers

our company

out culture

our brands

Blog

               categories

Chnaging lives

experience more

               categories

Chnaging lives

experience more


text:
Q: Adding component to window GraphicsWindow Class:
import java.awt.*;
import java.awt.geom.*;
public class GraphicsWindow extends BlankWindow
{
    public void paintComponent(Graphics g)
    {
        Graphics2D g2d = (Graphics2D) g;
        this.setBackground(Color.ORANGE);
    }
}

BlankWindow Class (main):
import java.awt.*;
import javax.swing.*;
import java.awt.Container;
public class BlankWindow extends JFrame
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Picture");
        JPanel pane = new JPanel();
        frame.setSize(400,500);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setVisible(true);

        GraphicsWindow component = new GraphicsWindow();
        frame.add(pane);
        pane.add(component);
    }
}

I am getting an error on the pane.add(component); whenever I try to run it.

A: In your GraphicsWindow, you must extend javax.swing.JComponent not BlankWindow
Source: http://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html


text:
Q: ADOBE AIR : Error #16824 : Version mismatch while trying to auto update OBJECTIVE :
So here is my problem, I am trying to auto-update an old version software X v1.0.7 AIR Runtime SDK 2.0 to a new version X v1.0.8 AIR Runtime SDK 2.5.
CONFIGURATION =
Old Software X is version 1.0.7 using runtime SDK 2.0. App.xml as follow :
<application xmlns="http://ns.adobe.com/air/application/2.0">
<version>1.0.7</version>
This software X is so, suppose to update to version 1.0.8 which suppose to use the AIR runtime 2.5.
Im using an update.xml file with tags :
<update xmlns="http://ns.adobe.com/air/framework/update/description/1.0">
       <version>1.0.8</version>
The computer is MacOS X v10.6.6. running the latest AIR RUNTIME 2.5
The new version of the old software X, version 1.0.8, is using an app.xml as follow :
<application xmlns="http://ns.adobe.com/air/application/2.5">
    <versionNumber>1.0.8</versionNumber>
   <publisherID>#my hidden publisherID#</publisherID>
The software X v1.0.8 is using the tag publisherID so the software would be recognized as the same software.
WHAT HAPPEN ?
When I launch the old software X v1.0.7, it is trying to update and raise the error 16824. This error is suppose to mean that my version of the new software does not match the version defined in the update.xml file but to me, its not true... so what is wrong ? Anyone can help ?

A: The solution is here :
http://kb2.adobe.com/cps/873/cpsid_87300.html

A: If you're trying to follow the instructions in the knowledge base article, you'll find that it tells you what to do but not how to do it. You're told to include the updated applicationupdater.swc and applicationupdater_ui.swc from Air 2.5 / Flex 4.5 but that is the hardest part.
In Flash Builder do this:

*

*Go to "Project Properties", "Build Path"

*Unfold the Flex Framework in the list and remove applicationupdater.swc and applcationupdater_ui.swc.

*Click "Add SWC" and add those two files from your Flex 4.5 framework location (/Applications/Adobe Flash Builder 4.5/sdks/4.5.0/frameworks/libs/air/applicationupdater.swc on Mac).

If you're using the mxmlc task in an Ant buildfile, this has worked for me:
<target name="compile" depends="css, copy_assets">
  <mxmlc file="${MAIN_SOURCE_FILE}" output="${OUTPUT}/${FLEX_APP_NAME}.swf">

    <load-config filename="${FLEX_HOME}/frameworks/air-config.xml"/>

    <compiler.source-path  path-element="${APP_ROOT}/src"/>
    <compiler.source-path  path-element="${APP_ROOT}/locale/{locale}"/>

    <!-- append=false clears your library-path -->
    <compiler.library-path dir="${FLEX_HOME}" append="false">
      <!-- Now we need to re-add the flex libs -->
      <include name="libs"/>
      <include name="locale/{locale}"/>
    </compiler.library-path>
    <compiler.library-path dir="/" append="true">
      <!-- Add the updater framework from Flex 4.5 / Air 2.6 -->
      <include name="Applications/Adobe Flash Builder 4.5/sdks/4.5.0/frameworks/libs/air/applicationupdater_ui.swc"/>
      <include name="Applications/Adobe Flash Builder 4.5/sdks/4.5.0/frameworks/libs/air/applicationupdater.swc"/>
      <!-- You may need to adjust these paths -->
    </compiler.library-path>
    <compiler.library-path dir="${FLEX_HOME}" append="true">
      <!-- Re-add the rest of the air libs -->
      <include name="libs/air"/>
    </compiler.library-path>
    <compiler.library-path dir="${APP_ROOT}/libs/" append="true">
      <!-- Your custom libraries here -->
    </compiler.library-path>
  </mxmlc>
</target>

An equivalent set of commandline options should work for the mxmlc command line compiler, but I haven't tested this:
mxmlc -library-path=$(FLEX_HOME)/libs $(FLEX_HOME)/locale/{locale} \
$(FLEX45_HOME)/frameworks/libs/air/applicationupdater.swc \
$(FLEX45_HOME)/frameworks/libs/air/applicationupdater_ui.swc \
$(FLEX_HOME)/frameworks/libs/air \
... your custom libs \
... other compiler options

I have described the entire process with a bit more background information on my blog.

A: The error occurred for me because versions number in my compiled application was different than the version number in the UpdateDescriptor.xml on the server.
In an AIR application the version number is defined in the application descriptor file under the tag versionNumber:
<versionNumber>2.3.0</versionNumber>

In the UpdateDescriptor.xml file on the server I had a different number:
<?xml version="1.0" encoding="utf-8"?>
<update xmlns="http://ns.adobe.com/air/framework/update/description/2.5">
    <versionNumber>2.2.1</versionNumber>
    <url>http://www.example.com/project_2.2.1.air</url>
    <description><![CDATA[List the changes in this version here]]>
    </description>
</update>

It resulted in this error:


text:
Q: Discord.py can't check for messages and check for commands at the same time I'm using
@client.event
async def on_message(message):

to check for messages sent by users.
I'm also using
@client.command(aliases=['a'])
async def a(ctx):

to check if a command is being run. when i leave the on message in, the command part won't run. what do i do.

A: If you're using on_message event, it blocks your commands. In order to prevent this, you can use await client.process_commands(message). You just have to add this line of code in the last line of your on_message event.


text:
Q: How do I parse \n in rust? I'm trying to get a string from user which contains escape characters like \n and others. But, after getting user input, when I try to print that exact string to standard output via print macro it prints literal \n instead of a newline.
Here's my code:
use std::io::{self, Write};

fn main() {
    let mut string = String::new();
    io::stdin().read_line(&mut string);
    print!("{}", string);
    io::stdout().flush().unwrap();
}

Output:
~ ./main
are you working \n\n ???
are you working \n\n ???

A: When you use \n in code, the compiler automatically converts that into an ASCII newline (0xA/10). When typing input to a program like this, that's not done, so you get two characters '\' and 'n'. If you want them to work, you need to convert them yourself (e.g. using .replace as @Chayim Friedman suggessted).
You could use e.g. printf to do:
~ ⵃ printf "abc\tdef\n" | hexdump
00000000  61 62 63 09 64 65 66 0a                           |abc.def.|
00000008

However, this won't work with get_line


text:
Q: In Java, how to rewrite smthing like "typedef double Scalar"? I am fairly new to Java. I used to work with C++. For one task, my Java code needs to be flexible enough for a performance test with float and double. In C++, I can simply write my code with "typedef float Scalar", and use Scalar as my primitive type across the code. When changing to double, I could replace that line with  "typedef double Scalar". How could I do similar thing in Java?
I read Is there a Java equivalent or methodology for the typedef keyword in C++? . Someone mentioned a pseudo-typedef, but I think that doesn't apply to my case, as I try to typedef a primitive type. Any suggestion?
Very appreciated.

A: Java doesn't really have anything similar to typedef. I think the closest you could get would be to define a Scalar class to wrap a float or double, but then you wouldn't be able to conveniently use operators such as + and - (and it might just be overkill to do so in general).


text:
Q: checking symbol equality in defmacro (clojure) This returns false.
(defmacro scratch [pattern]
  `(= 'b (first ~pattern)))

(scratch '(b))

However, the output of the following is b.
(defmacro scratch2 [pattern]
  `(first ~pattern))

(scratch2 '(b))

How do I setup the first macro to return true?

A: that is happening, because the 'b that you introduce in macro is namespaced:
example:
user> (defmacro nsmac []
        `(namespace 'b))

user> (nsmac)
;;=> "user"

while the value you pass isn't:
user> (namespace (first '(b)))
;;=> nil

so, you can pass the namespaced symbol to a macro, like this:
user> (scratch '(user/b))
;;=> true

or you can fix you macro to use unnamespaced symbol (known trick with qoute-unquote):
(defmacro scratch [pattern]
  `(= '~'b (first ~pattern)))

user> (scratch '(b))
;;=> true

but what you really want, is to check this one in compile-time, because this macro you have is better as a plain function, since it doesn't employ any macro-related goodness.
It could look like this:
(defmacro scratch [pattern]
  (= 'b (first pattern)))

(scratch (b))
;;=> true

something about namespacing can be found in this article


text:
Q: Where should I fetch a product price to create an order in CQRS / DDD? I want to save an order with order items with prices in my write database. But firstly I need to fetch products with their prices because I don't trust a user - he could pass a lower price, that's why I don't want to add a Price property to CreateOrderDTO.
Where should I fetch product prices? In a command handler - if yes then from which database: read database or write database? Or maybe in a controller before sending a command?
The flow in my application is the following:
API - the controller:
[HttpPost]
public async Task<IActionResult> CreateOrder(CreateOrderDTO orderDto)
{
    var orderCmd = new CreateOrderCommand(orderDto.CustomerId, orderDto.OrderItems);
    await _mediator.Send(orderCmd);
}

The CreateOrderDTO model:
public class CreateOrderDTO
{
    public Guid CustomerId { get; set; }
    public List<CreateOrderItemDTO> OrderItems { get; set; }
}

public class CreateOrderItemDTO
{
    public Guid ProductId { get; set; }

    public int Quantity { get; set; }
}

The command and command handler:
public class CreateOrderCommand : IRequest
{
    public Guid CustomerId { get; }
    public List<CreateOrderItemDTO> OrderItems { get; }

    public CreateOrderCommand(Guid customerId, List<CreateOrderItemDTO> orderItems)
    {
        CustomerId = customerId;
        OrderItems = orderItems;
    }
}

public class CreateOrderCommandHandler : IRequestHandler<CreateOrderCommand>
{
    private readonly IEventStoreRepository _eventStoreRepository;

    public CreateCustomerCommandHandler(
        IEventStoreRepository eventStoreRepository)
    {
        _eventStoreRepository = eventStoreRepository;
    }

    public async Task<Unit> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
    {
        var order = new Order(Guid.NewGuid(), request.CustomerId);
        foreach (var item in request.OrderItems)
        {
            order.AddOrderItem(item.ProductId, item.Quantity, /* I need a price here */);
        }

        await _eventStoreRepository.Save(order);

        return Unit.Value;
    }
}

And my aggregate root:
public class Order : AggregateRoot
{
    public Guid Id { get; private set; }
    public Guid CustomerId { get; private set; }
    public List<OrderItem> OrderItems { get; private set; }

    public Order(Guid id, Guid customerId)
    {
        OrderItems = new List<OrderItem>();
    }

    public void AddOrderItem(Guid productId, int quantity, decimal price)
    {
      //...
    }
}

A:
If yes then from which database: read database or write database?

TL;DR: usually the read database.

Recommended reading: Data on the Outside versus Data on the Inside
Basic riddle: does the fact that you are copying a price into an order mean that nobody is allowed to change the price in the product catalog?
After all, it takes sometime for the information to travel from there to here - by the time we have a copy of the information in memory, it might be nanoseconds out of date.
What's the impact to the business?
The usual answer is "not a lot".

A microsecond difference in timing shouldn't make a difference to core business behaviors.  -- Udi Dahan.

So in this common case, it's going to be OK to use a cached copy of the data, so long as the service level of cache updates is sufficient to meet the needs of the business.  And that in turn means that read database/write database/local cache as the source of your data doesn't really matter very much -- it's just a matter of balancing different trade offs.
On the other hand, if it is critical to the business that the price in the order be exactly right - no latency allowed - then you are going to have to get the information from the write database (because all of the other sources can be nanoseconds behind) and you are going to have to make sure that information isn't changing while you work.

Another thing that you can sometimes do is replace concepts like "the current price" with "the price at the current local time".  So when the order is placed we write down the local time, and then we can ask the product service what the price was at the time we wrote it down.
Immutability Changes Everything is a good starting point for this idea.
Notice the difference: "what's the price now?" is a question that gets different answers, depending on how long information takes to move through the system.  "what was the price then?" always gets one of two answers - either the authoritative answer or "I don't know (yet)".


text:
Q: How can I order a list by number of matches after filtering by Search Terms in C#? I have a Filter Method in my User Class, that takes in a list of Users and a string of search terms. Currently, the FindAll predicate splits the terms on spaces then returns a match if any of the searchable properties contain any part of the terms.
public static List<User> FilterBySearchTerms( List<User> usersToFilter, string searchTerms, bool searchEmailText )
{
    return usersToFilter.FindAll( user =>
    {
        // Convert to lower case for better comparison, trim white space and then split on spaces to search for all terms
        string[] terms = searchTerms.ToLower().Trim().Split( ' ' );

        foreach ( string term in terms )
        {
            // TODO: Is this any quicker than two separate ifs?
            if (
                    (searchEmailText && user.Email.ToLower().Contains( term ))
                    || (
                        user.FirstName.ToLower().Contains( term ) || user.Surname.ToLower().Contains( term )
                        || user.Position.ToLower().Contains( term ) || user.Company.ToLower().Contains( term )
                        || user.Office.ToLower().Contains( term )
                        || user.Title.ToLower().Contains( term )
                    )
            )
                return true;
            // Search UserID by encoded UserInviteID
            else
            {
                int encodedID;
                if ( int.TryParse( term, out encodedID ) )
                {
                    User fromInvite = GetByEncodedUserInviteID( encodedID );
                    if ( fromInvite != null && fromInvite.ID.HasValue && fromInvite.ID.Value == user.ID )
                        return true;
                }
            }
        }

        return false;
    } );
}

I have received a new requirement so that the ordering is now important. For example, a search for 'Mr Smith' should have Mr Adam Smith ahead of Mrs Eve Smith, which might make my use of Contains inappropriate. However, the most important thing is the number of property/part of term matches.
I'm thinking I could have a couple of counters to keep track of complete term matches and partial matches, then order by those two. I'm also open to suggestions on how the Filter method can be improved - perhaps using something else entirely.

A: Here's a LINQ-based solution. It will be a bit more of a pain if you're not using .NET 3.5, I'm afraid. It separates out the details of the matching from the query itself, for clarity.
You'll need to create a LowerCaseUser method which returns a User object with all the properties lower-cased - it makes more sense to do that once than for every search term. If you can put that and UserMatches into the User class, so much the better. Anyway, here's the code.
public static List<User> FilterBySearchTerms
    (List<User> usersToFilter,
     string searchTerms,
     bool searchEmailText)
{
    // Just split the search terms once, rather than for each user
    string[] terms = searchTerms.ToLower().Trim().Split(' ');

    return (from user in usersToFilter
            let lowerUser = LowerCaseUser(user)
            let matchCount = terms.Count(term =>
                                         UserMatches(lowerUser, term))
            where matchCount != 0
            orderby matchCount descending
            select user).ToList();
}

private static bool UserMatches(User user, string term,
                                bool searchEmailText)
{
    if ((searchEmailText && user.Email.Contains(term))
        || user.FirstName.Contains(term)
        || user.Surname.Contains(term)
        || user.Position.Contains(term)
        || user.Company.Contains(term)
        || user.Office.Contains(term)
        || user.Title.Contains(term))
    {
        return true;
    }
    int encodedID;
    if (int.TryParse(term, out encodedID))
    {
        User fromInvite = GetByEncodedUserInviteID(encodedID);
        // Let the compiler handle the null/non-null comparison
        if (fromInvite != null && fromInvite.ID == user.ID)
        {
            return true;
        }
    }
    return false;
}

A: The first thing, I'd say that you need to do, is to break the large lazily evaluated or conditions into separate conditions. Otherwise you're never going to resolve how many matches you're actually getting. After this you'll probably need a score for each user which reflects how well the search terms match it.
I'm also assuming you are able to use LINQ here as you are already using lambda expressions.
    class ScoredUser
    {
        public User User { get; set; }
        public int Score { get; set; }
    }

    public static List<User> FilterBySearchTerms(List<User> usersToFilter, string searchTerms, bool searchEmailText)
    {
        // Convert to lower case for better comparison, trim white space and then split on spaces to search for all terms
        string[] terms = searchTerms.ToLower().Trim().Split(' ');

        // Run a select statement to user list which converts them to
        // a scored object.
        return usersToFilter.Select(user =>
        {
            ScoredUser scoredUser = new ScoredUser()
            {
                User = user,
                Score = 0
            };

            foreach (string term in terms)
            {
                if (searchEmailText && user.Email.ToLower().Contains(term))
                    scoredUser.Score++;

                if (user.FirstName.ToLower().Contains(term))
                    scoredUser.Score++;

                if (user.Surname.ToLower().Contains(term))
                    scoredUser.Score++;

                // etc.
            }

            return scoredUser;

            // Select all scored users with score greater than 0, order by score and select the users.
        }).Where(su => su.Score > 0).OrderByDescending(su => su.Score).Select(su => su.User).ToList();
    }

Having the method return a scored customer also allows you easily tweak the scoring balances later on. Say you want a matching first name matter more than a matching company for example.

A: Is the distinction between full and partial matching what's relevant, or just standard lexicographical sorting? If you were to sort Mr. Adam Smith and Mrs. Eve Smith they would be placed in that order. That would just allow you to use a standard ordering lambda.


text:
Q: Formatting number to have 2 digits: "Object required" Having a look in other threads on the issue, I've found how I can do it, but still i have some issue with my code (printing some values to a file. )
I'm trying to read some data from Excel sheet (it has 32 lines) and print it to a text file in some defined format. The code is for Excel Visual Basic
For y = 1 to 32
   Print #1, y.ToString("D2")
   Print #1, "some text" & y.ToString("D2")
Next y

I'm getting runtime error 424: object required on both of printing commands.
Am I missing something?

A: You seem to be mixing up Visual Basic with Visual Basic for Applications (VBA): they are quite different.
In VBA you can format a number with the Format function:
 Format(y, "00")


text:
Q: Неэффективное использование оперативной памяти Написал задачу на java. В ней используются postgresql, spring boot, rest. Все просто, надо считать данные из БД, объект с двумя полями айди и имя, и потом в json передать в response. Вот проверив его одной из ошибок стало неэффективное использование оперативной памяти.
Одним из условий является не использовать возможности SQL. Так же в БД по условию более миллиона записей.
Что делать чтобы исправить? Контроллер скидывать пока не буду, потому как кажется что проблема на нижних слоях, но если надо выложу сразу.
Мой код:
@Repository

public class ContactRepositoryImpl implements ContactRepository {

    private static final BeanPropertyRowMapper<Contact> ROW_MAPPER = BeanPropertyRowMapper.newInstance(Contact.class);

    JdbcTemplate jdbcTemplate;

    @Autowired

    public ContactRepositoryImpl(@Qualifier("dataSource") DataSource dataSource) {

        this.jdbcTemplate = new JdbcTemplate(dataSource);

    }

    public List<Contact> getAll() {

        System.out.println(jdbcTemplate.toString());

        return jdbcTemplate.query("SELECT * FROM contacts", ROW_MAPPER);

    }

}

@Service

public class ContactServiceImpl implements ContactService {

    @Autowired

    private ContactRepository repository;

    @Override

    public List<Contact> getFilteredContacts(String nameFilter) {

        Pattern pattern = Pattern.compile(nameFilter);

        List<Contact> list = repository.getAll();

        List<Contact> list2 = list.stream()

                .filter(Objects::nonNull)

                .filter(it -> it.getName() != null)

                .filter(it -> !pattern.matcher(it.getName()).matches())

                .collect(Collectors.toList());

        return list2;

    }

}

A: Я так понял ограничения состоят в том, чтобы использовать возможности Spring Data?
Посмотрите в сторону PagingAndSortingRepository.

В данном интерфейсе есть метод:
Page<T> findAll(Pageable pageable)

который позволяет вытягивать записи страницами.
Вы можете считывать записи постранично и мёржить результаты.
Если не хочится ломать лаконичность стримов, то можете обернуть всю логику page-инации в свой стрим, заменив list.stream() на свою реализацию How to implement a Java stream?
.

Если лень делать ручками, можете попробовать использовать fetch size hint
@QueryHints(@javax.persistence.QueryHint(name="org.hibernate.fetchSize", value="50"))
List<Foo> findAll();

Set the fetch size with Spring Data.

A: фильтрацию в getFilteredContacts можно сделать в запросе: SELECT * FROM contacts WHERE name IS NOT NULL AND name LIKE :name. Вы вытаскиваете все результаты из базы и гоняете туда сюда. В этом нет смысла.


text:
Q: Connecting two subnets I have two linksys routers connected together LAN to WAN and I'm trying to establish connection between the two subnets.
The secondary router is in a shed not in my house. I'd rather not do LAN to LAN as that would take up a port on the router. This is a learning experience for me so I'd rather not take the easy way out. I've learned a lot while trying to get it working.
Here's my setup:

I can not ping (computer A) to (computer B).
I can not ping (computer B) to (computer A).
From (computer A) I can not access the secondary router.
From (computer B) I can access both routers.
Both Routers have a DVR camera system hooked up to them, they have local IPs for viewing the cameras and I can access both DVRs from either computer.
I want to be able to ping computer A and computer B from either router (want to be able to transfer files)
I have looked at so many guides and information but nothing seems to work.
P.S. I cant even access the secondary router from computer A. if i type 192.168.1.134 or 192.168.7.7 in the browser it dont load

A: From the diagram, your IP addressing and routing appear to be fine.

*

*Although you marked on the diagram that the secondary router has "SPI firewall" disabled, I'd double-check whether there is any other firewall configuration; perhaps reenable the firewall and just explicitly configure it to accept everything. If you're lucky, the firewall rules might even come with logging, so that the router's "system log" section would show all mistakenly-blocked packets.

*It's also possible that the firewall on the main router might be interfering; e.g. it might only have an allow-forward rule for "192.168.1.x to WAN".

*Another possible problem is that the primary router might not want to forward routed packets back to the same interface that they already came from (i.e. from LAN to LAN). I don't know why some routers do that, but it's apparently a thing that happens.
To rule out the latter two problems, I suggest temporarily adding the same route (192.168.7.0/24 via 192.168.1.134) to computer A (thereby bypassing the Main Router entirely).
The secondary router's "NAT" rules (SNAT or masquerading) shouldn't interfere with incoming connections, but it's still good that you've disabled NAT regardless.

If you run out of LAN ports, buy an Ethernet switch.


text:
Q: How to sync slash command globally discord.py I want to sync all slash commands with all guilds in discord.py
My code
import discord
from discord import app_commands
from discord.ext import commands

intents = discord.Intents.default()
client = discord.Client(intents=intents)

tree = app_commands.CommandTree(client)

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')
    try:
        await tree.sync(guild=discord.Object(id=11234411))

        print(f'Synced')
    except Exception as e:
        print(e)

@tree.command(name="ping", description="Simple ping pong command", guild=discord.Object(id=1032007648566059142))
async def ping(interaction):
    await interaction.response.send_message(f"Pong", ephemeral=True)

I tried to just delete the guild=discord.Object(id=11234411) But its not working

A: You shouldn't sync your commands in on_ready because it's unnecessary and can get you ratelimited. You should create a owner-only command to sync the command tree instead.
@tree.command(name='sync', description='Owner only')
async def sync(interaction: discord.Interaction):
    if interaction.user.id == YOUR_ID:
        await tree.sync()
        print('Command tree synced.')
    else:
        await interaction.response.send_message('You must be the owner to use this command!')

You don't need to include guild anywhere because you're syncing global commands. Your extra saftey/security you can create a message command instead.


text:
Q: pip module is not installed If I try to use pip, it says it is not installed. If I import it, it says no module named symbol. If I try importing symbol, it says no module named symbol. I don't know what to do. My OS is Ubuntu 22.04 jammy jellyfish and it is up to date. It has python 3.10.4.

A: Try typing pip in Terminal if it gives you an error you need to install pip. Otherwise, make sure the module/library you are working with supports your version.


text:
Q: Send accelerator with mouse to perform selection of text I need to make selection of text using mouse instead of ctrl+A
I tried:
sendAcceleratorKey(MouseEvent.BUTTON1, "");

but I don't know which argument could I set to say make a click with mouse and let the mouse enforced to select the text.

A: If the text is in a JTextComponent, selectAll() may be a suitable choice in your MouseListener.
Addendum: You may also be able to leverage the select-all Action, which is bound to control-A or meta-A by default on various platforms.
Your sscce may be helpful in deciding. There's a related example here.


text:
Q: Why is FromOADate getting day and month wrong way round? I have the date in an excel file "03/07/2013"
When I use the DateTime.FromOADate() Microsoft.Excel.Interop method in my project to read this back  I am getting the date back as "07/03/2013".
Have had a look at the other answers relating to this on stack overflow, none of which seem to solve this problem for me.

A: Excel is set to display day month year and your c# program is set to display month day year.
or, the opposite of that.
Change the display format of the one you don't like.


text:
Q: Rounding Pixel Error Having trouble with a layout going out of alignment by 1 pixel while resizing the browser in Safari. I have a vertically repeating background with a container that includes a header div and a wrapper containing the page content.You can view the site here: view here
Here is some of the CSS:
body {color: #666666; background: #f2f2f2 url('../images/blue/background_site.gif') repeat-y center center; margin: 0; padding: 0;}

#Container {
    width: 960px;
    border-collapse: collapse;
    margin:0px;
    padding:0px;
    margin-left: auto;
    margin-right: auto;
}

#Header {height: 98px; background: url('../images/blue/background_header.gif') repeat-x bottom left; margin-bottom: 20px;}

A: Ended up using a Javascript hack, it works but isn't the best solution.


text:
Q: about bounded boxes of objects i'm trying to compose a dataset for the detection of soccer players, ball etc.. in a soccer game, i'm using alexeyAB Darknet framework,
So in the labeling phase in each image there are at least 8 players a ball and other stuff, at some point it is logical to think about the fact that i will have enough instances per player, but not enough for the ball and the goalkeeper for example,
so can i only marking bounded boxes the ball and other things avoiding to do it with the players to not waste time?

A: If you are training the model on your own dataset, I would recommend limiting the number of labels/classes in your data to what you seek. For example if you only want your model to see balls, goal-posts and Not players, simply keep the classes as balls and goal-posts. (This reminds me of a classification problem where 0 stands for balls and 1 stands for goal-post). P.S you mentioned object detection and Not Localization, which is the purpose of the YOLO models.


text:
Q: How to change default directory access for a web app? Currently when I open the main URL xyz.com of my web app, it takes the web app to xyz.com/abc/index.php.
I have another directory called 'ghi' in addition to 'abc' in my web app.
I want the web app to open with xyz.com/ghi/index.php instead of xyz.com/abc/index.php.
How do I achieve this so that upon entering xyz.com in a browser, the web app is taken to xyz.com/ghi/index.php instead of xyz.com/abc/index.php?

A: simply ,place it as the first line after   in index.php file
 header('location:xyz.com/ghi/index.php');

or else Cpanel and redirect to the URL

A: I think you can (and should) achive this goal with using a .htaccess file..
Here is a sample generated via this tool
//Rewrite to www
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com/ghi/index.php[nc]
RewriteRule ^(.*)$ http://www.example.com/ghi/index.php/$1 [r=301,nc]

Hope this helps..

A: Create a file index.php inside xyz directory with following code:

 Click Here


text:
Q: Subversion post-commit with different user I've installed subversion and have the following setup:
Repo:
/home/svn/tester (apache:apache)
The site is:
/var/www/tester (tester:tester)
I've checked out the tester repo to /var/www/tester
in the /home/svn/tester/hooks/post-commit I have:
sudo -u tester /usr/bin/svn update /home/tester --username aaa --password bbb
What I am trying to do is keep the owners of the files in /home/svn/tester = apache
and the owner of files in /var/www/tester = tester
I have added to /etc/sudoers:
tester ALL=(ALL) NOPASSWD: /usr/bin/svn
I've commented out requiretty in /etc/sudoers:
#Defaults    requiretty
Once I run the commit I receive the following message (in tortoisesvn):
Commit failed (details follow):
MERGE of '/svn/tester': 200 OK (https://[site name])

Am I going about this the correct way? If so how can I get past this error?

A: You've configured your repository below the normal web stuff.
/var/_www_/tester

That won't work: SVN requests some DAV stuff, but it only gets normal answers.
That's why 200 OK is actually an error in this case.
Move your repository out of the www tree and you should be fine.


text:
Q: Java script click counter: problems with origin policy? Is it possible to create a Javascript file that act as "click counter"?
What I want to do is that I put that Javascript file in my domain
mydomain.com/js/clickcounter.js

And anyone can include it to start counting clicks..
Example for THEIRdomain.com/index.html
 <script src="mydomain.com/js/clickcounter.js"></script>

And a possible script:
function myDomain_TrackClicks(){
    xhttp.open("POST", "mydomain.com/trackClicks.php", true);
    xhttp.send( "pagevisited=" + encodeURIComponent( window.location.href));
}

if(window.attachEvent) {
    window.attachEvent('onload', myDomain_TrackClicks);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function(evt) {
            curronload(evt);
            myDomain_TrackClicks(evt);
        };
        window.onload = newonload;
    } else {
        window.onload = myDomain_TrackClicks;
    }
}

Or is that limited by some origin policy? Origin policy really confuses me.

A: All thats required is your server must respond with the correct HTTP headers when mydomain.com/js/clickcounter.js is requested by the browser.
Specifically, this header must be included in the response headers:
Access-Control-Allow-Origin: *

This tells the browser that the resource may be requested from any origin.
Recommended reading - https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS


text:
Q: How to send gmp variable such as mpz_t throught MPI_Send #include <stdio.h>
#include <gmp.h>
#include <mpi.h>

int main(int *argc, char **argv)
{
    int rank;
    mpz_t a;
    mpz_t b;
    mpz_init(a);
    mpz_init(b);
    mpz_set_ui(a,23000000000000000000000000001);
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    if(rank==0)
    {
        MPI_Send(&a,1,MPI_INT,1,100,MPI_COMM_WORLD);
    }

    if(rank==1)
    {
        MPI_Recv(&b,1,MPI_INT,0,100,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
    }
    MPI_Finalize();
    return 1;
}

This code produce error so please help me how to send mpz_t variable through MPI_Send function.

A: I found a presentation www.macs.hw.ac.uk/~hwloidl/Courses/F21DP/gph_milan15_handout.pdf where, on slides 86 and 88, they send a multiprecision integer by marshalling it to/from a string using gmp_sprintf() and gmp_sscanf().
Actually, I notice they're using rationals of type mpq_t but I guess the same approach would work for mpz_t.


text:
Q: Unrotate final path of path that has multiple translates and rotations I'm working in WPF, but SVG would probably be the same so I've tagged it. I have some paths that I am rotating/translating multiple times and in it's final rendered position, I would like to take the path and "unrotate" at that position. The issue is that I can't find the right CenterX/CenterY for this (renderTransformOrigin="0.5, 0.5" doesn't work because the final rendered path has been translated). Finding the boundingbox of the final rendered shape also doesn't not work to rotate it back.
Here's what the non-rotated paths look like:

And here's what they look like when rotated:

To get this, here's my XAML.
<Canvas>
            <Rectangle Fill="DarkGray" Opacity=".3"  Canvas.Left="168.48"  Width="100.08" Height="200.16" Canvas.Top="164.88"/>
            <!-- ////////////////// -->

            <!-- ///shape/// -->
            <Path Stroke="Purple" x:Name="purpleShape" Data="M0,150 25,150 25,0 75,0 75,150 100,150 50,200 Z" StrokeThickness="2">
                <Path.RenderTransform >
                    <TransformGroup>
                        <!--shape transforms-->
                        <RotateTransform Angle="30" CenterX="50" CenterY="100"/>
                        <TranslateTransform X="46.08" Y="0"/>
                    </TransformGroup>
                </Path.RenderTransform>
            </Path>

            <!-- ///childGroup/// -->
            <!-- ///childGroup.shape/// -->
            <Path Stroke="Green" x:Name="greenShape" Data="M0,25 150,25 150,0 200,50 150,100 150,75 0,75 Z" StrokeThickness="2">
                <Path.RenderTransform >
                    <TransformGroup>
                        <!--shape transforms-->
                        <RotateTransform Angle="330" CenterX="100" CenterY="50"/>
                        <TranslateTransform X="50" Y="200" />
                        <!--childgroup transforms-->
                        <RotateTransform Angle="60" CenterX="150" CenterY="150"/>
                        <TranslateTransform X="0" Y="96.46" />
                    </TransformGroup>
                </Path.RenderTransform>
            </Path>
            <!-- ///childGroup.shape/// -->
            <Path Stroke="Red" x:Name="redShape" Data="M0,150 25,150 25,0 75,0 75,150 100,150 50,200 Z " StrokeThickness="2">
                <Path.RenderTransform >
                    <TransformGroup>
                        <!--shape transforms-->
                        <RotateTransform Angle="330" CenterX="50" CenterY="100"/>
                        <TranslateTransform X="150" Y="0" />
                        <!--childgroup transforms-->
                        <RotateTransform Angle="60" CenterX="150" CenterY="150"/>
                        <TranslateTransform X="0" Y="96.46"/>
                    </TransformGroup>
                </Path.RenderTransform>
            </Path>
         </Canvas>

Notice in this code <Rectangle Fill="DarkGray" .... as the first element. This is where I am hoping to "unrotate" the red path to, so that it fits in this bounding box (the size of this is the size of the non-rotated bounding box).
Here's what this looks like:

The final render path of the red shape is: Data="M150,283.064 171.651,295.564 246.651,165.66 289.952,190.66 214.952,320.564 236.603,333.064 168.301,351.365 Z " and now I want to unrotate that (-30 degrees) so that it is pointing down again - again, at this same exact location. (again, getting the bounding box of the red shape doesn't work as it has a different center x/y than I need in order to unrotate).
So using another shape (orange shape) and the path data above, I place it on the red shape and try to rotate it back (i.e. so it doesn't appear rotated).
                <Path RenderTransformOrigin="0.5,0.5" Stroke="Orange" x:Name="unrotatedShape" Data="M150,283.064 171.651,295.564 246.651,165.66 289.952,190.66 214.952,320.564 236.603,333.064 168.301,351.365 Z " StrokeThickness="4">
                <Path.RenderTransform >
                    <TransformGroup>
                        <RotateTransform Angle="-30" CenterX="0.5" CenterY="0.5"/>
                    </TransformGroup>
                </Path.RenderTransform>
            </Path>

And this is the result:

This is obviously getting rotated from the path as it is both rotated and translated (e.g.  Data="M150,283.064...). It's that 150,283.064 that are causing the issue.
So I'm asking for solutions that allow me to "unrotate" the "red shape" (the rendering of which is the "orange shape") at the same position so that it looks like the following (blue shape).

A: Caveat
Your grey rectangle is not the same size as the red arrow. I'll place the center of the red arrow on the center of the grey box.
Setup
Rotating around some point, P, is equivalent to translating P to the origin, rotating around the origin, and then translating the origin back to P again.
Define a function which does that, and check how it modifies the individual coordinates. (Below is Mathematica.)
In[1] :=
RotateVAroundP[V_, \[Theta]_, Px_, Py_] := {{Cos[\[Theta]], -Sin[\[Theta]]}, {Sin[\[Theta]], Cos[\[Theta]]}} . (V - {{Px}, {Py}}) + {{Px}, {Py}}
MatrixForm[Simplify[RotateVAroundP[{{x}, {y}}, \[Theta], Px, Py]]]

Out[2]//MatrixForm =
MatrixForm[{{Px + (-Px + x)*Cos[\[Theta]] + (Py - y)*Sin[\[Theta]]}, {Py + (-Py + y)*Cos[\[Theta]] + (-Px + x)*Sin[\[Theta]]}}]

Testing
Rotate the point (1,0), 90 degrees around the point (1,1) to (2,1).
In[3] :=
MatrixForm[RotateVAroundP[{{1}, {0}}, 90*Degree, 1, 1]]

Out[3]//MatrixForm =
MatrixForm[{{2}, {1}}]

Solving
Start with the center of the original red arrow: V1 = (50, 100). Apply all the transformations. The final transformation has the desired -30 degrees, around an unknown point (x,y). This final rotation needs to place the center of the arrow on the center of the box, which is (168.48 + 100.08/2, 164.88 + 200.16/2).
In[5] :=
V1 = {{50}, {100}};
V2 = RotateVAroundP[V1, 330*Degree, 50, 100];
V3 = V2 + {{150}, {0}};
V4 = RotateVAroundP[V3, 60*Degree, 150, 150];
V5 = FullSimplify[V4 + {{0}, {96.46}}];
Solve[RotateVAroundP[V5, -30*Degree, x, y] == {{168.48 + 100.08/2}, {164.88 + 200.16/2}}]

Out[10] =
{{x -> 218.78146997001204, y -> 264.4524797111341}}

Verifying
I don't know anything about WPF, but I dabble in SVG. Working from the initial opaque arrow to the transparent one, the subsequent transformations in each element are applied from right to left.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink" viewBox="-25 -25 350 425" width="560" height="680">
    <rect xmlns="http://www.w3.org/2000/svg" fill="none" stroke="black" x="0" y="0" width="300" height="375"/>
    <rect fill="darkgray" fill-opacity=".3" x="168.48" width="100.08" height="200.16" y="164.88"/>
    <path stroke="red" id="redShape" d="M0,150 25,150 25,0 75,0 75,150 100,150 50,200 Z " stroke-width="2" fill=" red"/>
    <use href="#redShape" transform="rotate(330, 50, 100)" fill-opacity=".8"/>
    <use href="#redShape" transform="translate(150,0) rotate(330, 50, 100)" fill-opacity=".6"/>
    <use href="#redShape" transform="rotate(60,150,150) translate(150,0) rotate(330, 50, 100)" fill-opacity=".4"/>
    <use href="#redShape" transform="translate(0,96.46) rotate(60,150,150) translate(150,0) rotate(330, 50, 100)" fill-opacity=".2"/>
    <use href="#redShape" transform="rotate(-30, 218.781, 264.452) translate(0,96.46) rotate(60,150,150) translate(150,0) rotate(330, 50, 100)" fill-opacity="0"/>
</svg>

Generalizing
If you want to rotate the point V to the point W by applying a rotation θ around a point P, the coordinates for P are the expressions below.
In[11] :=
FullSimplify[Solve[RotateVAroundP[{{Vx}, {Vy}}, \[Theta], Px, Py] == {{Wx}, {Wy}}, {Px, Py}]]

Out[11] =
{{Px -> (1/2)*(Vx + Wx + (Vy - Wy)*Cot[\[Theta]/2]), Py -> (1/2)*(Vy + Wy + (-Vx + Wx)*Cot[\[Theta]/2])}}


text:
Q: Protractor with typescript and mocha framework and chai assertions i get error: timeout of 2000ms exceeded I am not able to execute a simple test in protractor with mocha, typescript and chai.
I get the below error:
"Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves."
After the browser.get() line is executed, the page opens and closes abruptly with the above error. I do not have any other line executing after this, as i wanted this to be executed first successfully.
I have tried to put browser.sleep() as well, no luck.
I have tried all options mentioned in all similar issues (different timeouts here and there) none works.
My package.json has:
Protractor version : 7.0.0,
Mocha: 8.1.3,
typescript: 3.4.3,
jasmine:3.6.1,
@types/.. all latest versions,
chai and chai-as-promised
I am also using async/await.
I am stuck with this for more than 2 weeks now. Please help with ideas.
Thanks in advance!!!

A: Got my vm today, and found out that mochaOpts was spelled wrong in my config, it was spelt as mochaopts, which was the issue, because of which timeout was not getting considered. After i changed the spelling, timeout error didnt come and test passed.
thought of sharing it, as we might end up doing this unknowingly.
thank you!!!!
have a good learning.