text:
Q: Xcode loop array of URLs with NSURLSessionDataTask I must be making this harder than it is... or implementing the solutions I see online incorrectly.
I have an array of URLs which I would like to loop through and push the results to a dictionary in order or the array. How can I make it wait for the dictionary to be updated before running the next request? Basically I want to make the calls synchronously in a background thread.
Here is where I call the download:
for (NSString *path in paths) {

    NSURLSession *session = [NSURLSession sessionWithConfiguration [NSURLSessionConfiguration defaultSessionConfiguration]];

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:10];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error)
                                                {

                                                }
                                                else
                                                {
                                                    NSError *parsingError = nil;
                                                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:NSJSONReadingAllowFragments
                                                                                error:&error];
                                                    if (parsingError)
                                                    {

                                                    }
                                                    else
                                                    {
                                                        [myDictionary addObject:dict];
                                                    }
                                                }
                                            }];
    [task resume];
}

A: Unless one request really requires the results of the prior request before being issued (which is not the case here), you should not run them sequentially. It may feel more logical to issue the sequentially, but you pay a huge performance penalty to do so. Issue them concurrently, save the results in some unordered structure (like a dictionary), and then when all done, build your ordered structure.
NSMutableDictionary *results = [NSMutableDictionary dictionaryWithCapacity:[paths count]];

// don't create new session for each request ... initialize this outside of the loop

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; // or since you're not doing anything special here, use `sharedSession`

// since we're going to block a thread in the process of controlling the degree of
// concurrency, let's do this on a background queue; we're still blocking
// a GCD worker thread as these run (which isn't ideal), but we're only using
// one worker thread.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    // only do for requests at a time, so create queue a semaphore with set count

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(4); // only do four requests at a time

    // let's keep track of when they're all done

    dispatch_group_t group = dispatch_group_create();

    // now let's loop through issuing the requests

    for (NSString *path in paths) {
        dispatch_group_enter(group);                               // tell the group that we're starting another request

        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); // wait for one of the four slots to open up

        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path]
                                                      cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                  timeoutInterval:10];

        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            if (error) {
                // ...
            } else {
                NSError *parsingError = nil;
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                if (parsingError) {

                } else {
                    // synchronize updating of dictionary

                    dispatch_async(dispatch_get_main_queue(), ^{
                        results[path] = dict;
                    });
                }
            }

            dispatch_semaphore_signal(semaphore);                  // when done, flag task as complete so one of the waiting ones can start
            dispatch_group_leave(group);                           // tell the group that we're done
        }];
        [task resume];
    }

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        // trigger whatever you want when they're all done

        // and if you want them in order, iterate through the paths and pull out the appropriate result in order
        for (NSString *path in paths) {
            // do something with `results[path]`
        }
    });
});

I tried to reduce the amount of extra dependencies here, so I used dispatch groups and semaphores. In the above, I use semaphores to constrain the degree of concurrency and I use dispatch group to identify when it's all done.
Personally, I wouldn't use semaphores and groups, but rather I'd wrap these requests in asynchronous NSOperation subclass, but I was trying to limit the changes I made to your code. But the NSOperation idea is logically the same as the above: Run them concurrently, but constrain the degree of concurrency so you don't end up with them timing out on you, and trigger the retrieval of the results only when all the results are retrieved.


text:
Q: Diamond inheritance (C++) I know that having diamond inheritance is considered bad practice. However, I have 2 cases in which I feel that diamond inheritance could fit very nicely. I want to ask, would you recommend me to use diamond inheritance in these cases, or is there another design that could be better.
Case 1: I want to create classes that represent different kinds of "Actions" in my system. The actions are classified by several parameters:

*

*The action can be "Read" or "Write".

*The action can be with delay or without delay (It is not just 1 parameter. It changes the behavior significantly).

*The action's "flow type" can be FlowA or FlowB.

I intend to have the following design:
// abstract classes
class Action
{
    // methods relevant for all actions
};
class ActionRead      : public virtual Action
{
    // methods related to reading
};
class ActionWrite     : public virtual Action
{
    // methods related to writing
};
class ActionWithDelay : public virtual Action
{
    // methods related to delay definition and handling
};
class ActionNoDelay   : public virtual Action  {/*...*/};
class ActionFlowA     : public virtual Action  {/*...*/};
class ActionFlowB     : public virtual Action  {/*...*/};

// concrete classes
class ActionFlowAReadWithDelay  : public ActionFlowA, public ActionRead, public ActionWithDelay
{
    // implementation of the full flow of a read command with delay that does Flow A.
};
class ActionFlowBReadWithDelay  : public ActionFlowB, public ActionRead, public ActionWithDelay  {/*...*/};
//...

Of course, I will obey that no 2 actions (inheriting from Action class) will implement the same method.
Case 2: I implement the composite design pattern for a "Command" in my system. A command can be read, written, deleted, etc. I also want to have a sequence of commands, which can also be read, written, deleted, etc. A sequence of commands can contain other sequences of commands.
So I have the following design:
class CommandAbstraction
{
    CommandAbstraction(){};
    ~CommandAbstraction()=0;
    void Read()=0;
    void Write()=0;
    void Restore()=0;
    bool IsWritten() {/*implemented*/};
    // and other implemented functions
};

class OneCommand : public virtual CommandAbstraction
{
    // implement Read, Write, Restore
};

class CompositeCommand : public virtual CommandAbstraction
{
    // implement Read, Write, Restore
};

In addition, I have a special kind of commands, "Modern" commands. Both one command and composite command can be modern. Being "Modern" adds a certain list of properties to one command and composite command (mostly same properties for both of them). I  want to be able to hold a pointer to CommandAbstraction, and initialize it (via new) according to the needed type of command. So I want to do the following design (in addition to the above) :
class ModernCommand : public virtual CommandAbstraction
{
    ~ModernCommand()=0;
    void SetModernPropertyA(){/*...*/}
    void ExecModernSomething(){/*...*/}
    void ModernSomethingElse()=0;

};
class OneModernCommand : public OneCommand, public ModernCommand
{
    void ModernSomethingElse() {/*...*/};
    // ... few methods specific for OneModernCommand
};
class CompositeModernCommand : public CompositeCommand, public ModernCommand
{
    void ModernSomethingElse() {/*...*/};
    // ... few methods specific for CompositeModernCommand
};

Again, I will make sure that no 2 classes inheriting from CommandAbstraction class will implement the same method.
Thank you.

A: There's a design-quality difference between implementation-oriented diamond inheritance where implementation is inherited (risky), and subtyping-oriented inheritance where interfaces or marker-interfaces are inherited (often useful).
Generally, if you can avoid the former, you're better off since somewhere down the line the exact invoked method may cause problems, and the importance of virtual bases, states, etc., starts mattering. In fact, Java wouldn't allow you to pull something like that, it supports only the interface hierarchy.
I think that the "cleanest" design you can come up for this is to effectively turn all your classes in the diamond into mock-interfaces (by having no state information, and having pure virtual methods). This reduces the impact of ambiguity. And of course, you can use multiple and even diamond inheritance for this just like you would use implements in Java.
Then, have a set of concrete implementations of these interfaces that can be implemented in different ways (E.g., aggregation, even inheritance).
Encapsulate this framework so that external clients only get the interfaces and never interact directly with the concrete types, and make sure to thoroughly test your implementations.
Of course, this is a lot of work, but if you're writing a central and reusable API, this might be your best bet.

A: I ran into this problem just this week and found an article on DDJ that explained the problems and when you should or shouldn't be concerned about them.  Here it is:
"Multiple Inheritance Considered Useful"

A: "Diamonds" in the inheritance hierarchy of interfaces is quite safe - it's inheritance of code that get's you into hot water.
To get code reuse, I advise you to consider mixins (google for C++ Mixins if you are unfamiliar with the tequnique).  When using mixins you feel like you can "go shopping" for the code snippets that you need to implement you class without using multiple inheritance of stateful classes.
So, the pattern is - multiple inheritance of interfaces and a single chain of mixins (giving you code reuse) to help implement the concrete class.
Hope that helps!

A: Inheritance is the second strongest (more coupling) relations in C++, preceded only by friendship. If you can redesign into using only composition your code will be more loosely coupled. If you cannot, then you should consider whether all your classes should really inherit from the base. Is it due to implementation or just an interface? Will you want to use any element of the hierarchy as a base element? Or are just leaves in your hierarchy that are real Action's? If only leaves are actions and you are adding behavior you can consider Policy based design for this type of composition of behaviors.
The idea is that different (orthogonal) behaviors can be defined in small class sets and then bundled together to provide the real complete behavior. In the example I will consider just one policy that defines whether the action is to be executed now or in the future, and the command to execute.
I provide an abstract class so that different instantiations of the template can be stored (through pointers) in a container or passed to functions as arguments and get called polymorphically.
class ActionDelayPolicy_NoWait;

class ActionBase // Only needed if you want to use polymorphically different actions
{
public:
    virtual ~Action() {}
    virtual void run() = 0;
};

template < typename Command, typename DelayPolicy = ActionDelayPolicy_NoWait >
class Action : public DelayPolicy, public Command
{
public:
   virtual run() {
      DelayPolicy::wait(); // inherit wait from DelayPolicy
      Command::execute();  // inherit command to execute
   }
};

// Real executed code can be written once (for each action to execute)
class CommandSalute
{
public:
   void execute() { std::cout << "Hi!" << std::endl; }
};

class CommandSmile
{
public:
   void execute() { std::cout << ":)" << std::endl; }
};

// And waiting behaviors can be defined separatedly:
class ActionDelayPolicy_NoWait
{
public:
   void wait() const {}
};

// Note that as Action inherits from the policy, the public methods (if required)
// will be publicly available at the place of instantiation
class ActionDelayPolicy_WaitSeconds
{
public:
   ActionDelayPolicy_WaitSeconds() : seconds_( 0 ) {}
   void wait() const { sleep( seconds_ ); }
   void wait_period( int seconds ) { seconds_ = seconds; }
   int wait_period() const { return seconds_; }
private:
   int seconds_;
};

// Polimorphically execute the action
void execute_action( Action& action )
{
   action.run();
}

// Now the usage:
int main()
{
   Action< CommandSalute > salute_now;
   execute_action( salute_now );

   Action< CommandSmile, ActionDelayPolicy_WaitSeconds > smile_later;
   smile_later.wait_period( 100 ); // Accessible from the wait policy through inheritance
   execute_action( smile_later );
}

The use of inheritance allows public methods from the policy implementations to be accessible through the template instantiation. This disallows the use of aggregation for combining the policies as no new function members could be pushed into the class interface. In the example, the template depends on the policy having a wait() method, which is common to all waiting policies. Now waiting for a time period needs a fixed period time that is set through the period() public method.
In the example, the NoWait policy is just a particular example of the WaitSeconds policy with the period set to 0. This was intentional to mark that the policy interface does not need to be the same. Another waiting policy implementation could be waiting on a number of milliseconds, clock ticks, or until some external event, by providing a class that registers as a callback for the given event.
If you don't need polymorphism you can take out from the example the base class and the virtual methods altogether. While this may seem overly complex for the current example, you can decide on adding other policies to the mix.
While adding new orthogonal behaviors would imply an exponential growth in the number of classes if plain inheritance is used (with polymorphism), with this approach you can just implement each different part separately and glue it together in the Action template.
For example, you could make your action periodic and add an exit policy that determine when to exit the periodic loop. First options that come to mind are LoopPolicy_NRuns and LoopPolicy_TimeSpan, LoopPolicy_Until. This policy method ( exit() in my case ) is called once for each loop. The first implementation counts the number of times it has been called an exits after a fixed number (fixed by the user, as period was fixed in the example above). The second implementation would periodically run the process for a given time period, while the last one will run this process until a given time (clock).
If you are still following me up to here, I would indeed make some changes. The first one is that instead of using a template parameter Command that implements a method execute() I would use functors and probably a templated constructor that takes the command to execute as parameter. The rationale is that this will make it much more extensible in combination with other libraries as boost::bind or boost::lambda, since in that case commands could be bound at the point of instantiation to any free function, functor, or member method of a class.
Now I have to go, but if you are interested I can try posting a modified version.

A: With the first example.....
its whether ActionRead   ActionWrite need to be subclasses of action at all.
since you are going to end up with one concrete class that will be an action anyways, you could just inherit actionread and actionwrite without them being actions in themselves.
though, you could invent code that would require them to be actions.   But in general I'd try and separate Action, Read, Write, and Delay   and just the concrete class mixes all that together

A: With out knowing more of what you are doing,
I would probably reorganize things a bit.
Instead of multiple inheritence with all these versions of action,
I would make polymorphic reading and writing and writing classes,
instanciated as delegates.
Something like the following (which has no diamond inheritence):
Here I present one of many ways implementing optional Delay,
and assume the delay methodology is the same for all readers.
each subclass might have their own implementation of delay
in which case you would pass down to Read and instance of the
respective derived Delay class.
class Action // abstract
{
   // Reader and writer would be abstract classes (if not interfaces)
   // from which you would derive to implement the specific
   // read and write protocols.

   class Reader // abstract
   {
      Class Delay {...};
      Delay *optional_delay; // NULL when no delay
      Reader (bool with_delay)
      : optional_delay(with_delay ? new Delay() : NULL)
      {};
      ....
   };

   class Writer {... }; // abstract

   Reader  *reader; // may be NULL if not a reader
   Writer  *writer; // may be NULL if not a writer

   Action (Reader *_reader, Writer *_writer)
   : reader(_reader)
   , writer(_writer)
   {};

   void read()
   { if (reader) reader->read(); }
   void write()
   { if (writer)  writer->write(); }
};

Class Flow : public Action
{
   // Here you would likely have enhanced version
   // of read and write specific that implements Flow behaviour
   // That would be comment to FlowA and FlowB
   class Reader : public Action::Reader {...}
   class Writer : public Action::Writer {...}
   // for Reader and W
   Flow (Reader *_reader, Writer *_writer)
   : Action(_reader,_writer)
   , writer(_writer)
   {};
};

class FlowA :public Flow  // concrete
{
    class Reader : public Flow::Reader {...} // concrete
    // The full implementation for reading A flows
    // Apparently flow A has no write ability
    FlowA(bool with_delay)
    : Flow (new FlowA::Reader(with_delay),NULL) // NULL indicates is not a writer
    {};
};

class FlowB : public Flow // concrete
{
    class Reader : public Flow::Reader {...} // concrete
    // The full implementation for reading B flows
    // Apparently flow B has no write ability
    FlowB(bool with_delay)
    : Flow (new FlowB::Reader(with_delay),NULL) // NULL indicates is not a writer
    {};
};

A: For case 2, isn't a OneCommand just a special case of CompositeCommand?  If you eliminate OneCommand and allow CompositeCommands to only have one element, I think your design gets simpler:
              CommandAbstraction
                 /          \
                /            \
               /              \
        ModernCommand      CompositeCommand
               \               /
                \             /
                 \           /
             ModernCompositeCommand

You still have the dreaded diamond, but I think this may be an acceptable case for it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get query step OR count returned data points My goal is to show the currently used step in a panel or in the panel title. The only way to know the step right now (at least from my knowledge) is to hover over a panel and look at the x-axis.
How can I get the step value?
I don't think that Grafana has a global variable that contains the step. There are only vars like $__range_s.
So now I am left with Prometheus. I'm trying to achieve it with something like this:
vector($__range_s) / count_datapoints(sum(counter_total[$__range_s]))

count_datapoints does not exist. I have tried count, but it counts the number of time series returned, not the number of points along the time axis. So, do you know da wae?

Edit: Please see my answer below, the question does not make sense for my use case.

A: Okay, flawed thought by me. The used step is not the same over a whole dashboard. So there is no way I could have a single panel that displays the current step.
At best I could calculate it panel by panel and even this makes no sense even though this is possible with the alternative version of PromQL https://github.com/VictoriaMetrics/VictoriaMetrics/wiki/MetricsQL


text:
Q: What is the easiest way to convert a bunch of text files from LF (Unix) to CRLF (Windows) in a single run? There is a directory tree on a Windows7 machine containing a few hundred text files that I want to convert from LF to CRLF.
I already found a Win32 version of UNIX2DOS but that one accepts only one file at a time for input whereas I want to convert a whole set of directories and subdirectories recursively in a single run.
What is the easiest way to accomplish that task?

A: for one directory, open a command-prompt window, cd to the desired folder and
for %f in (*.txt) do UNIX2DOS %f ...

or for all subdirectories use the /R option
for /R %f in (*.txt) do UNIX2DOS %f ...

It may be worth remembering that, unlike notepad, editors like wordpad and notepad++ are happy with LF as line endings.
If you are converting a bunch of text files, you might also consider converting to UTF-8 using something like recode or iconv.


text:
Q: Mysql Regex ending with language iso code but not other chars (non alphabetical) EDITED:
i have a mysql table row with 'option_name'.
The option names are:
my_option_en
my_option_de

my_option_adv_en
my_option_adv_de
my_option_sc_en
my_option_sc_de
my_option_labs_en
my_option_labs_de

A query for the option name my_option_ should return my_option_en and my_option_de but not any other option names
What i need is look for given string ending with 2 any letters (language iso
 code) and no any character after the 2 language iso letters.
How can i realize it with Mysql REGEXP? Thanks

A: This will discard every row where option_name starts with my_option_adv:
select option_name
from yourtable
where not(option_name regexp '^my_option_adv')

Demo here: db-fiddle.com

A: In MySQL regexp form, you would need
SELECT *
FROM yourtable
WHERE option_name REGEXP  '^my_option_[a-z]{2}$'

A: WHERE CHAR_LENGTH(option_name) = 12

will do exactly what you stated.  But I suspect that is not good enough.


text:
Q: Jenkings error: Exec exit status not zero. Status [-1] when I try to run npm install in the exec command I have a Jenkins server in my localhost that is trying to connect to a remote server. Using the plugin ssh publish over I am copying my workspace to a folder in my remote server.
Now what I whould like to do is ones the folders are copied across I would like to run npm install and npm start from jenkins to start the node service in the remote computer but I get the following error:
SSH: EXEC: STDOUT/STDERR from command [npm intall && npm start && exit
] ...
SSH: EXEC: completed after 200 ms
SSH: Disconnecting configuration [api] ...
ERROR: Exception when publishing, exception message [Exec exit status not zero. Status [-1]]
Build step 'Send build artifacts over SSH' changed build result to UNSTABLE
Finished: UNSTABLE
my screen in my job looks like this :

can someone tell me why this simple exec commands are making the build unstable? the files are being copied fine the only problem re the commands which don't do anything.
Thanks

A: Looks like you have typo in running first command itself, post successful transfer of files.
You can enable verbose output to get more info of ssh Transfer : https://web.archive.org/web/20181012120424/https://wiki.jenkins.io/download/attachments/53608875/pos-server-advanced.png?version=2&modificationDate=1321576167000&api=v2
'Çlick' Advanced.. button below 'Name' textbox & enable 'Verbose output in console'
First it does file Transfer then runs command.
So try running command in sequence first by correcting typo on 'npm install'
And use echo $? after every command run


text:
Q: PLSQL DEFINE variable populate using cursor I need some help with dynamic SQL and cursor.
I have stored procedure which has DEFINE variables.
How I can populate DEFINE variable using cursor?
I want to use another table as source for cursor and insert these results to another table.
Here is simplified example about my problem:
CREATE OR REPLACE PROCEDURE usp_TEST
AS
BEGIN

DEFINE vTable = 'TABLE_NAME'; -- How I can create cursor loop, so I can loop and change this table name using another table as source?

INSERT INTO results
WITH CTE_main
AS
(
    SELECT
        TABLE_NAME
    FROM dest_TABLES
)
SELECT
    'SELECT * FROM ' || '&vTable' || ' source INNER JOIN ' ||  cte.TABLE_NAME || ' dest ON source.ID = dest.ID;' AS query
FROM CTE_main cte

END;

Source table contains only table names:
TABLE_ONE
TABLE_TWO
etc...
Result should be something like this:
SELECT * FROM TABLE_ONE source INNER JOIN DEST_ONE dest ON source.ID = dest.ID;
SELECT * FROM TABLE_ONE source INNER JOIN DEST_TWO dest ON source.ID = dest.ID;
SELECT * FROM TABLE_TWO source INNER JOIN DEST_ONE dest ON source.ID = dest.ID;
SELECT * FROM TABLE_TWO source INNER JOIN DEST_TWO dest ON source.ID = dest.ID;

A: Are you after something like:
WITH dest_tables AS (SELECT 'TABLE_ONE' table_name FROM dual UNION ALL
                     SELECT 'TABLE_TWO' table_name FROM dual),
        cte_main AS (SELECT 'DEST_ONE' table_name FROM dual UNION ALL
                     SELECT 'DEST_TWO' table_name FROM dual)
SELECT 'SELECT * FROM ' || dt.table_name || ' src INNER JOIN ' ||  cm.TABLE_NAME || ' dest ON src.ID = dest.ID;' AS query
FROM   dest_tables dt
       CROSS JOIN cte_main cm
ORDER BY dt.table_name, cm.table_name;

QUERY
-------------------------------------------------------------------------
SELECT * FROM TABLE_ONE src INNER JOIN DEST_ONE dest ON src.ID = dest.ID;
SELECT * FROM TABLE_ONE src INNER JOIN DEST_TWO dest ON src.ID = dest.ID;
SELECT * FROM TABLE_TWO src INNER JOIN DEST_ONE dest ON src.ID = dest.ID;
SELECT * FROM TABLE_TWO src INNER JOIN DEST_TWO dest ON src.ID = dest.ID;

? (N.B. I used the two subqueries in the with-clause to mimic data in your tables; you wouldn't need those two subqueries, you'd just use your tables instead.)
No PL/SQL is required, just SQL. You could take the above statement and use it in an insert statement inside a PL/SQL program, though.


text:
Q: how to hide a nav button declare in the index page? I declare a nav button in index page and it shown all the page But  I want remove from my home page. How can I remove that button in that specific pages

A: make $rootScope array of pages where you don't want to show the button. Then use ng-if in button tag to show n hide the button
<button ng-if="root.pageIgnore.indexOf($route.current.name) === -1">Shy Button</Button>


text:
Q: Handling touch outside of the parent component Area marked with blue border doesn't handle touches
I've created a custom TabBar and Component with TouchableOpacity (highlighted with golden). The problem is it only handles touches inside the bottom view. zIndex: 1 didn't solve the problem. Is there any way to fix this?
Here is the src of my middle button:
const DiaryTab = props => {
  const {isActive, onPress, onLongPress} = props;

  return (
    <TouchableOpacity
      onPress={onPress}
      onLongPress={onLongPress}
      style={[S.container, {backgroundColor: 'gold'}]}>
      <View style={S.outerCircle}>
        <View
          style={[
            S.innerCircle,
            {
              backgroundColor: isActive ? R.colors.orange : R.colors.mainGreen
            }
          ]}>
          <Icon name="header-check" size={40} color={R.colors.white} />
        </View>
      </View>
    </TouchableOpacity>
  );
};

const S = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    height: 100,
    top: -42
    // zIndex: 999
  },
  outerCircle: {
    width: 82,
    height: 82,
    backgroundColor: R.colors.white,
    // top: -42,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 41
  },
  innerCircle: {
    width: 60,
    height: 60,
    borderRadius: 30,
    justifyContent: 'center',
    alignItems: 'center',
    elevation: 3
  }
});

Thank you!


text:
Q: How to use procedures of neo4j using cypher in java I have been studying about neo4j and using it in our project. We are using neo4j jdbc drivers. Recently, came to knew about the new feature of neo4j 3.0 and its additional features. I tried studying about it still in process but need some proper example to know about the usage of procedures.
My Questions:-

*

*Use of built in procedure in my project which is in java using cypher query.

*Steps to create a simple user defined procedure.


text:
Q: Scrapy Splash HTTP status code is not handled or not allowed I'm using scrapy-splash to scrape a car dealership website that uses javascript to load the results but I keep getting error 504 Gateway Time-out.
I have docker and Win10 and I don't think the problem is docker configuration because I can scrape another site with the same code.
import scrapy
from scrapy_splash import SplashRequest
from scrapy.loader import ItemLoader
from ..items import  AutoItem

class Main_Spider(scrapy.Spider):
     name = 'dealers'
     allowed_domains = ['audidowntowntoronto.com']

     script = '''
     function main(splash)
        local scroll_delay = 3
        local is_down = splash:jsfunc("function() { return((window.innerHeight + window.scrollY) >= document.body.offsetHeight);}")
        local scroll_to = splash:jsfunc("window.scrollTo")
        local get_body_height = splash:jsfunc("function() {return document.body.scrollHeight;}")
        assert(splash:go(splash.args.url))
        while not is_down() do
            scroll_to(0, get_body_height())
            splash:wait(scroll_delay)
        end
        return splash:html()
     end
     '''

     def start_requests(self):
       yield SplashRequest(url="http://audidowntowntoronto.com/all/", callback=self.parse, endpoint="execute", args={'lua_source': self.script})

     def parse(self, response):
        url = response.xpath('//*[@itemprop="url"]/@href').extract()
        print (url)

A: It's okay not to use lua script here. Add endpoint and additional arguments shown below.
yield SplashRequest(
                    url="http://audidowntowntoronto.com/all/",
                    callback=self.parse,
                    args={
                            'html': 1,
                            'wait': 5,
                            'render_all': 1
                        },
                    endpoint='render.json')


text:
Q: Is a namespace required when referring to the base class I have code like this:
namespace N {
   class B {
     public:
       virtual void doStuff(B *) = 0;
    };
 }

 // not in a namespace
 class Derived : public N::B {
   public:
       void doStuff(B *); // Should this be N::B, or is B ok?
 };

Do I need the namespace qualifier where Derived refers to it's base class?  GCC and MSVC are happy with the code as written, but another compiler complains unless I put the namespace in.  What does the C++ standard say?

A: Inside the class definition B is OK. That's the so-called injected class name.
This also refers to templates (not counting dependent bases). E.g.
template <class T> class B{};
template <class T> class C: public B<int>
{
   void f(B* p) {} //same as B<int>* p
   void f(C* p) {} //same as C<T>* p
};

In general the base class (and the class itself) can be referred to inside the class definition without qualification or template arguments.
Quotes from the standard:

9.2 : A class-name is inserted into the scope in which it is declared immediately after the class-name is seen. The class-name is also
  inserted into the scope of the class itself; this is known as the
  injected-class-name. For purposes of access checking, the
  injected-class-name is treated as if it were a public member name.

From this definition it follows that the name of the class itself is publicly accessible from the class, and therefore is available in derived classes. Which proves my point about B being OK along with N::B because the name B is inherited
Btw, this also explains why the following is invalid:
template <class T> class B{};
template <class T> class C: public B<T>
{
     void f(B* p){} //ERROR
    // the above is invalid!! Base class is dependent therefore
    //its scope is not considered during unqualified name lookup
     void g(typename C::B* p){} //this is valid, same as B<T>* p
};

14.6.1 Speaks about injected class names in templates. It is far too long to paste here.
Hth


text:
Q: Cannot make negative matrix in OpenCV/Java I'm working on a project with OpenCV, and at some point I need to apply a 2dFilter in an image using this kernel:
-1, -1, -1;
-1,  9, -1;
-1, -1, -1

in C++ i did this:
Mat kernel = (Mat_<char>(3,3) << -1, -1, -1, -1, 9, -1, -1, -1, -1);

and it worked fine. But now I need to do the same in Java, and I can't make a Mat object with negative numbers. I'm doing this:
Mat m = new Mat();

m.create(3, 3, 0);

m.put(0, 0, -1);
m.put(0, 1, -1);
m.put(0, 2, -1);
m.put(1, 0, -1);
m.put(1, 1,  9);
m.put(1, 2, -1);
m.put(2, 0, -1);
m.put(2, 1, -1);
m.put(2, 2, -1);

and the matrix goes like this:
0, 0, 0; 0, 9, 0; 0, 0, 0

I really think this is something very stupid, but I couldn't find anything to help me.
Could anyone give me some enlightening?
Thanks!

A: m.create(3, 3, 0); // 0 for type == CV_8U == unsigned char.

well, that won't work. if you want to put negative values into it, choose a signed type.


text:
Q: Anyone experiencing weird behavior of "wire"? Been learning Salesforce for a month now and this is the first weird stuff I have encountered and not a single documentation was able to help me
I have imported the wire from lwc properly
But whenever I'm deploying it, it says that a wire variable is NOT a known adapter, can anyone kindly help me out to resolve this please?

A: So dumb of me, the official documentation wasn't able to tell that I need to import some important tools
Aside from importing wire, we'll need the following:
import { publish, MessageContext } from 'lightning/messageService';

take note of this, especially those who want to use the LMS, or to communicate their component to another component that's not related at all

A: You should have received an error in your IDE when you made this mistake.

c:\Users\brian\workspace\sfdcfox\recordEditorComponent.js: LWC1100: Invalid decorator usage. Supported decorators (api, wire, track) should be imported from "lwc"lwc

It seems like you haven't fully set up your environment/missed some steps. In your terminal/command line system, you should probably take the following steps:
sfdx force:project:create -n myProjectName
cd myProjectName
npm i

The entire transaction should look something like this:
brian@home MINGW64 ~/workspace
$ sfdx force:project:create -n myProject
target dir = C:\Users\brian\workspace
   create myProject\config\project-scratch-def.json
   create myProject\README.md
   create myProject\sfdx-project.json
   create myProject\.husky\pre-commit
   create myProject\.vscode\extensions.json
   create myProject\.vscode\launch.json
   create myProject\.vscode\settings.json
   create myProject\force-app\main\default\lwc\.eslintrc.json
   create myProject\force-app\main\default\aura\.eslintrc.json
   create myProject\scripts\soql\account.soql
   create myProject\scripts\apex\hello.apex
   create myProject\.eslintignore
   create myProject\.forceignore
   create myProject\.gitignore
   create myProject\.prettierignore
   create myProject\.prettierrc
   create myProject\jest.config.js
   create myProject\package.json

brian@home MINGW64 ~/workspace
$ cd myProject

brian@home MINGW64 ~/workspace/myProject
$ npm i

> salesforce-app@1.0.0 postinstall
> husky install

fatal: not a git repository (or any of the parent directories): .git

added 756 packages, and audited 757 packages in 24s

104 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

brian@home MINGW64 ~/workspace/myProject
$

By following these steps, you'll ensure that you're getting the full developer experience.
Regardless, this error is incorrect. I'm going to try and contact someone in Salesforce to see if we can get this message corrected. It should state something about how MessageContext isn't a known adapter, which would be a clue that you forgot to import something.
In general, whenever you see "X is not a known adapter", it means that you have forgotten to import the adapter. This is true for both Salesforce development and LWC OSS.


text:
Q: How can I improve performance of Field.set (perhap using MethodHandles)? I'm writing some code that calls Field.set and Field.get many many thousands of times. Obviously this is very slow because of the reflection.
I want to see if I can improve performance using MethodHandle in Java 7. So far here's what I have:
Instead of field.set(pojo, value), I'm doing:
private static final Map<Field, MethodHandle> setHandles = new HashMap<>();

MethodHandle mh = setHandles.get(field);
if (mh == null) {
    mh = lookup.unreflectSetter(field);
    setHandles.put(field, mh);
}
mh.invoke(pojo, value);

However, this doesn't seem to perform better than the Field.set call using reflection. Am I doing something wrong here?
I read that using invokeExact could be faster but when I tried using that I got a java.lang.invoke.WrongMethodTypeException.
Has anyone successfully been able to optimize repeated calls to Field.set or Field.get?

A: 2015-06-01: Updated to reflect @JoeC's comment about another case when handles are static. Also updated to latest JMH and re-ran on modern hardware. The conclusion stays almost the same.
Please do proper benchmarking, it is arguably not that hard with JMH. Once you do that, the answer becomes obvious. It can also showcase the proper use of invokeExact (requires target/source 1.7 to compile and run):
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(3)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MHOpto {

    private int value = 42;

    private static final Field static_reflective;
    private static final MethodHandle static_unreflect;
    private static final MethodHandle static_mh;

    private static Field reflective;
    private static MethodHandle unreflect;
    private static MethodHandle mh;

    // We would normally use @Setup, but we need to initialize "static final" fields here...
    static {
        try {
            reflective = MHOpto.class.getDeclaredField("value");
            unreflect = MethodHandles.lookup().unreflectGetter(reflective);
            mh = MethodHandles.lookup().findGetter(MHOpto.class, "value", int.class);
            static_reflective = reflective;
            static_unreflect = unreflect;
            static_mh = mh;
        } catch (IllegalAccessException | NoSuchFieldException e) {
            throw new IllegalStateException(e);
        }
    }

    @Benchmark
    public int plain() {
        return value;
    }

    @Benchmark
    public int dynamic_reflect() throws InvocationTargetException, IllegalAccessException {
        return (int) reflective.get(this);
    }

    @Benchmark
    public int dynamic_unreflect_invoke() throws Throwable {
        return (int) unreflect.invoke(this);
    }

    @Benchmark
    public int dynamic_unreflect_invokeExact() throws Throwable {
        return (int) unreflect.invokeExact(this);
    }

    @Benchmark
    public int dynamic_mh_invoke() throws Throwable {
        return (int) mh.invoke(this);
    }

    @Benchmark
    public int dynamic_mh_invokeExact() throws Throwable {
        return (int) mh.invokeExact(this);
    }

    @Benchmark
    public int static_reflect() throws InvocationTargetException, IllegalAccessException {
        return (int) static_reflective.get(this);
    }

    @Benchmark
    public int static_unreflect_invoke() throws Throwable {
        return (int) static_unreflect.invoke(this);
    }

    @Benchmark
    public int static_unreflect_invokeExact() throws Throwable {
        return (int) static_unreflect.invokeExact(this);
    }

    @Benchmark
    public int static_mh_invoke() throws Throwable {
        return (int) static_mh.invoke(this);
    }

    @Benchmark
    public int static_mh_invokeExact() throws Throwable {
        return (int) static_mh.invokeExact(this);
    }

}

On 1x4x2 i7-4790K, JDK 8u40, Linux x86_64 it yields:
Benchmark                             Mode  Cnt  Score   Error  Units
MHOpto.dynamic_mh_invoke              avgt   25  4.393 ± 0.003  ns/op
MHOpto.dynamic_mh_invokeExact         avgt   25  4.394 ± 0.007  ns/op
MHOpto.dynamic_reflect                avgt   25  5.230 ± 0.020  ns/op
MHOpto.dynamic_unreflect_invoke       avgt   25  4.404 ± 0.023  ns/op
MHOpto.dynamic_unreflect_invokeExact  avgt   25  4.397 ± 0.014  ns/op
MHOpto.plain                          avgt   25  1.858 ± 0.002  ns/op
MHOpto.static_mh_invoke               avgt   25  1.862 ± 0.015  ns/op
MHOpto.static_mh_invokeExact          avgt   25  1.859 ± 0.002  ns/op
MHOpto.static_reflect                 avgt   25  4.274 ± 0.011  ns/op
MHOpto.static_unreflect_invoke        avgt   25  1.859 ± 0.002  ns/op
MHOpto.static_unreflect_invokeExact   avgt   25  1.858 ± 0.002  ns/op

...which suggests MH are really much faster than Reflection in this particular case (this is because the access checks against the private field is done at lookup time, and not at the invocation time). dynamic_* cases simulate the case when the MethodHandles and/or Fields are not statically known, e.g. pulled from Map<String, MethodHandle> or something like it. Conversely, static_* cases are those where the invokers are statically known.
Notice the reflective performance is on par with MethodHandles in dynamic_* cases, this is because reflection is heavily optimized further in JDK 8 (because really, you don't need the access check to read your own fields), so the answer may be "just" switching to JDK 8 ;)
static_* cases are even faster, because the MethoHandles.invoke calls are aggressively inlined. This eliminates part of the type checking in MH cases. But, in reflection cases, there are still quick checks present, and therefore, it lags behind.

A: EDIT thanks to holger I noticed that I really should have used invokeExact, so I decided to remove the stuff about other jdks and use invokeExact only... using -server or not still does not really make a difference for me though
The main difference between using reflection and using MethodHandles is that for reflection you have a security check for every call, in case of MethodHandles, only for the creation of the handle.
If you look at this
class Test {
    public Object someField;
    public static void main(String[] args) throws Exception {
        Test t = new Test();
        Field field = Test.class.getDeclaredField("someField");
        Object value = new Object();
        for (int outer=0; outer<50; outer++) {
            long start = System.nanoTime();
            for (int i=0; i<100000000; i++) {
                field.set(t, value);
            }
            long time = (System.nanoTime()-start)/1000000;
            System.out.println("it took "+time+"ms");
        }
    }
}

Then I get on my computer times 45000ms on jdk7u40 (jdk8 and pre 7u25 perform much better though)
Now let's look at the same program using handles
class Test {
    public Object someField;
    public static void main(String[] args) throws Throwable {
        Test t = new Test();
        Field field = Test.class.getDeclaredField("someField");
        MethodHandle mh = MethodHandles.lookup().unreflectSetter(field);
        Object value = new Object();
        for (int outer=0; outer<50; outer++) {
            long start = System.nanoTime();
            for (int i=0; i<100000000; i++) {
                mh.invokeExact(t, value);
            }
            long time = (System.nanoTime()-start)/1000000;
            System.out.println("it took "+time+"ms");
        }
    }
}

7u40 says roughly 1288ms. So I can confirm Holger's 30 times on 7u40. On 7u06 this code handles would be slower because reflection was several times faster and on jdk8 everything is new again.
As for why you didn't see an improvement... difficult to say. What I did was microbenchmarking. That doesn't tell anything about a real application at all. But using those results I would assume you either use an old jdk version, or you don't reuse the handle often enough. Because while executing a handle can be faster, the creation of the handle can cost much more then the creation of a Field.
Now the biggest problem point... I did see you want this for google appengine... And I must say, you can test locally as much as you want, what counts in the end is what the performance of the application on the google site will be. Afaik they use a modified OpenJDK, but what version with what modification they don't say. With Jdk7 being that unstable you could be unlucky or not. Maybe they added special code for reflection, then all bets are off anyway. And even ignoring that... maybe the payment model changed again, but usually you want to avoid datastore access by caching because it costs. If that still holds, is it then realistic that any handle will be called let's say 10.000 times on average?

A: There's a catch 22 for MethodHandles in JDK 7 and 8 (I haven't tested JDK 9 or higher yet): A MethodHandle is fast (as fast as direct access) if it is in a static field. Otherwise they are as slow as reflection. If your framework reflects over n getter or setters, where is n is unknown at compile time, then MethodHandles are probably useless to you.
I wrote an article that benchmarked all the different approaches to speed up reflection.
Use LambdaMetafactory (or more exotic approaches such as code generation) to speed up calling getters and setters. Here's the gist for a getter (for a setter use a BiConsumer):
public final class MyAccessor {

    private final Function getterFunction;

    public MyAccessor() {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        CallSite site = LambdaMetafactory.metafactory(lookup,
                "apply",
                MethodType.methodType(Function.class),
                MethodType.methodType(Object.class, Object.class),
                lookup.findVirtual(Person.class, "getName", MethodType.methodType(String.class)),
                MethodType.methodType(String.class, Person.class));
        getterFunction = (Function) site.getTarget().invokeExact();
    }

    public Object executeGetter(Object bean) {
        return getterFunction.apply(bean);
    }

}

A: Update: since some people started a pointless discussion about "how to benchmark" I will emphasize the solution to your problem contained in my answer, now right at the beginning:
You can use invokeExact even in your reflective context where you don't have the exact type signature by converting the MethodHandle using asType to a handle taking Object as arguments. In environments affected by the performance difference between invoke and invokeExact, using invokeExact on such a converting handle is still way faster than using invoke on a direct method handle.

Original answer:
The problem is indeed that you are not using invokeExact. Below is a little benchmark program showing the results of different ways of incrementing an int field. Using invoke instead of invokeExact leads to a performance drop below the speed of Reflection.
You receive the WrongMethodTypeException because the MethodHandle is strongly typed. It expects an exact invocation signature matching type type of the field and owner. But you can use the handle to create a new MethodHandle wrapping the necessary type conversions. Using invokeExact on that handle using a generic signature (i.e. (Object,Object)Object) will be still way more efficient than using invoke with a dynamic type conversion.
The results on my machine using 1.7.0_40 were:

direct        :   27,415ns
reflection    : 1088,462ns
method handle : 7133,221ns
mh invokeExact:   60,928ns
generic mh    :   68,025ns

and using a -server JVM yields to a baffling

direct        :   26,953ns
reflection    :  629,161ns
method handle : 1513,226ns
mh invokeExact:   22,325ns
generic mh    :   43,608ns

I don't think that it has much real life relevance seeing a MethodHandle being faster than a direct operation but it proves that MethodHandles are not slow on Java7.
And the generic MethodHandle will still outperform Reflection (whilst using invoke does not).
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;

public class FieldMethodHandle
{
  public static void main(String[] args)
  {
    final int warmup=1_000_000, iterations=1_000_000;
    for(int i=0; i<warmup; i++)
    {
      incDirect();
      incByReflection();
      incByDirectHandle();
      incByDirectHandleExact();
      incByGeneric();
    }
    long direct=0, refl=0, handle=0, invokeExact=0, genericH=0;
    for(int i=0; i<iterations; i++)
    {
      final long t0=System.nanoTime();
      incDirect();
      final long t1=System.nanoTime();
      incByReflection();
      final long t2=System.nanoTime();
      incByDirectHandle();
      final long t3=System.nanoTime();
      incByDirectHandleExact();
      final long t4=System.nanoTime();
      incByGeneric();
      final long t5=System.nanoTime();
      direct+=t1-t0;
      refl+=t2-t1;
      handle+=t3-t2;
      invokeExact+=t4-t3;
      genericH+=t5-t4;
    }
    final int result = VALUE.value;
    // check (use) the value to avoid over-optimizations
    if(result != (warmup+iterations)*5) throw new AssertionError();
    double r=1D/iterations;
    System.out.printf("%-14s:\t%8.3fns%n", "direct", direct*r);
    System.out.printf("%-14s:\t%8.3fns%n", "reflection", refl*r);
    System.out.printf("%-14s:\t%8.3fns%n", "method handle", handle*r);
    System.out.printf("%-14s:\t%8.3fns%n", "mh invokeExact", invokeExact*r);
    System.out.printf("%-14s:\t%8.3fns%n", "generic mh", genericH*r);
  }
  static class MyValueHolder
  {
    int value;
  }
  static final MyValueHolder VALUE=new MyValueHolder();

  static final MethodHandles.Lookup LOOKUP=MethodHandles.lookup();
  static final MethodHandle DIRECT_GET_MH, DIRECT_SET_MH;
  static final MethodHandle GENERIC_GET_MH, GENERIC_SET_MH;
  static final Field REFLECTION;
  static
  {
    try
    {
      REFLECTION = MyValueHolder.class.getDeclaredField("value");
      DIRECT_GET_MH = LOOKUP.unreflectGetter(REFLECTION);
      DIRECT_SET_MH = LOOKUP.unreflectSetter(REFLECTION);
      GENERIC_GET_MH = DIRECT_GET_MH.asType(DIRECT_GET_MH.type().generic());
      GENERIC_SET_MH = DIRECT_SET_MH.asType(DIRECT_SET_MH.type().generic());
    }
    catch(NoSuchFieldException | IllegalAccessException ex)
    {
      throw new ExceptionInInitializerError(ex);
    }
  }

  static void incDirect()
  {
    VALUE.value++;
  }
  static void incByReflection()
  {
    try
    {
      REFLECTION.setInt(VALUE, REFLECTION.getInt(VALUE)+1);
    }
    catch(IllegalAccessException ex)
    {
      throw new AssertionError(ex);
    }
  }
  static void incByDirectHandle()
  {
    try
    {
      Object target=VALUE;
      Object o=GENERIC_GET_MH.invoke(target);
      o=((Integer)o)+1;
      DIRECT_SET_MH.invoke(target, o);
    }
    catch(Throwable ex)
    {
      throw new AssertionError(ex);
    }
  }
  static void incByDirectHandleExact()
  {
    try
    {
      DIRECT_SET_MH.invokeExact(VALUE, (int)DIRECT_GET_MH.invokeExact(VALUE)+1);
    }
    catch(Throwable ex)
    {
      throw new AssertionError(ex);
    }
  }
  static void incByGeneric()
  {
    try
    {
      Object target=VALUE;
      Object o=GENERIC_GET_MH.invokeExact(target);
      o=((Integer)o)+1;
      o=GENERIC_SET_MH.invokeExact(target, o);
    }
    catch(Throwable ex)
    {
      throw new AssertionError(ex);
    }
  }
}


text:
Q: Why does this Java Switch-Case not work? So, all variables in the conditions are static strings. type itself is a string in fact.
         switch(type) {
             case (INT || TINYINT):
                 preparedStatement = setInteger(preparedStatement, value, index);
                 break;
             case (BIGINT || LONG):
                 preparedStatement = setLong(preparedStatement, value, index);
                 break;
             case (DATETIME || TIMESTAMP):
                 preparedStatement = setTimestamp(preparedStatement, value, index);
                 break;
             case (MEDIUMTEXT || ENUM || TEXT || LONGTEXT || VARCHAR):
                 preparedStatement = setString(preparedStatement, value, index);
                 break;
         }

A: First, switch statements on strings are supported in Java 7+, but not in Java 6 and before.
Next, the || operator (the logical-OR operator) only works on boolean values, not String values.  But you can get the same code to be run on multiple cases by listing the cases and not breaking until past the relevant code:
switch(type) {
    case INT:
    case TINYINT:
        // This code will run for INT and TINYINT only.
        preparedStatement = setInteger(preparedStatement, value, index);
        break;
    case BIGINT:
    case LONG:
        // This code will run for BIGINT and LONG only.
        preparedStatement = setLong(preparedStatement, value, index);
        break;
    // etc.

A: Java 7 example:
public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;
}

Further I have never seen an OR statement inside of a switch like that.  I would highly recommend not doing that.

A: Assuming you are using Java SE 7 (or later) and the constants are static final Strings, then the syntax is not Java.
         case INT: case TINYINT:

A: What does this expression evaluate to?
INT || TINYINT

What are the datatypes for INT and TINYINT
I've only ever seen switch used with some primitives (and new in Java 7, string) literals or variables declared as final.
If this isn't throwing a compile error, then the || operator must be defined for whatever datatype those are. But unless that's somehow being resolved at compile time, that operator is not going to be allowed. (Again, this might be something new in Java 7 I'm not aware of.)

If you are trying to do "or" logic, the normative pattern (in pre-7 versions of Java at least), is:
    switch(type) {
        case INT:
        case TINYINT:
             preparedStatement = setInteger(preparedStatement, value, index);
             break;
        case BIGINT:
        case LONG:
             preparedStatement =
             break;

A: It is supported on and after java 7

A: You cannot use logical operators in switch statements, even with Strings. You can only test one case at a time.


text:
Q: Jquery prepend with no class input=TYPE I am wondering if its possible to use a selector of an input field with no class...
I do have quite a few options to use below is a psudo type command that I would like to accomplish.
Type of Command:
$("input[type=radio]").prepend("
");

Current HTML:
<input type="radio">SelectME

Result Required:
<input type="radio">SelectME

OR

<input type="radio">SelectME

Note: This document is acctually being loaded from another script, so the tag that I want to munipulate is inside a dynamically loaded object.

thats all that shows up in php file aside from the script to load it in the head. The input box is loaded within the IDX div, so I am having problems putting that BR in for mobile users...

A: Keep track of those quotes :
$('input[type="radio"]')

and you can't append or prepend to an input, it's self closing.
$('input[type="radio"]').before('
')


text:
Q: calculating area of triangle APE I'm calculating the area of the triangle APE.
Given that $\vec{AP} = \vec{PE}$. My assumption is that P would represent an 'identity', for A and E, suggesting that A = E. Although, this is probably not the case.
How would I tackle this question?
The area of a triangle for ABC = $\frac{1}{2} |\vec{AB}\times \vec{AC}|$
I thought that APE would be something like: $\frac{1}{2} |\vec{AP}\times \vec{AE}|$ given that A=E, although I get 0.
What did I miss?
Given that $\vec{AP}=(3, 5, 0) - (1, 5, 2) = (2, 0, -2)$
How would I find more than one possible coordinate for E?
If a point E lies on the line $l_1$, which has the equation:
$\pmatrix{1 \\ 5 \\ 2} + \lambda \pmatrix{-5 \\ 4 \\ 3}$ Given $\lambda$ = 1, does this change the significance above?

A: If $\vec{AP} = \vec{PE}$, we have a degenerate triangle.
$$\vec{AP} = \vec{PE} $$
$$\Rightarrow \vec{P}-\vec{A}=\vec{E}-\vec{P}$$
$$\Rightarrow \vec{P} = \frac{\vec{A}+\vec{E}}{2}$$
Since the direction of $\vec{AP}$, $\vec{PE}$ is same, $P$ is collinear with $A,E$ and is shown to be the midpoint of $AE$. The area is thus, zero.


text:
Q: How to convert SQL nested query that deals with multiple tables to corresponding HQL? I have a SQL query defined in Java as:
String queryString =
        "select payee_id from ("
            + "select distinct d.company_name, d.business_type, d.service_type,m.payee_id "
            + " from BOOKER.PC_PAYEE_BACKFILL_DATA d, BOOKER.PC_PAYEE_BACKFILL_METADATA m "
            + " where d.DATA_RECORD_ID=m.DATA_RECORD_ID "
            + " and d.status = '"
            + PayeeBackfillStatus.VM_ACCEPTED
            + "' and d.canceled = '"
            + AppConstants.FALSE_CHAR
            + "' and d.wave_num = "
            + waveNumber
            + " ) "
            + "group by payee_id having count(*) > 1 ";

I need to convert it to HQL. But HQL does not support inner queries. So what can be the alternative of doing it? One way is to run the inner query and then pull out payee_id using Java's collections. But that is a work around. You can assume any mapping class name for PC_PAYEE_BACKFILL_DATA and PC_PAYEE_BACKFILL_METADATA. Please help.

A: There is no way in HQL to do so.

A: HQL supports sub queries in select and where please refer this one hope this one will help you
 http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/queryhql.html#queryhql-subqueries


text:
Q: How do I await code inside a method that returns an EitherAsync in LanguageExt? When using TryAsync in LanguageExt, you can do something like this...
static TryAsync<int> Divide(int n1, int n2) =>
    TryAsync(async () => {
      // Simulate some async operation that might fail
      await Task.Delay(300);
      return n1 / n2;
    });

I have the need for a similar method that returns an EitherAsync, but I'm stuck, as I can't find a static EitherAsync method to which I can pass an async lambda.
I know I can do this...
static EitherAsync<string, int> Square(int n) =>
  (n * n).AsTask();

...but that doesn't do anything async. If I change it to do this (simulate an async call)...
static EitherAsync<string, int> Square(int n) {
  Task.Delay(300);
  return (n * n).AsTask();
}

...then the call to Task.Delay is not awaited. I can't await it, as I can't make the method async (see this issue for more details).
I might be approaching this wrongly, but I can't see how you can await code inside such a method, which seems odd (to me, but that doesn't prove anything!), as the whole point of this monad is for async code.
Anyone know if it's possible to do something similar for EitherAsync? Thanks

A: Any function function returning task should work due to implicit casts from T and Task<T> to Either, for example:
static EitherAsync<string, int> Square(int n)
{
    async Task<int> inner()
    {
        await Task.Delay(300);
        return n * n;
    }

    return inner();
}

Or you can manipulate with TryAsync mapping, which, I would say, is more correct approach cause previous one will not handle exceptions thrown during the task execution:
static EitherAsync<string, int> Square2(int n) =>
    TryAsync(async () =>
        {
            await Task.Delay(300);
            throw new Exception();
            return n * n;
        })
        .ToEither(error => error.Message);

A: There is an implicit conversion from a Task<T> to an EitherAsync<T, Anything> and an EitherAsync<Anything, T>, so you can just create a Task<T> using Task.Run to run any async code you'd like for example:
static EitherAsync<string, int> Square(int n) =>
    Task.Run(async () => {
        await Task.Delay(300);
        return n * n;
    });


text:
Q: c# TreeView get Parent node Index On expand asp:treeView How do I get the index that was expended?
I tried to look into: ontreenodeexpanded="Node_Expand"  but I cant find the index of the parent root that was clicked.
Thanks,

A: The node you expanded is the Node property of the event arguments:
// Inside the event handler method
TreeNode clickedNode = e.Node;

You can get its index with the IndexOf method of the TreeNodeCollection that is storing the node.


text:
Q: Passing Extra Parameters in express - Node.JS I'm trying to remove the anonymous functions from my node application. For instance:
app.post('/page-edit.json', function (req, res) {
    db.get(req.body.page_id, function (err, doc) {
        res.contentType('json');
        res.send(doc);
    });
});

So say I break out the inner function:
function innerMost(err, doc) {
    res.contentType('json');
    res.send(doc);
}

function outer(err, doc) {
     db.get(req.body.page_id, innerMost);
}

app.post('/page-edit.json', outer);

The question is, how do I pass extra parameters, like 'res' into 'innerMost'? It's getting lost in the process.
If you want to see the source code (or even want to contribute to the open source project!) you can see it here!

A: This is probably the best you can do with regular JS:
function outer(req, res) {
    function innerMost(err, doc) {
        res.contentType('json');
        res.send(doc);
    }

    db.get(req.body.page_id, innerMost);
}

app.post('/page-edit.json', outer);

However, you might want to look into various async libraries such as https://github.com/caolan/async. If you want to venture even further, you could look into using icedcoffeescript http://maxtaco.github.io/coffee-script/, which is pretty good in my opinion.

A: It sounds like what you are looking for is currying (also known as "partial application of functions") which basically lets you prefill the values of some parameters ahead of time.
John Resig has a nice writeup on this.
Grabbing some code from his writeup, you can create a partial function like this:
Function.prototype.partial = function(){
    var fn = this, args = Array.prototype.slice.call(arguments);
    return function(){
      var arg = 0;
      for ( var i = 0; i < args.length && arg < arguments.length; i++ )
        if ( args[i] === undefined )
          args[i] = arguments[arg++];
      return fn.apply(this, args);
    };
};

And in your case, use it like this:
function innerMost(err, doc, req, res) {
    res.contentType('json');
    res.send(doc);
}

function outer(req, res) {
    //partially apply `innerMost` here by passing in `req` and `res`
    db.get(req.body.page_id, innerMost.partial(undefined, undefined, req, res));
}

app.post('/page-edit.json', outer);

Note, this code isn't tested.

A: I tend to separate things out using Function.bind(), so you don't need to mess with Function's prototype, external libs, etc..
function innermost(req, res, e, r){
    res.end(r)
}

function somedbfunc(q, cb){
    cb(null, 'db results');
}

function outer(req, res){
    somedbfunc('query', innermost.bind(this, req, res));
}

app.all('*', outer)
    ==> "db results"


text:
Q: jQuery toggled tr elements drift down page The gist of my problem is that I have a table that every even row is hidden, and visibility is toggled using an anchor on the row above. This works correctly, but in some browsers (Safari and Chrome) the tr below the one that just appeared moves down further than it should have.
If you keep toggling the hidden tr the next sibling drifts down the page.
Here is a bare bones code that shows this issue (requires jquery)

   Title
   Some Detail
   Show/Hide

    Sed scelerisque, tellus non auctor pretium, felis massa vehicula sem, quis vehicula nulla dolor eget justo. Pellentesque porttitor aliquet metus a accumsan. Aenean luctus, lacus in tristique imperdiet, nulla ipsum dignissim massa, quis laoreet eros justo eu nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam sed purus nisi, at venenatis tellus. Praesent id magna ac dui congue convallis. Duis sit amet arcu eu ipsum tincidunt fermentum. Praesent mollis, eros sit amet auctor iaculis, mi elit aliquet elit, at rhoncus elit urna nec magna. Vestibulum iaculis fringilla diam, in rhoncus tortor blandit id. Nam id leo eros, et posuere massa. Morbi fermentum egestas nisl, et pharetra urna convallis viverra. Maecenas id massa nulla. Pellentesque eget urna vel diam interdum sollicitudin sit amet in massa.

   Title 2
   Some Detail 2
   Show/Hide

    Sed scelerisque, tellus non auctor pretium, felis massa vehicula sem, quis vehicula nulla dolor eget justo. Pellentesque porttitor aliquet metus a accumsan. Aenean luctus, lacus in tristique imperdiet, nulla ipsum dignissim massa, quis laoreet eros justo eu nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam sed purus nisi, at venenatis tellus. Praesent id magna ac dui congue convallis. Duis sit amet arcu eu ipsum tincidunt fermentum. Praesent mollis, eros sit amet auctor iaculis, mi elit aliquet elit, at rhoncus elit urna nec magna. Vestibulum iaculis fringilla diam, in rhoncus tortor blandit id. Nam id leo eros, et posuere massa. Morbi fermentum egestas nisl, et pharetra urna convallis viverra. Maecenas id massa nulla. Pellentesque eget urna vel diam interdum sollicitudin sit amet in massa.

The above code seems to work fine in Opera and Firefox, but the issue mentioned above happens in Safari and Chrome. (Haven't tested in IE yet). This makes me suspicious that it is a webkit related issue.
Anyone else found the problem? Is there a workaround?

A: I'm able to reproduce your problem in Chrome with jQuery 1.4.2, but not with 1.4.4. In fact, with 1.4.4, the table row doesn't animate at all -- instead it just toggles on and off (after a delay).
The behavior of slideToggle on table elements seems to be somewhat undefined. As a workaround, place a
 around your  contents and call slideToggle on that instead:

            Sed scelerisque...


text:
Q: problem using page.registerstartupscript I am using page.registerstartupscript in my code behind C#. Its like this:
string item1="category1";
string Script = "window.program = '" + item1 + "';";
    Page.RegisterStartupScript("PopupScript", Script);
item1 gets generated dynamically from some value in code behind. But its not working. Any suggestoins where I m getting wrong?

A: You need it wrapped in script tags, there's an overload for this in the newer replacement ClientScript:
string item1="category1";
string Script = "window.program = '" + item1 + "';";
Page.ClientScript.RegisterStartupScript(GetType(), "PopupScript", Script, true);

Unless you're on .Net 1.1 I believe, Page.RegisterStartupScript is deprecated.


text:
Q: Hide a table if all cells in tbody are empty I would like to be able to hide an entire table if all the cells in tbody are empty. I have only been able to find out how to hide a single row, if all the cells in it were empty.
Here's the code. It is a dynamically generated table that I would like to hide it if it has no content in the body:

            Headline 1
            Headline 2
            Headline 3
            Headline 4
            Headline 5

Thank you very much for any help !

A: if ($.trim($('.acf-dynamic-table tbody').text())=="") {
    $('.acf-dynamic-table').hide();
}

A: if ($(".acf-dynamic-table td:not(:empty)").length == 0) {
  $(".acf-dynamic-table").hide();
}

A: You can use jQUery :empty selector which:

Select all elements that have no children (including text nodes)

 if ($(".acf-dynamic-table td:not(:empty)").length == 0) {
      $(".acf-dynamic-table").hide();
 }


text:
Q: Return a value from array if two other values are known - Python3 Probably a basic question for the more experienced python programmers here, but I am looking for a neat way to find the third value in an array of three parameters if two of them are given.
Example:
array1 = [["a1", 22, 3], ["a2", 222, 4]]
array2 = ["a1", 22]

And I want based on the values given in array 2 to get the value 3 as an answer for this example.

A: Does converting it into a dict of tuples and using it work for you? See below:
>>> array1 = [["a1", 22, 3], ["a2", 222, 4]]
>>> array1_dict = {(a,b):c for a,b,c in array1}
>>> array1_dict[tuple(array2)]
3
>>>

The other way is ofcourse to loop over all items in array1 and keep checking the conditions.
>>> for each_item in array1:
...     if each_item[0] == array2[0] and each_item[1] == array2[1]:
...             print(f'My required value: {each_item[2]}')
...
My required value: 3
>>>


text:
Q: properly getting data from nested dictionaries, there must be a better way I come across this issue on a regular basis, hopefully someone has an elegant solution...
x = {'a':1, 'b':{'c':2}}

now:
x.get('a', None) = 1

x.get('b', None).get('c', None) = 2

what about:
x.get('a', None).get('c', None) =

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-278862f593e8> in <module>()
----> 1 x.get('a', None).get('c')

AttributeError: 'int' object has no attribute 'get'

#
Is there a simple pythonic one-liner for handling cases like this? (without using a bunch of if statements)
Thanks!
#
Thanks for all the comments/feedback. I'm looking for an elegant one-liner, as I come across this on a regular basis. Obviously this is a toy-example, which was constructed just to explain the problem. I would prefer not to use try/catch blocks or wrap the code in long if statements. Thanks!

A: The usual syntax to access nested dictionary keys is:
>>> x = {'a':1, 'b':{'c':2}}
>>> x['b']['c']
2
>>> x['b']['c'] = 100
>>> x['b']['c']
100

This will throw a key error on missing keys:
>>> x['b']['d']
...
KeyError: 'd'

Which you could wrap in a try-catch:
>>> try:
...     x['b']['d']
... except KeyError as err:
...     # do something when no key is present ...
...     pass

If you are looking for a "catch-all non-existing keys and always do the right thing" kind of solution, I guess you'll have to write some thin wrapper around your specific data structure.

A: Here's a generator that will grab the nested value if it's nested, and just the value if it isn't nested:
x = {'a':1, 'b':{'c':2}}
def get_value(x, nested_key='c'):
    for k, v in x.items():
        if isinstance(v, dict):
            yield v[nested_key]
        else:
            yield v

Here's a demo:
>>> for value in get_value(x):
        print (value)

2
1

A: There isn't a Pythonic one liner. Arbitrary nesting requires some arbitrary code. The Pythonic way is to ask for forgiveness meaning a try-catch block.
Think this through and it makes sense. Imagine debugging your nested get call above if it worked. Which layer was missing the key?

A: Do you mean such construction:
try:
    x['a']['b'] = 1  # getting or setting values for existing dicts/keys
except:
    pass  # or do something in case dict does not exists


text:
Q: extract substrings starting with same pattern in a file I have a fileA.txt which contains strings:
>AMP_16 RS0247 CENPF__ENST00000366955.7__3251__30__0.43333__66.8488__1 RS0255
>AMP_16 RS0332 CENPF__ENST00000366955.7__2262__30__0.43333__67.9513__1 RS0451
>AMP_16 RS0332 CENPF__ENST00000366955.7__1108__30__0.43333__67.4673__1 RS0247
and so on .....

I would like to extract all the substring which start with RS
Output:
RS0247_RS0255
RS0332_RS0451
RS0332_RS0247

I tried something like this:
while read line
do
        for word in $line
        do
                if [[ "$word" =~ ^RS ]]
                then
                        [ -z "$str" ] && str="$word"
                fi
        done
done < fileA.txt

echo "$str"

However I only get the first string RS0247 printed out when I do echo

A: Given the three sample lines pasted above in the file f...
Assuming a fixed format:
awk '{print $2"_"$4}' f
RS0247_RS0255
RS0332_RS0451
RS0332_RS0247

Assuming a flexible format (and that you're only interested in the first two occurrences of fields that start with RS:
awk '{f=1;for (i=1;i<=NF;i++){if($i~/^RS/){a[f]=$i;f++}}print a[1]"_"a[2]}' f
RS0247_RS0255
RS0332_RS0451
RS0332_RS0247

Edit 1:
And assuming that you want your own script patched rather than an efficient solution:
#!/bin/bash
while read line
do
        str=""
        for word in $line
        do
                if [[ "$word" =~ ^RS ]]
                then
                        if [[ -z $str ]]
                        then
                                str=$word
                        else
                                str+="_${word}"
                        fi
                fi
        done
        echo "$str"
done < fileA.txt

Edit 2:
In terms of efficiency; I copied and pasted those 3 lines into fileA.txt 60 times (180 lines total).  The runtimes for the three attempts above in the same order are:

*

*real    0m0.002s

*real    0m0.002s

*real    0m0.011s


text:
Q: Translate TextField value Some of my fields are stored in English in database and translated only in the client(in this case react-admin). So, how do I achieve this?
In my translations, I have entries for all possible member_category values and when displayed I want the value from the database to be translated.
export const MemberList = withStyles(listStyles)(({ classes,
  permissions, ...props }) => (
    <List {...props}>
     <Datagrid rowClick="show">
       <TextField source="full_name" />
       <TextField source="email" />
       <TextField source="telephone" />
       <TextField source="member_category" />
     </Datagrid>
    </List>
));

A: Use a custom component wrapping a FunctionField instead of TextField.
Use react-admin's translate HOC on it.
import React from 'react';
import PropTypes from 'prop-types';
import { translate, FunctionField } from 'react-admin';
import get from 'lodash/get';
const TranslateField = translate(( { translate, namespace, ...props } ) => {
    return (
        <FunctionField {...props}
            render={ (record, source) => translate(`${namespace}.${get(record, source)}`) }
        />
    )
});
TranslateField.propTypes = {
    namespace: PropTypes.string
}
TranslateField.defaultProps = {
    namespace: 'dbphrases',
};

export default TranslateField;

export const MemberList = withStyles(listStyles)(({ classes,
  permissions, ...props }) => (
    <List {...props}>
     <Datagrid rowClick="show">
       <TextField source="full_name" />
       <TextField source="email" />
       <TextField source="telephone" />
       <TranslateField source="member_category" />
     </Datagrid>
    </List>
));

Then it's just a matter of loading the right translations in the right namespace in your i18n config. Here I put a default dbphrases namespace to take translations from ${locale}.dbphrases.${value}
See react-admin's doc


text:
Q: R : Error when using "lines" instruction for a previously defined function in a loop I have a problem when I use "lines" into a loop, which is used to plot the functions that I have defined into the loop. My purpose is to plot x³,x⁴,x⁵. I leave my code so that you can see which are the problems.
Thank you in advance.
x <- seq(0,1,0.05)
plot(x,x,type="l",ylab="y")
j <-3
for(j in 3:5){
  f1 <- function(a){
        a^j
        }
  lines(f1)

  j <- j+1
}

A: I strongly advise to plot using ggplot2 regarding this kind of problem:
library(ggplot2)

df = data.frame(x=x, y=c(x^2,x^3,x^4), func=rep(paste0('x',2:4), each=length(x)))

ggplot(df,aes(x,y,color=func))+geom_line()

A: Part of the problem is that you call f1(a) without specifying a. The second problem is that when you do not specify the x and y values for 'lines()', the x values are assumed to be 1:n. Therefore, the line is plotted but not on the same interval. To see this you can run the following code.
x <- seq(0,1,0.05)
plot(x,x,type="l",ylab="y",xlim=c(0,length(x)+1))
j <-3

f1 <- function(a){
  a^j
}

for(j in 3:5){
  lines(f1(x))
}

Here is some code that will generate a simple plot with all lines on the same interval.
x <- seq(0,1,0.05)
plot(x,x,type="l",ylab="y")
j <-3

f1 <- function(a){
  a^j
}

for(j in 3:5){
  lines(x,f1(x))
}


text:
Q: Is it possible to decrease the power dissipated in a winding with a constant braking torque? I have a 4-quadrant current controller which regulates the braking current of a brushed DC motor with a high-inertia load to a constant level, but the motor winding cannot handle the current required to halt the load in the time I want.
I thought I could dissipate the energy elsewhere by regulating the braking current and letting it drain back into the supply where a DC link regulator is, but I was wrong: the only thing I would be doing, would be to charge up the inductor, and discharge it into the DC link regulator.
I have the feeling now that I can't decrease the power the winding itself dissipates for a given mechanical braking power, since I can clearly see the mechanical breaking power is the back-EMF (constant at a given time) times the current (constant because regulated at the desired braking torque), regardless of what I do with the current.
Could anyone confirm or suggest how I could achieve what I want electrically (except brake over a longer time)?

A: The motor heating goes as the winding current squared, which goes as the braking torque squared. So your motor heating will only allow a certain braking torque. If you only want to brake for a short time, you might allow the motor temperature to rise to absorb rather than dissipate the heat, subject to long enough being allowed between braking events to allow the motor to cool.
The motor voltage will depend on speed, so when braking from high speed you would be able to use an external load to dissipate some of the braking energy. At some lowish speed, the external load would need to be zero to allow enough braking current to flow. Below that speed you would have to actively drive a braking current into the motor.

A: Obviously, the current of the electrical machine has to be in the acceptable range. No matter if this machine works in a motoring mode or in generator mode. Ideally the same time is needed for accelerating the mass of inertia and for stopping it. In a practical world it's much different, since there is also a friction and load, so the decelerating time is shorter than acceleration at the same current.
As for your question, you probably have some wrong interpretation. 4-quadrant  means that electrical energy is converted into a mechanical energy and vice versa. Thus, when decelerating you get the electrical energy back that you have to store it somewhere or to dump it through a braking resistor and not into motor's winding, that's not a 4-Q.

A: Clearly you have to dispose of a fixed amount of energy to slow the rotor by a certain amount.  A direct short will give the highest current and therefore the best retardation, but if you use a resistor rather than a dead shirt then the resistor will dissipate some of the energy, and the part that the motor dissipates will be over a longer time, so the power will be reduced.  It's not clear whether a small extension of the braking time would be acceptable.  Unavoidably, the braking force is proportional to the current in the windings, so if the maximum motor current doesn't give you enough retardation then there's not much you can do about it.


text:
Q: AnyChart Android unable to populate values from firestore in for loop Below iam trying to add the values from FireStore to LineChart but chart shows blank,Where as reference.get methods is retreiving data and saving in my model but its not adding up in series data
if i manually add data in the seriesData.add() it populates in the chart, i dont know where i am doing wrong
Please help me guys.
private void initChart() {

        SimpleDateFormat localDateFormat;
        localDateFormat = new SimpleDateFormat("MMMM-yyyy");
        String date1 = localDateFormat.format(date);

        Cartesian cartesian = AnyChart.line();

        cartesian.animation(true);

        cartesian.padding(10d, 20d, 5d, 20d);

        cartesian.crosshair().enabled(true);
        cartesian.crosshair()
                .yLabel(true)
                // TODO ystroke
                .yStroke((Stroke) null, null, null, (String) null, (String) null);

        cartesian.tooltip().positionMode(TooltipPositionMode.POINT);

        cartesian.title("Furnace Kwh Reading for the month of "+date1);

        cartesian.yAxis(0).title("Reading");
        cartesian.xAxis(0).labels().padding(5d, 5d, 5d, 5d);
        SimpleDateFormat localDateFormat2;
        localDateFormat2 = new SimpleDateFormat("dd-yy");

        List<DataEntry> seriesData = new ArrayList<>();
        reference.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
                    Energy_cons_model model=documentSnapshot.toObject(Energy_cons_model.class);

                    String da= localDateFormat2.format(model.getTs());
                    int ip1= Math.toIntExact(model.getHpdc1());
                    int ip2= Math.toIntExact(model.getHpdc2());
                    int ip3= Math.toIntExact(model.getHpdc3());

                    seriesData.add(new CustomDataEntry(da,ip1,ip2,ip3,model.getGspm2B()));
                }

            }
        });

        Set set = Set.instantiate();
        set.data(seriesData);
        // Number ip3,Number gspm2b,Number gspm3b1,Number gspm3b2,Number gspm3b3,Number roto
        Mapping series1Mapping = set.mapAs("{ x: 'x', value: 'value' }");
        Mapping series2Mapping = set.mapAs("{ x: 'x', value: 'value2' }");
        Mapping series3Mapping = set.mapAs("{ x: 'x', value: 'value3' }");
        Mapping series4Mapping = set.mapAs("{ x: 'x', value: 'value4' }");

        Line series1 = cartesian.line(series1Mapping);
        series1.name("HPDC-1");
        series1.hovered().markers().enabled(true);
        series1.hovered().markers()
                .type(MarkerType.CIRCLE)
                .size(4d);
        series1.tooltip()
                .position("right")
                .anchor(Anchor.LEFT_CENTER)
                .offsetX(5d)
                .offsetY(5d);

        Line series2 = cartesian.line(series2Mapping);
        series2.name("HPDC-2");
        series2.hovered().markers().enabled(true);
        series2.hovered().markers()
                .type(MarkerType.CIRCLE)
                .size(4d);
        series2.tooltip()
                .position("right")
                .anchor(Anchor.LEFT_CENTER)
                .offsetX(5d)
                .offsetY(5d);

        Line series3 = cartesian.line(series3Mapping);
        series3.name("HPDC-3");
        series3.hovered().markers().enabled(true);
        series3.hovered().markers()
                .type(MarkerType.CIRCLE)
                .size(4d);
        series3.tooltip()
                .position("right")
                .anchor(Anchor.LEFT_CENTER)
                .offsetX(5d)
                .offsetY(5d);

        Line series4 = cartesian.line(series4Mapping);
        series4.name("2B");
        series4.hovered().markers().enabled(true);
        series4.hovered().markers()
                .type(MarkerType.CIRCLE)
                .size(4d);
        series4.tooltip()
                .position("right")
                .anchor(Anchor.LEFT_CENTER)
                .offsetX(5d)
                .offsetY(5d);

        cartesian.legend().enabled(true);
        cartesian.legend().fontSize(13d);
        cartesian.legend().padding(0d, 0d, 10d, 0d);

        anyChartView.setChart(cartesian);

    }

below is my CustomValues class
private class CustomDataEntry extends ValueDataEntry {

        CustomDataEntry(String x, Number value, Number value2, Number value3,Number value4) {
            super(x, value);
            setValue("value2", value2);
            setValue("value3", value3);
            setValue("value4", value4);
        }

  [1]: https://i.stack.imgur.com/bC16K.png
  [2]: https://i.stack.imgur.com/n9b1t.png

A: I think issue is you are initializing dataset of chart before getting tiger.
public void updateChart(List<DataEntry> seriesData)
{
    Set set = Set.instantiate();
    set.data(seriesData);
    // Number ip3,Number gspm2b,Number gspm3b1,Number gspm3b2,Number gspm3b3,Number roto
    Mapping series1Mapping = set.mapAs("{ x: 'x', value: 'value' }");
    Mapping series2Mapping = set.mapAs("{ x: 'x', value: 'value2' }");
    Mapping series3Mapping = set.mapAs("{ x: 'x', value: 'value3' }");
    Mapping series4Mapping = set.mapAs("{ x: 'x', value: 'value4' }");

    Line series1 = cartesian.line(series1Mapping);
    series1.name("HPDC-1");
    series1.hovered().markers().enabled(true);
    series1.hovered().markers()
            .type(MarkerType.CIRCLE)
            .size(4d);
    series1.tooltip()
            .position("right")
            .anchor(Anchor.LEFT_CENTER)
            .offsetX(5d)
            .offsetY(5d);

    Line series2 = cartesian.line(series2Mapping);
    series2.name("HPDC-2");
    series2.hovered().markers().enabled(true);
    series2.hovered().markers()
            .type(MarkerType.CIRCLE)
            .size(4d);
    series2.tooltip()
            .position("right")
            .anchor(Anchor.LEFT_CENTER)
            .offsetX(5d)
            .offsetY(5d);

    Line series3 = cartesian.line(series3Mapping);
    series3.name("HPDC-3");
    series3.hovered().markers().enabled(true);
    series3.hovered().markers()
            .type(MarkerType.CIRCLE)
            .size(4d);
    series3.tooltip()
            .position("right")
            .anchor(Anchor.LEFT_CENTER)
            .offsetX(5d)
            .offsetY(5d);

    Line series4 = cartesian.line(series4Mapping);
    series4.name("2B");
    series4.hovered().markers().enabled(true);
    series4.hovered().markers()
            .type(MarkerType.CIRCLE)
            .size(4d);
    series4.tooltip()
            .position("right")
            .anchor(Anchor.LEFT_CENTER)
            .offsetX(5d)
            .offsetY(5d);

    cartesian.legend().enabled(true);
    cartesian.legend().fontSize(13d);
    cartesian.legend().padding(0d, 0d, 10d, 0d);

    anyChartView.setChart(cartesian);
}

Call update function.
        reference.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                List<DataEntry> seriesData = new ArrayList<>();
                for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
                    Energy_cons_model model=documentSnapshot.toObject(Energy_cons_model.class);

                    String da= localDateFormat2.format(model.getTs());
                    int ip1= Math.toIntExact(model.getHpdc1());
                    int ip2= Math.toIntExact(model.getHpdc2());
                    int ip3= Math.toIntExact(model.getHpdc3());

                    seriesData.add(new CustomDataEntry(da,ip1,ip2,ip3,model.getGspm2B()));
                }
               updateChart(seriesData);
            }
        });


text:
Q: Problems when deleting resource files C# When I delete resource files from my C# project all the menustrip, toolstrip and status strips items are removed from their respective strips.
These lines of code are deleted everytime it happens.
        this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
        this.fileToolStripMenuItem,
        this.processToolStripMenuItem,
        this.toolStripMenuItem1,
        this.windowsToolStripMenuItem,
        this.adminToolStripMenuItem,
        this.helpToolStripMenuItem1});

Is there:
a) a way to stop this?
b) a reason why it does this?


text:
Q: Prove the identity about interpolation I am studying numerical analysis and I have difficulty with the following exercise concerning interpolation:
$$\sum_{i=0}^n \dfrac{x_i^n}{\prod_{j=0,j≠i}^n(x_i-x_j)}=1,$$where $x_i$ are pairwisely unequal.I want to use  Lagrange interpolation to prove it, but failed, can anyone help me?

A: Hint. Try to match $\frac{d^n}{dx^n} \ell_i(x)$ with the product from the problem.


text:
Q: How to add tooltip link in Grafana with link to another panel from status map I'm using Grafana to show the status of some ci/cd pipelines and I would like to be able to add a link to the pipeline run for each status event in the tooltip. However, I'm having trouble figuring out how to do that. I have a query that returns the status, time and pipeline_id for each pipeline run. I need the pipeline_id to determine where the link should go, but I want to show the status as the actual value in the graph. Is there a way to do this?
Currently, I setup my grafana graph by adding this query, and then using an organize fields transform to show status as a row and not show the pipeline_id as a row.
Also, I am open to using statusmap, or status history, or other similar plugins if they support this functionality.


text:
Q: convert all img in one pdf .? I would like to finish my script, I tried a lot to solve but being a beginner failed.
I have a function imageio which takes image from website and after that, i would like resize all images in 63x88 and put all my images in one pdf.
full_path = os.path.join(filePath1, name + ".png")
if os.path.exists(full_path):
    number = 1
    while True:
        full_path = os.path.join(filePath1, name + str(number) + ".png")
        if not os.path.exists(full_path):
            break
        number += 1
imageio.imwrite(full_path, im_padded.astype(np.uint8))
os.chmod(full_path, mode=0o777)

thanks for answer

A: We (ImageIO) currently don't have a PDF reader/writer. There is a long-standing features request for it, which hasn't been implemented yet because there is currently nobody willing to contribute it.
Regarding the loading of images, we have an example for this in the docs:
import imageio as iio
from pathlib import Path

images = list()
for file in Path("path/to/folder").iterdir():
    im = iio.imread(file)
    images.append(im)

The caveat is that this particular example assumes that you want to read all images in a folder, and that there is only images in said folder. If either of these cases doesn't apply to you, you can easily customize the snippet.
Regarding the resizing of images, you have several options, and I recommend scikit-image's resize function.
To then get all the images into a PDF, you could have a look at matplotlib, which can generate a figure which you can save as a PDF file. The exact steps to do so will depend on the desired layout of your resulting pdf.


text:
Q: How does heapq push comparison work in 2.7 vs 3.x import heapq

class Foo(object):
    def __init__(self, x):
        self._x = x

l = [Foo(1)]
heapq.heapify(l)
heapq.heappush(l, Foo(2))

This works in Python 2.7 but not in 3.x. As mentioned in the docs

In the future with Python 3, tuple comparison breaks for (priority, task) pairs if the priorities are equal and the tasks do not have a default comparison order.

How are non-comparable objects handled in 2.7's heapq.heappush?

A: Let us assume that you want Foo instances to be compared by their ._x values.  Your code may run in 2.x, but it will not work in any sensible fashion as Foo instancex will instead be compared by their ids.  Python 3 protects you from such silent bugs by not having a useless default.  heapq at least uses <.  The following runs in 3.x and works correctly, at least for this example, in 2.x and 3.x.
import heapq

class Foo(object):
    def __init__(self, x):
        self._x = x
    def __repr__(self):
        return 'Foo(%s)' % self._x
    def __lt__(self, other):
        return self._x < other._x

l = [Foo(1)]
heapq.heapify(l)
heapq.heappush(l, Foo(2))
print(l)

Add other rich comparision methods as needed or desired.  You could add if isinstance(other, Foo) else NotImplemented to the end of each return expression to make comparisons with non-Foo instances work better.


text:
Q: Do User tests for every url? I have urls like this:
in main:
path('admin/', ...),
path('forstaff/', include("myapp.urls"),
path('forusers/', include("anotherapp.urls"),

If a user is is_staff=True, they can access forstaff/, if not, they get redirected to `forusers/'. I know that I can do this:
class StaffRequiredMixin(LoginRequiredMixin, UserPassesTestMixin):

    def test_func(self):
        return self.request.user.is_staff

but I have to add this StaffRequiredMixin to every single class based view in myapp.urls, and also can not use it with function based classes.
Is there a way I can tell Django to apply this "rule" to every single view of the app?


text:
Q: Odd numbering of files from one folder to other in matlab Files present in one folder:
1 copy(1).jpg,
1 copy(2).jpg
.......
.......
.......
1 copy(800)
Odd numbering of files and save it in other folder.Desired output shown below:
1.jpg,
3.jpg,
5.jpg
....
....
....
799.jpg
Source code i tried:
a ='C:\Users\rahul\Desktop\jumbled test\copiedimages\';
A =dir( fullfile(a, '*.jpg') );
fileNames = { A.name };
for iFile = 1 : numel( A )
  newName = fullfile(a, sprintf( '%d.jpg',iFile+2) );
  movefile( fullfile(a, fileNames{ iFile }), newName );
end

But i cant able to get desired output.So what will be the solution?

A: Don't rename the files, just move them to the new directory after checking if they had an odd number in their file name:
a ='C:\Users\rahul\Desktop\jumbled test\copiedimages\';
destination = a ='C:\Users\rahul\Desktop\jumbled test\copiedimages\Odd\';
A =dir( fullfile(a, '*.jpg') );
fileNames = { A.name };
for iFile = 1 : numel( A )
    [~,name] = fileparts(fileNames{ iFile });  %// This part might not be necessary if fileNames{ iFile } is just the file name without the directory. In that case rather use name=fileNames{ iFile };
    %// Extract the number from the file name
    filenum = str2num(name(8:end-4));
    %// Check if the number is odd
    if mod(filenum,2) == 1
        movefile(fullfile(a, fileNames{ iFile }), fullfile(destination, fileNames{ iFile }));
    end
end