text:
Q: hook postNotificaiton using Frida I am trying to hook postNotificationName Function with Frida. I call two functions:

*

*postNotificationName:(NSNotificationName)object:(id)userInfo:(NSDictionary)

*postNotification:(NSNotification)object

sO, When I trace the functions using frida-trace, I see that in the later case there is calls to postNotificationName. I want to know if postNotification calls postNotification and why is that?
Also,
var newObject = ObjC.classes.NSNotification;
var myObj = newObject.alloc().initWithName_object_userInfo_('notificationName','nil','userInfo');
var hook = ObjC.classes.NSNotificationCenter["- postNotification:"];
Interceptor.attach(hook.implementation, {
    onEnter: function(args) {
        console.log("\n[*] Detected call to: " + NsNotificationCenter + " -> " + postNotification);
        console.log("\t[-] Argument Value: " + args[2]);
        args[2] = ptr(myObj)
        console.log("\t[-] New Argument Value: " + args[2])
    }

works when is injected using Frida to hook the postNotification function.
However,
var nsName = ObjC.classes.NSString;
var notificationName= nsName.stringWithString_("Blah");
var hook = ObjC.classes.NSNotificationCenter["- postNotificationName:"];
Interceptor.attach(hook.implementation, {
    onEnter: function(args) {
        console.log("\n[*] Detected call to: " + NSNotificationCenter + " -> " + postNotificationName);
        console.log("\t[-] Argument Value: " + args[2]);
        args[2] = ptr(notifname)
        console.log("\t[-] New Argument Value for postNotificaitonName: " + args[2])
    }
});

is not working for the postNotificationName:Object:userInfo. I guess the issue is in the line "var hook = ObjC.classes.NSNotificationCenter["- postNotificationName:"];".
Does anyone know what is wrong with it and how to make it work please?
Thank you

A: According to the Apple documentation the class NSNotificationCenter has no selector "- postNotificationName:".
There are two selectors with that name but they have additional parameters:

*

*"- postNotificationName:object:userInfo:"

*"- postNotificationName:object:"
If you want to hook any of these selectors you have to use the full selector string as stated above for hooking:
var hook = ObjC.classes.NSNotificationCenter["- postNotificationName:object:userInfo:"];

or
var hook = ObjC.classes.NSNotificationCenter["- postNotificationName:object:"];


text:
Q: How can I edit WooCommerce menu? I want edit menu where can found "My Account", "My Orders", etc. I want include new links on that menu, but I can´t edit via admin panel and can´t found the template where woocommerce creates the menu.

A: you can find a solution here.
it worked for me and i think it will be working for you too.
<?php
/*
* Add custom endpoint that appears in My Account Page - WooCommerce 2.6
* New URL below as Claudio changed his github username
* Ref - https://gist.github.com/claudiosanches/a79f4e3992ae96cb821d3b357834a005#file-custom-my-account-endpoint-php
*/

class My_Custom_My_Account_Endpoint
{

    /**
    * Custom endpoint name.
    *
    * @var string
    */
    public static $endpoint = 'my-custom-endpoint';

    /**
    * Plugin actions.
    */
    public function __construct()
    {
        // Actions used to insert a new endpoint in the WordPress.
        add_action( 'init', array( $this, 'add_endpoints' ) );
        add_filter( 'query_vars', array( $this, 'add_query_vars' ), 0 );

        // Change the My Accout page title.
        add_filter( 'the_title', array( $this, 'endpoint_title' ) );

        // Insering your new tab/page into the My Account page.
        add_filter( 'woocommerce_account_menu_items', array( $this, 'new_menu_items' ) );
        add_action( 'woocommerce_account_' . self::$endpoint .  '_endpoint', array( $this, 'endpoint_content' ) );
    }

    /**
    * Register new endpoint to use inside My Account page.
    *
    * @see https://developer.wordpress.org/reference/functions/add_rewrite_endpoint/
    */
    public function add_endpoints()
    {
        add_rewrite_endpoint( self::$endpoint, EP_ROOT | EP_PAGES );
    }

    /**
    * Add new query var.
    *
    * @param array $vars
    * @return array
    */
    public function add_query_vars($vars)
    {
        $vars[] = self::$endpoint;

        return $vars;
    }

    /**
    * Set endpoint title.
    *
    * @param string $title
    * @return string
    */
    public function endpoint_title($title)
    {
        global $wp_query;

        $is_endpoint = isset( $wp_query->query_vars[ self::$endpoint ] );

        if ($is_endpoint && ! is_admin() && is_main_query() && in_the_loop() && is_account_page()) {
            // New page title.
            $title = __( 'My Stuff', 'woocommerce' );

            remove_filter( 'the_title', array( $this, 'endpoint_title' ) );
        }

        return $title;
    }

    /**
    * Insert the new endpoint into the My Account menu.
    *
    * @param array $items
    * @return array
    */
    public function new_menu_items($items)
    {
        // Remove the logout menu item.
        $logout = $items['customer-logout'];
        unset( $items['customer-logout'] );
        // Insert your custom endpoint.
        $items[ self::$endpoint ] = __( 'My Stuff', 'woocommerce' );

        // Insert back the logout item.
        $items['customer-logout'] = $logout;

        return $items;
    }

    /**
    * Endpoint HTML content.
    */
    public function endpoint_content()
    {
        wc_get_template( 'myaccount/navigation.php' ); ?>

Hello World! - custom field can go here

        <?php
    }

    /**
    * Plugin install action.
    * Flush rewrite rules to make our custom endpoint available.
    */
    public static function install()
    {
        flush_rewrite_rules();
    }
}

new My_Custom_My_Account_Endpoint();

// Flush rewrite rules on plugin activation.
register_activation_hook( __FILE__, array( 'My_Custom_My_Account_Endpoint', 'install' ) );

redpajama_set_name: RedPajamaStackExchange


text:
Q: Append query error My primary key of Specialization table is complex and consists of two columns: Specialization_id and Specialty_id(which is foreign key of Specialty table).
I am going to make insert query by creating a new SPECIALIZATION of an existing specialty.
I have some specializations in my table already, primary key for one specialty with id = 1 looks like   (1,1) (2,1), with id = 2 looks like (1,2) (2,2).
Now I am going to add a new Specialization to Specialization table, but this Specialization should reference to existing Specialty.
My idea is
    INSERT INTO Specialization ( Specialization_name, Specialization_id, Specialty_id )
VALUES( 'Network technologies','(SELECT Max(Specialization_id) FROM Specialization WHERE Specialty_id = '2')+1', '2');

I've tried with '' clauses and without it, still, I am getting errors.
What should I do here?

A: In a database like MySQL or ORACLE you should not programatically increment the primary key.  Instead you should set the field to AUTOINCREMENT when you design the database.
That would change your INSERT statement to:
 INSERT INTO Specialization (Specialization_name, Specialty_id)
 VALUES('Network technologies', '2')

which is not only much easier, it is safer.
edited to add: Are you sure Specialty_id is a string?  I would think it would be some kind of number.

A: Your main error is the quotes, since your subquery is quoted it will get processed as a string and not a query.
Also, you don't need to use a subquery if you don't have a main query:
INSERT INTO Specialization ( Specialization_name, Specialization_id, Specialty_id )
SELECT 'Network technologies' As a, Max(Specialization_id)+1 As b, 2 As c
FROM Specialization WHERE Specialty_id = 2

However, like dstudeba said, relying on autonumbers for creating new IDs is probably smarter.


text:
Q: How to display posts i grid photo am trying to make grid view of posts for a specific category any one to help
<?php
$args = array(
'post_type' => 'post',
'category_name' => 'featured',
'posts_per_page' => 5,
'post__not_in' => get_option( 'sticky_posts' )
);
$the_query = new WP_Query( $args );?>

A: You need to build the query and then loop through it afterwards.

<?php
//Your Args
    $args = array(
    'post_type' => 'post',
    'category_name' => 'featured',
    'posts_per_page' => 5,
    'post__not_in' => get_option( 'sticky_posts' )
    );

    // The Query
    $query = new WP_Query( $args );

    // The Loop
    while ( $query->have_posts() ) {
        $query->the_post();
        echo '
' . get_the_title() . '
';
    }
?>

Then where the code echos the title, you would include your HTML to build your grid. And obviously have extra CSS elsewhere to style it as a grid.


text:
Q: Saving data from JSON end point I am trying to map over the returned json and save the id into profile/profiles. However it does not seem to be mapping over the the data correctly, id: ${ profile.id } this bit needs to be changed? Any help is much appreciated.
Is their a online tool that can help with me this?
API request:
  // Grabs company data from the json url
  private getProfiles() {
    let config = {
      headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
    }
    axios
      .get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
      .then(response =>
          response.data.map(profile => ({
            id: `${ profile.id }`
         }))
        )
        .then(profiles => {
          this.setState({
            profiles
          });
        })
      // We can still use the `.catch()` method since axios is promise-based
      .catch(error => this.setState({ error, isLoading: false }));
  }

Json data returned:
{
    "localizedLastName": "King",
    "id": "fm0B3D6y3I",
    "localizedFirstName": "Benn"
}

When I console log the response.data

A: If the only data returned from your endpoint is the JSON you posted, then you don't have an array to map over.
You have a single object.
I've never used the axios library before, but looking at the source code response.data should be the JSON-parsed responseText from the XHR request:
https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/adapters/xhr.js#L51-L53
https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/defaults.js#L61
And now I see that you have posted response.data and it matches what I'd expect.
With that in mind I'd suggest handling it like this:
 // Grabs company data from the json url
  private getProfiles() {
    let config = {
      headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
    }
    axios
      .get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
      .then(response => ({
            id: profile.id
         }))
        .then(profiles => {
          this.setState({
            profiles
          });
        })
      // We can still use the `.catch()` method since axios is promise-based
      .catch(error => this.setState({ error, isLoading: false }));
  }

What you're getting back is a single profile though.  If you need profiles to be an array you'll need to put the response in an array.

A: I don't get it, what you are trying to do. In the map you have a callback function, but as I see you wrote there an object. If you are wanting to rewrite the current profile's id then write this:
 response.data.map(profile => ({
    profile.id = `${ profile.id }`;
 }))

But if you want it to make a variable then this:
 response.data.map(profile => ({
   let id = `${ profile.id }`;
 }))


text:
Q: Performance of Array#Contain vs OR logic vs switch statement Which of these is the fastest and which is the slowest (C#)?
// Array#Contain
int i = ...;
if ((new int[] { 0, 1, 3, 7, ... }).Contains(i))
{
  ...
}

// OR logic
int i = ...;
if (i == 0 || i == 1 || i == 3 || i == 7  || ...)
{
  ...
}

// switch statement
int i = ...;
switch(i)
{
  case 0:
  case 1:
  case 3:
  case 7:
  ...
    ...
    break;
}

A: Performance of these things depends on the target machine architecture and maybe OS.
For the x86/x64 machines, I believe the code above should be translated by JIT to the following assembler equivalents:

*

*Array.Contains method
lea    EDI, [...]
mov    ECX, sizeof(...)
repne  scasd

*Sequental ORs in if statement
mov    EAX, ...
cmp    EAX, 0
jz     iftrue
cmp    EAX, 1
jz     iftrue
cmp    EAX, 3
jz     iftrue
...
jmp    endif
iftrue:
...
endif:

*switch statement
lea    EBX, [case_values_table]
xor    EAX, EAX
mov    AL, case_index
xlat
mov    ESI, EAX
jmp    [case_codeblocks_table][ESI * 4 or 8]

The only thing you need is to sum timings of the ASM instructions for each option, including potential disadvantage of any jmps due to the positive probability of clearing the opcode prefetching queue.
But I believe, that the much better advice is to choose the most supportable C# code.

A: I do not know for sure, but I would expect the switch-statement to be the fastest for the reason explained here, i.e. constant lookup time through implementation as a hashtable (for case statements with more than 5 items, that is).
Creating a new int[] for one .Contains seems very inefficient, but you might work around that with a constant field. Also, the method will have to iterate over all elements (worst case), so it is probably the least favorable option performance wise.
The if cascade might beat switch if in almost every case the first condition is correct, since it won't have to evaluate anything after that has been determined.
That being said, I'd usually go with an array, just because it reads nicely and is easily changed. The performance gains are usually moot.


text:
Q: Execute .exe file on server side from local desktop I have an web application, which was working on server (virtual client). After Publishing and checking from the client side(Locally), I'm getting error.
code I used:
protected void BtnLoadTempTable_Click(object sender, EventArgs e)
{
    ProcessStartInfo ps = new ProcessStartInfo();
    ps.UseShellExecute = false;
    System.Diagnostics.Process.Start(@"D:\Solutions\TFS_Itsme\DEV\WebSolution\WebService\bin\Debug\WebService.exe");
}

Error I got
File not specified

A: I'm going to answer you questions by describing a good architecture to perform what you are describing.   This is designed to be used in a secure production environment.
Requirement:
Allow a remote user to start a process on the server to perform some task.
(You may have other requirements, but at this point all you have given is this one requirement.)
Implementation hardware:

*

*Secure and locked down web server.

*Secure and locked down application server

*Secure and locked down database server (only be connected to via web and application server
Note, you can run more than one of these on the same physical or virtual server but the processes should be run as different service accounts (users) which have rights to only the resources they need to perform their function.
Data Model

*

*one or more tables which describe the action which needs to take place (for example run example.exe)

*one or more tables which describe pending actions to perform (for example, perform an action described in the action table now or in the future)
Use case / Process flow

*

*User connects to website and requests an action be taken (run example.exe) -- this will typically be selected from a list of allowed actions stored in the DB

*Website updates the pendingactions table to include information about this request (who asked and when it needs to be run)

*User interaction is done.

*On the application server (NOT THE WEB SERVER) an agent is checking for actions to perform.  That agent sees it needs to run the program -- it does so.
-> Program has been run.
OK -- you are probably looking at this and saying "why"?  The importance here is creating a secure environment.  The user is never running or using code that runs other code on the server.  The user can only pick from a list of "approved" actions -- they don't enter the name of the program.  When the program is run it is run in a different context, by a different service account, that has different rights.

You probably noticed this is VERY different than the implementation design you described.  This is why I made my comment.  No programmer who has a good understanding of secure architecture would ever implement the design you describe.  It is very likely such a design would be hacked easily.


text:
Q: vertically align text in HTML list On this page there's a menu in the right sidebar that is composed of a HTML list with this structure:

         Home

        Development

        Management

        Learning

Notice that some menu entries have (font) icons to the left of the label, whereas others don't. This makes the menu appear rather unsightly, because the labels are not vertically aligned.
Is there are any way to vertically align the labels, ideally without introducing additional HTML elements (because that messes up some immediate descendant rules that are defined within Bootstrap itself)?

A: Try this:
.nav-pills.nav-stacked > li > a {
  padding-left: 25px;
}

.nav-pills.nav-stacked > li > a > i {
  position: absolute;
  margin-left: -25px;
}

It takes the icons out of the flow, puts the text 25px to the right,  and then positions the icons 25px to the left


text:
Q: How do I read through a CSV file twice and print certain rows based on arguments passed through the function? I am having trouble with reading through a CSV file and printing out a row based on whether or not a string value exists in that row. Here is my current code:
main("Fuel")
main("Temp")

^This is the main function that will take a string as an argument and pass it through another function.
def main(String):
with open(fileName, 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        for field in row:
            if field == String:
                print(row)

^This is the function that will take the argument from above "Fuel" and "Temp" and look for it in a CSV file. If it finds it, it will print the row out.

A header
Another header

Fuel
X116.75 Y151 Z175

Fuel
X138.50 Y151 Z175

Fuel
X160.25 Y151 Z175

Temp
X138.50 Y93   Z225

Temp
X160.25 Y122 Z225

Temp
X116.75 Y93   Z225

^ This is CSV file that I am reading from
When I execute my code I am able to print out all of the "Fuel" rows, but all of the "Temp" rows do not get printed. Here is my output:
['Fuel', 'X116.75', 'Y151', 'Z175']
['Fuel', 'X138.5', 'Y151', 'Z175']
['Fuel', 'X160.25', 'Y151', 'Z175']

Even if I have main("Temp") in front of main("Fuel"), nothing gets printed as well. It seems like the program will only iterate through the first row. How do I change my program so that it can read through the whole file each time and print all the rows that have the string value in it?

A: Your main function should iterate over reader instead of data.
def main(s):
    with open(fileName, 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            for field in row:
                if field == s:
                    print(row)


text:
Q: IntelliJ: how do you override VM options for a single test? I want to run a single test method in a test class. Running "Modify Configuration" (screenshot below), there is no option to override a system property. It is possible to override environment variables (System.getenv) but that is not the same.

A: VM options are in the third field where you currently see -ea. You can add your own VM options there.


text:
Q: How to sign outgoing soap request without using wsf/php? I am looking how to sign soap header using PHP.
The soap service is built by apache rampart, which is exactly same as sample 2 in https://axis.apache.org/axis2/java/rampart/samples.html.
Now, I have a soap client develop by using PHP.
I have no idea how to sign the entire headers and body.
I can make my soap request as following
<?xml version="1.0" encoding="UTF-8" ?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://ws.globesteel.com" xmlns:ns2="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:ns3="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
  <SOAP-ENV:Header>
    <ns3:Security SOAP-ENV:mustUnderstand="1">
      <ns2:Timestamp>
        <ns2:Created>2016-07-13T08:16:02Z</ns2:Created>
        <ns2:Expires>2016-07-20T06:56:02Z</ns2:Expires>
      </ns2:Timestamp>
      <ns3:Signature>
        <ns3:SignedInfo>
          <Signature>
            <SignedInfo>
              <CanonicalizationMethod>
                <Algorithm>http://www.w3.org/2001/10/xml-exc-c14n#</Algorithm>
              </CanonicalizationMethod>
              <SignatureMethod>
                <Algorithm>http://www.w3.org/2000/09/xmldsig#rsa-sha1</Algorithm>
              </SignatureMethod>
              <Reference>
                <SOAP-ENC:Struct>
                  <Transforms>
                    <SOAP-ENC:Struct>
                      <Algorithm>http://www.w3.org/2001/10/xml-exc-c14n#</Algorithm>
                    </SOAP-ENC:Struct>
                  </Transforms>
                  <DigestMethod>
                    <Algorithm>http://www.w3.org/2000/09/xmldsig#sha1</Algorithm>
                  </DigestMethod>
                  <DigestValue>8f6c3a934fc237673e9f1a12793f5507b8103e4a</DigestValue>
                  <URI>#_body</URI>
                  <Id/>
                </SOAP-ENC:Struct>
                <SOAP-ENC:Struct>
                  <Transforms>
                    <SOAP-ENC:Struct>
                      <Algorithm>http://www.w3.org/2001/10/xml-exc-c14n#</Algorithm>
                    </SOAP-ENC:Struct>
                  </Transforms>
                  <DigestMethod>
                    <Algorithm>http://www.w3.org/2000/09/xmldsig#sha1</Algorithm>
                  </DigestMethod>
                  <DigestValue></DigestValue>
                  <URI>#_control</URI>
                  <Id/>
                </SOAP-ENC:Struct>
              </Reference>
            </SignedInfo>
            <SignatureValue>Yu/DkCbKXAoalySGM2XdieRYhk1rnwhFKNcklXn5l+YgNk3AXEnpr4yDAlReYgU3FGOZh0XGUn8hGWwEs28S+xjrROgb3G/SYKVKbS3EmAU/vLBa+lABn/0NDoGdR/iIv9C7XAr/OBhE++cHA+lktZSS1SUPtfG5BAifN/RtfkE=</SignatureValue>
            <KeyInfo>aqePjuZzE1lzwMMtquksvNJsbmI=</KeyInfo>
          </Signature>
        </ns3:SignedInfo>
      </ns3:Signature>
    </ns3:Security>
  </SOAP-ENV:Header>
  <SOAP-ENV:Body>
    <ns1:GetAvailableSecurityQuestions/>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

But I still get error return "Message is not signed".

A: After 2 weeks of pain, I finally solved this by using https://github.com/robrichards/xmlseclibs


text:
Q: Incrementing numerical values in excel formula Hello I would love some help with this problem I am having an issue in Excel I am trying to pull fill a formula that I have written to advance the value of the cells being counted. What my formula does is check each cell to see if the letter p is in the cell, and if so it counts up for every cell that it searches and outputs the total in the cell the formula is in, pretty simple.
This is the pattern for the formula that I have created.
=SUM(COUNTIF(INDIRECT({"K1","N1","Q1","T1","W1","Z1","AC1","AF1"}),"*p*"))
=SUM(COUNTIF(INDIRECT({"K2","N2","Q2","T2","W2","Z2","AC2","AF2"}),"*p*"))
=SUM(COUNTIF(INDIRECT({"K3","N3","Q3","T3","W3","Z3","AC3","AF3"}),"*p*"))

For some reason this will not AutoFill when I pull down the cell.
I have thought about perhaps writing a python script to increment the values but am not that familiar with how to do this within Python.
Does anyone here have an idea in how I could achieve the repeated formula without having to manually type it in each cell? I am trying to normalize a "Database" and this is the only way that I am able to normalize level 3.
Thank you in advance.

A: Countif requires the first argent to be a range, therefore it errors. The following function does work:
=SUMPRODUCT(N(ISNUMBER(SEARCH("p",CHOOSE({1,2,3,4,5,6,7,8},K1,N1,Q1,T1,W1,Z1,AC1,AF1)))))

A: A bit hard to follow  without seeing a few example values of k1 n1 etc but it might be worth adding in the address formula =ADDRESS()


text:
Q: Robot Framework, AngularJSLibrary - No module named 'Selenium2Library.locators' I am setting up a new machine on Windows Server 2016 to run some existing Robot Framework tests of an Angular application. As it's a new machine I decided to move from Python 2 to 3.  I've installed all the dependencies I should need...
> pip list
certifi (2017.11.5)
chardet (3.0.4)
idna (2.6)
pip (9.0.1)
pip-autoremove (0.9.0)
requests (2.18.4)
robotframework (3.0.2)
robotframework-angularjs (0.0.6)
robotframework-extendedselenium2library (0.9.1)
robotframework-pabot (0.43)
robotframework-requests (0.4.7)
robotframework-selenium2library (3.0.0)
robotframework-seleniumlibrary (3.0.0)
robotremoteserver (1.1)
selenium (3.8.0)
setuptools (28.8.0)
urllib3 (1.22)'

When I run my tests (both in Jenkins and on the command line) I get the following error
Error in file 'C:\apps\Jenkins\workspace\RF_RunUITests\common.robot': Importing test library 'AngularJSLibrary' failed: ModuleNotFoundError: No module named 'Selenium2Library.locators'
Traceback (most recent call last):
  File "C:\apps\buildTools\Python36-32\lib\site-packages\AngularJSLibrary\__init__.py", line 6, in <module>
    from Selenium2Library.locators import ElementFinder
PYTHONPATH:
  C:\apps\buildTools\Python36-32\python36.zip
  C:\apps\buildTools\Python36-32\DLLs
  C:\apps\buildTools\Python36-32\lib
  C:\apps\buildTools\Python36-32
  C:\apps\buildTools\Python36-32\lib\site-packages

I have a very similar problem when I switch to the 'ExtendedSelenium2Library' - which also has support for Angular apps.
Error in file 'C:\apps\Jenkins\workspace\RF_RunUITests\common.robot': Importing test library 'ExtendedSelenium2Library' failed: ModuleNotFoundError: No module named 'Selenium2Library.keywords'

I've done a number of searches but I have not found anything to help.  I've tried uninstalling and reinstalling!
The test suite I've been focusing on for testing purposes pulls in a resource that references the two following libraries
*** Settings ***
Library           Selenium2Library    implicit_wait=5    timeout=5
Library           AngularJSLibrary
Library           String
Library           DateTime
Library           Collections

I don't really know Python very well so I am struggling to know what to do next.
Anyone got any ideas?
Many thanks

A: It appears that the libraries you are using haven't been updated to use the new version of SeleniumLibrary. They are trying to import modules that no longer exist, or exist under another name.
You'll either need to upgrade the libraries yourself, or switch back to using version 2.x of Selenium2Library.


text:
Q: what is data length/size limit of json datatype in mysql 5.7 I am using mysql 5.7 for json type storage. I want to know what is the size/length limit of json data type in mysql 5.7.
I am trying to convert json object into json string and store it , but somehow it is ignoring it. So is there any way to store the length json string into json datatype ?

A: According to here:

It is important to keep in mind that the size of any JSON document stored in a JSON column is limited to the value of the max_allowed_packet system variable.

And according to the docs this is a Maximum Value of 1,073,741,824. Note that the default value of max_allowed_packet is lower and depends on the version of MySQL you use.


text:
Q: Change Spring RestTemplate logging I'm using spring restTemplate,
when I get a 403 response error code from a specific method restTemplate writes it to log as WARN I wold like to change only that line to INFO. is it possible?
WARN RestTemplate - GET request for "http://localhost:8080/xxx/xxx/internalKeepAlive" resulted in 403 (Forbidden); invoking error handler

A: No, not possible. It is a WARN condition and it has been coded this way. What you could do is get the RestTemplate sources recompile them an change from log.warn to log.info :)


text:
Q: How to notify all People in a regular message (not Announcement) in a specific group (not All Company) in Yammer? From what I understand, to notify everyone in Yammer there are several possibilities:

*

*post in the All Company group;

*post an Announcement in a group, all the people from this group will
be notified;

*post a regular post (Update) anywhere and manually add all the
people to notify in the field (or add the @ in the text for everyone).

Is there any less tedious way to achieve the behaviour from the last option above (not realistic with a high number of People)? I.e., without having to post in All Company or to make an Announcement or to manually tag all the people? (Is there a possibility to create a "All" alias that could be use like @All to notify everyone? Or to create groups of People and notify these groups, e.g. @group1?)
So: is there a simple and efficient way to notify everyone (all the People of the company) in a regular message (Update) done in a specific group within a Yammer network?

A: There isn't support for this in the product. If you need to notify everyone you should use an announcement because that's what it's designed to do.
Notifying everyone in a similar way to sending an email to everyone is not considered to be a best practice within a social tool like Yammer. The message will be surfaced in Yammer for users, and they'll see other people replying or liking it.
You missed out on how to @mention users from code. To @mention a small number of users (best practive) you can take the name (user permalink) element from the users.json (or other user endpoint). Then post it in the body of a message as @name replacing "name" with the permalink value.


text:
Q: Python - how to overwrite output from Markdown library I have following problem, i'm using markdown library for my webapp and i need to modify the output generated by it, namely i want to change default  tag into . What would be the best way to change the html generated by this module?

A: You probably want to use Python-Markdown's Extension API. Most people use the API to add their own syntax, but it can alter the existing output just as easily. That way, you can use Markdown's parser but get your desired output. No need for wrappers or parsing twice.
In your case, you want to override (subclass) the ImagePattern class and define your own Element which is returned by the handleMatch method. Then you just need to tell Markdown about it. In your case, the regex doesn't even need to be different. Just import and reuse the existing IMAGE_LINK_RE and override inlinePatterns["image_link"].
This tutorial should get you started. While it is implementing a different syntax, the basics are the same and it is a lot shorter than the API docs. See also part 1.
For completeness, if you use the reference syntax for you images, you would need to do the same thing with the ImageReferencePattern. You may find it easier to implement as a TreeProcessor instead (which I believe is what @Kos was referring to in his comment to the original post). That way the existing parser builds the existing output, but before serializing the ElementTree to text, you can loop through all the img tags and alter them to fit your needs. As an example, the HeaderId Extension does this to add IDs to h1-6 tags.


text:
Q: Angular how to output a string with {{}}? for example:
js:
var str = "this my mark {{a}} {{e}} {{i} {{o}} {{u}}, select one!";
$scope.tip = str;

html:
<p>{{tip}}</p>

how to make the output is this my mark {{a}} {{e}} {{i} {{o}} {{u}}, select one!?

A: Add ngNonBindable attribute to the element who's content you don't want to be compiled or bind.


text:
Q: range of POSIXct dates in lists Consider this list of POSIXct dates:
times <- list(as.POSIXct(c("2012-07-26 00:30", "2012-07-26 6:20",
                           "2012-07-26 10:40", "2012-07-26 15:50")),
              as.POSIXct(c("2012-07-26 01:15", "2012-07-26 10:10",
                           "2012-07-26 15:15", "2012-07-26 18:50")),
              as.POSIXct(c("2012-07-26 00:35", "2012-07-26 15:05",
                           "2012-07-26 19:36", "2012-07-26 22:32")),
              as.POSIXct(c("2012-07-26 03:34", "2012-07-26 16:43",
                           "2012-07-26 21:44", "2012-07-26 23:45")))

If I do:
range(times[[1]])

I correctly get:
[1] "2012-07-26 00:30:00 CEST" "2012-07-26 15:50:00 CEST"

Now, if I do:
range(times[c(1,3)])

for whatever reason R decides to convert the POSIXct objects into timestamps and gives me
[1] 1343255400 1343334720

I then try to reconvert them to POSIXct by doing:
as.POSIXct(range(times[c(1,3)]), origin="1970-01-01 00:00")

And, strangely, I get the range with 1 hour of advance:
[1] "2012-07-25 23:30:00 CEST" "2012-07-26 21:32:00 CEST"

So I have to do:
as.POSIXct(range(times[c(1,3)]), origin="1970-01-01 01:00")

To get the correct range of:
[1] "2012-07-26 00:30:00 CEST" "2012-07-26 22:32:00 CEST"

Am I missing something or is there a bug somewhere?

A: times[[1]] is a vector, while times[c(1,3)] is a list.  Convert the latter to a vector before calling range and all is well.
You don't want to use unlist though, since it will only return an atomic vector (range must be doing something like that internally), but you can use do.call:
range(do.call(c,times[c(1,3)]))

The differences you get from using as.POSIXct are likely due to timezone issues.

A: As Joshua said, the hour is because of timezones. Try, for example:
times <- list(as.POSIXct(c("2012-07-26 00:30", "2012-07-26 6:20",
                       "2012-07-26 10:40", "2012-07-26 15:50"), "GMT"),
          as.POSIXct(c("2012-07-26 01:15", "2012-07-26 10:10",
                       "2012-07-26 15:15", "2012-07-26 18:50"), "GMT"),
          as.POSIXct(c("2012-07-26 00:35", "2012-07-26 15:05",
                       "2012-07-26 19:36", "2012-07-26 22:32"), "GMT"),
          as.POSIXct(c("2012-07-26 03:34", "2012-07-26 16:43",
                       "2012-07-26 21:44", "2012-07-26 23:45"), "GMT"))
as.POSIXct(range(times[c(1,3)]), origin="1970-01-01 00:00", "GMT")


text:
Q: iisnode db connection pooling I'm running a Node.js webapp via iisnode hosted on Windows Server 2012 R2 - IIS 8.5. On client request the app needs to query data from the server DB (PostgreSQL).
Within standalone Node.js apps one usually implements DB client pooling (via pg module or full scale ORM, e.g. Squeelize.js). iisnode however fires up a Node.js process per client request, rendering an appwise pooling useless (as far as I understand), although it does seem to work with the pg modules pooling instance.
I'm fairly new to IIS; how would I implement an efficient DB connection pooling (or an appropriate substitute) given the setup above? E.g.:

*

*does IIS / iisnode manage db connections, perhabs via single client connection requests?

*is using appwise client pooling still the way to go?

*is using an IIS module preferrable?

EDIT: The linked tutorial for MongoDB on Tomasz Janczuks iisnode GitHub site uses a single client connection if I'm not mistaken, but is that fit for near production use with multiple clients and possibly complex queries?
I'd like to stick to setting up / configuring the connection inside Node.js if that is possible and reasonable.


text:
Q: update Firebase emulator function timeout duration When emulating firebase functions locally is there a way to change the function timeout from the default 60s?
--idlePruneInterval has been added as an option to the google cloud emulator CLI: https://github.com/GoogleCloudPlatform/cloud-functions-emulator/issues/66
This option doesn't appear to work is not officially supported in either the firebase serve mode:
firebase serve --only functions --idlePruneInterval=5000

or the experimental shell emulation:
firebase experimental:functions:shell --idlePruneInterval=5000

Is there another way around this problem? Perhaps editing a config file?

A: The Cloud Functions emulator from Firebase is separate from the one provided by the Google Cloud Platform org. The command line parameters from one won't necessarily work on the other.


text:
Q: Evaluate the indefinite integral $\int \frac{1}{x^2} \sin\left(\frac{6}{x}\right) \cos\left(\frac{6}{x}\right) \, dx $ Evaluate the indefinite integral:
$$\int \frac{1}{x^2} \sin\left(\frac{6}{x}\right) \cos\left(\frac{6}{x}\right) \, dx $$
(using substitution)
The answer is: $$\frac {1}{24} \cos\left(\frac{12}{x}\right) + C $$
Whereas I get a slightly different one.
Here's my solution:
$$u = \frac{6}{x}$$
$$du = - \frac{6}{x^2} \cdot dx$$
$$-\frac {1}{6} du = \frac {1}{x^2} \cdot dx$$
Making substitution:
$$ \int -\frac{1}{6} du \sin (u) \cos (u)  $$
adding a new variable for substitution:
$$s = \cos (u)$$
$$ds = -sin(u) du$$
Making substitution:
$$ \frac {1}{6} \int ds \cdot s  $$
Evaluating:
$$ \frac{1}{6} \cdot \frac{s^2}{2} = \frac{s^2}{12} = \frac{\cos^2(u)}{12} = \frac{\cos^2(\frac{6}{x})}{12}$$
Then using a half angle formula for $\cos^2$:
$$ \frac {\frac{1}{2} \cdot (1 + \cos(\frac{12}{x}))}{12} = \frac{1}{24} + \frac{1}{24} \cdot \cos\left(\frac{12}{x}\right) + C$$
As you can see I have an additional $\frac{1}{24}$ in my answer... so what did I do wrong?

A: You  missed the constant of integration all the way! It "absorbs" the $\frac{1}{24}$!
Spot the difference:
Evaluating:
$\displaystyle \frac{1}{6} \cdot \frac{s^2}{2} +c= \frac{s^2}{12} +c= \frac{\cos^2(u)}{12} +c= \frac{\cos^2(\frac{6}{x})}{12}+c$, where c is the constant of integration.
Then using a half angle formula for $\cos^2$:
$\displaystyle \frac {\frac{1}{2} \cdot (1 + \cos(\frac{12}{x}))}{12} +c$ = $\frac{1}{24} \cdot \cos(\frac{12}{x}) + C$, where $C=c+\frac{1}{24}$

A: You did everything right, but you're constant of integration "absorbs" the $\frac{1}{24}$
$$\frac{1}{24}+C=C$$
The $C$ is an arbitrary constant meaning that it could be anything (depending on our initial conditions). So, what's a constant plus an arbitrary constant? It's just another arbitrary constant!
If it helps, you could do something like:
$$\frac{1}{24}+C=D$$


text:
Q: Is there a shorthand for  It's just such a long tag and I use it so much.
For example
<input name="LastName" <cfoutput> value="#FORM.LastName#" </cfoutput> />
becomes
<input name="LastName" <?> value="#FORM.LastName#" </?> />
Maybe I'm just asking for too much.

A: Nope <cfoutput> is all you get. For the tag syntax anyway. You could switch to script syntax instead.
<cfoutput>

hello

</cfoutput>

versus
<cfscript>
    writeOutput("
hello
");
</cfscript>

You could always add a short-cut (keystroke) to your editor of choice for the tag.

A: Ideally, you wouldn't wrap such a small piece of code in a cfoutput. It really makes the code hard to read and maintain.
Instead, you should wrap larger and logical chunks of code in cfoutput. There's little additional overhead and it's much easier to read and maintain.
<cfoutput>
<form>
    <input value="#SomeVar#">
    <input value="#SomeVar#">
    <input value="#SomeVar#">
    <input value="#SomeVar#">
    <input value="#SomeVar#">
</form>
</cfoutput>

A: <cfoutput>
    <form>
        <input name="LastName"  value="#FORM.LastName#"/>
    </form>
</cfoutput>


text:
Q: Flask Docker Heroku at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" I'm trying to publish a web app with Flask and docker via Heroku. I see this error in the Heroku logs:
2022-09-25T10:08:54.908035+00:00 app[web.1]:     obj = StockUnpickler.load(self)
2022-09-25T10:08:54.908035+00:00 app[web.1]: _pickle.UnpicklingError: invalid load key, 'v'.
2022-09-25T10:08:54.908219+00:00 app[web.1]: [2022-09-25 10:08:54 +0000] [6] [INFO] Worker exiting (pid: 6)
2022-09-25T10:08:55.035577+00:00 app[web.1]: [2022-09-25 10:08:55 +0000] [5] [WARNING] Worker with pid 8 was terminated due to signal 15
2022-09-25T10:08:55.036926+00:00 app[web.1]: [2022-09-25 10:08:55 +0000] [5] [WARNING] Worker with pid 6 was terminated due to signal 15
2022-09-25T10:08:55.042420+00:00 app[web.1]: [2022-09-25 10:08:55 +0000] [5] [WARNING] Worker with pid 9 was terminated due to signal 15
2022-09-25T10:08:55.127566+00:00 app[web.1]: [2022-09-25 10:08:55 +0000] [5] [INFO] Shutting down: Master
2022-09-25T10:08:55.127617+00:00 app[web.1]: [2022-09-25 10:08:55 +0000] [5] [INFO] Reason: Worker failed to boot.
2022-09-25T10:08:55.270746+00:00 heroku[web.1]: Process exited with status 3
2022-09-25T10:08:55.329162+00:00 heroku[web.1]: State changed from up to crashed
2022-09-25T10:34:20.321382+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=amr-book-rec.herokuapp.com request_id=d1ac4163-64a4-42e2-b872-5ab1fee6a99e fwd="180.252.81.6" dyno= connect= service= status=503 bytes= protocol=https
2022-09-25T10:34:21.176332+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=amr-book-rec.herokuapp.com request_id=2121b0eb-f4c8-4ce8-92d0-3065797fc085 fwd="180.252.81.6" dyno= connect= service= status=503 bytes= protocol=https

I don't know what the at=error code=H10 mean. How to deal with this error?
All my code can be found in my github page here: https://github.com/amrirasyidi/book_recommendation
Edit
This is my error now, I added heroku.yml as requested by the Heroku website when I try to deploy it again.
2022-09-25T23:56:24.147078+00:00 app[web.1]:     time.sleep(0.1)
2022-09-25T23:56:24.147087+00:00 app[web.1]:   File "/usr/local/lib/python3.9/site-packages/gunicorn/arbiter.py", line 242, in handle_chld
2022-09-25T23:56:24.147227+00:00 app[web.1]:     self.reap_workers()
2022-09-25T23:56:24.147236+00:00 app[web.1]:   File "/usr/local/lib/python3.9/site-packages/gunicorn/arbiter.py", line 525, in reap_workers
2022-09-25T23:56:24.147397+00:00 app[web.1]:     raise HaltServer(reason, self.WORKER_BOOT_ERROR)
2022-09-25T23:56:24.147412+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
2022-09-25T23:56:24.274738+00:00 heroku[web.1]: Process exited with status 1
2022-09-25T23:56:24.338518+00:00 heroku[web.1]: State changed from up to crashed
2022-09-26T01:07:46.615767+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=amr-book-rec.herokuapp.com request_id=ee73edda-8d0a-4395-a418-7d51d26a6bba fwd="180.251.183.93" dyno= connect= service= status=503 bytes= protocol=https
2022-09-26T01:07:47.774620+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=amr-book-rec.herokuapp.com request_id=371e3a7c-3530-4437-ba82-5904cd976e55 fwd="180.251.183.93" dyno= connect= service= status=503 bytes= protocol=https


text:
Q: How to get all selected values from ? Seemed odd I couldn't find this one already asked, but here it goes!
I have an html  as follows:
<select id="select-meal-type" multiple="multiple">
    <option value="1">Breakfast</option>
    <option value="2">Lunch</option>
    <option value="3">Dinner</option>
    <option value="4">Snacks</option>
    <option value="5">Dessert</option>
</select>

How do I get all the values(an array?) that the user has selected in javascript?
For example, if the user has selected Lunch and Snacks, I want an array of { 2, 4 }.
This seems like it should be a very simple task but I can't seem to do it.
Thanks.


text:
Q: Unable to cast object of type 'System.Byte[]' to type 'System.String[]' Hello I'm trying to pass image converted from Byte[] to String[] and display it in ReportViewer Image as following:
String[] dataImage;
private void showLogo()
{
    try
    {
        SqlDataAdapter dataAdapter = new SqlDataAdapter( new SqlCommand("SELECT logo
                                           FROM company WHERE id = 1", spojeni));
        DataSet dataSet = new DataSet();
        dataAdapter.Fill(dataSet);
        if (dataSet.Tables[0].Rows.Count == 1)
        {
            dataImage = new String[0];
            dataImage = (String[])(dataSet.Tables[0].Rows[0]["logo"]);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(""+ex);
    }
}

And this is the ReportViewer parameter:
ReportParameter[] parameter = new ReportParameter[24];
parameter[23] = new ReportParameter("rp_logo", dataImage );
this.reportViewer1.LocalReport.SetParameters(parameter);
this.reportViewer1.RefreshReport();

But I get following Exception Unable to cast object of type 'System.Byte[]' to type 'System.String[]'
Can someone help me solve this?
Thank you for your time.

A: Given ReportViewer requires a path to an image and not the actual image data itself, your best bet here is to save your byte[] to disk and reference this in the parameter instead e.g.
using (var cmd = new SqlCommand("SELECT logo FROM company WHERE id = 1", spojeni))
using (var dataAdapter = new SqlDataAdapter(cmd))
using (var dataSet = new DataSet())
{
    dataAdapter.Fill(dataSet);
    if (dataSet.Tables[0].Rows.Count == 1)
    {
        // generate temp file destination
        dataImage = System.IO.Path.GetTempFileName() + ".jpg"; // use whatever extension you expect the file to be in
        File.WriteAllBytes(dataImage, (byte[])dataSet.Tables[0].Rows[0]["logo"]); // save image to disk
    }

}

A: byte to string conversion can be done the following way
 Encoding.Ascii.GetString(yourByteArray)

if you need a further conversion you can do somthing like that:
Encoding.Ascii.GetString(yourByteArray).Select(c => c as string).ToArray()


text:
Q: GDAL concatenating vrts I'd like to concatenate a few vrts together. So i have three vrts representing data from different years and to make my life easier would like just to have one vrt created from the three vrts.
Each of the vrts has 365 bands, and i want the outputted vrt to be the stacking of these bands so (3*365) bands.
<VRTDataset rasterXSize="2400" rasterYSize="2400">
  <VRTRasterBand dataType="UInt16" band="1">
   [from 2007.vrt]
  </VRTRasterBand>
    ...
  <VRTRasterBand dataType="UInt16" band="365">
    [from 2007.vrt]
    </VRTRasterBand>
  <VRTRasterBand dataType="UInt16" band="366">
    [from 2008.vrt]
  </VRTRasterBand>
    ...
  <VRTRasterBand dataType="UInt16" band="730">
    [from 2008.vrt]
  </VRTRasterBand>
  <VRTRasterBand dataType="UInt16" band="731">
   [from 2009.vrt]
  </VRTRasterBand>
   ...
  <VRTRasterBand dataType="UInt16" band="1095">
   [from 2009.vrt]
  </VRTRasterBand>
</VRTDataset >

I was hoping something like:
gdalbuildvrt 2007_2009.vrt 200{7,8,9}.vrt

would work. But this unfortunately not. Instead of stacking as above i get:
<VRTDataset rasterXSize="2400" rasterYSize="2400">
  <VRTRasterBand dataType="UInt16" band="1">
   [from 2007.vrt band 1]
   [from 2008.vrt band 1]
   [from 2009.vrt band 1]
  </VRTRasterBand>
    ...
  <VRTRasterBand dataType="UInt16" band="N">
   [from 2007.vrt band N]
   [from 2008.vrt band N]
   [from 2009.vrt band N]
  </VRTRasterBand>
</VRTDataset >

which gdalinfo only records as 365 bands.
Pictorially 2007_2009.vrt would be constructed like:
2007_2009.vrt-|
             -- 2007.vrt
             -- 2008.vrt
             -- 2009.vrt

I'm on a unix system


text:
Q: How to make Jenkins job not to fail upon post-build actions failures? There is great build-name-setter-plugin for Jenkins, but in my instance it has staility issue over dependency version marking some builds as failed

IllegalStateException (Build step 'Changes build name' marked build as failure), while actual build is SUCCESS #62
https://github.com/jenkinsci/build-name-setter-plugin/issues/62

I cannot upgrade Jenkins or plugins right now.
How to make Jenkins job not to fail upon post-build actions failures?
It would be better build name not changed occasionally, than making build as failures while code is OK.


text:
Q: How to call create a proper interface I have an interface with two methods
interface IFoo{
  void FooOne(A,B,C);
  void FooTwo(D,E,F);
}

Now there are two implementation class which extends this interface. One is as follows:
class Foo1 implements IFoo{
 void FooOne(A,B,C);
  void FooTwo(D,E,F);
}

Other one is as follows :
 class Foo2 implements IFoo{
  void FooOne(A,B,C);
  void FooTwo(D,E,F);
}

Now Foo2 class dosen't needs parameter E at all. Parameter E is only required for class FOO1. So it's somehow ambious why this parameter is passed to class Foo2. So is there some another way so that I can do something like for class Foo2.
 class Foo2 implements IFoo{
  void FooOne(A,B,C);
  void FooTwo(D,F);
}

A: If Foo2 doesn't care about E, it should simply ignore it. You can't change the signature of FooTwo in a class that implements that interface, it doesn't make sens. The callers of IFoo.FooTwo must not be aware of the actual class that implements it.

A: If FooTwo(D,E,F) is your interface, then class Foo2 must implement that.
However, you could expose another non-interface overloaded public method for Foo2, like this
public void FooTwo(D,F) {
  this(D, null, F);
}

A: There is no syntactic way to do that. You have to refactor your classes.
Answer following questions to get a proper refactoring:

*

*Why isn't parameter E required in some cases?

*What does Foo2 have in common with Foo1?

*Why do they need the same interface?

A: If Foo2 does not need parameter E at all, you have designed your interface incorrectly. In an interface, you should only be requiring those methods and parameters that are implementation independent. This is because you are abstracting your implementation from the users of your interface and they should not need to care if it is Foo1 or Foo2 that is the actual implementation.

A: First, a class cannot extend an interface in java. So the code
class Foo1 extends IFoo{

when IFoo is an interface does not compile.
Assuming that you really meant implements:
When you have an interface, you define a contract, a skeleton. All the classes that implement this interface have to follow this contract. See How interfaces are actually used
The interface should be general, and everything that is specified in the interface should be applicable to all classes that implement it. So

Now Foo2 class dosen't needs parameter
  E at al

questions the design of the interface.
You still can have another method in Foo2 that takes only two parameters D anf F if need be.


text:
Q: Forecast Assistance given Monthly Time Series Data I'm looking for some help to determine what type of model I should use for the given data set:
structure(list(Date = structure(c(15706, 15737, 15765, 15796,
15826, 15857, 15887, 15918, 15949, 15979, 16010, 16040, 16071,
16102, 16130, 16161, 16191, 16222, 16252, 16283, 16314, 16344,
16375, 16405, 16436, 16467, 16495, 16526, 16556, 16587, 16617,
16648, 16679, 16709, 16740, 16770, 16801, 16832, 16861, 16892,
16922, 16953, 16983, 17014, 17045, 17075, 17106, 17136, 17167,
17198, 17226, 17257, 17287, 17318, 17348, 17379, 17410, 17440,
17471, 17501, 17532, 17563, 17591, 17622, 17652, 17683, 17713,
17744, 17775, 17805, 17836, 17866, 17897, 17928, 17956, 17987,
18017, 18048, 18078, 18109, 18140, 18170, 18201, 18231, 18262,
18293, 18322, 18353, 18383, 18414, 18444, 18475, 18506, 18536,
18567, 18597, 18628, 18659, 18687, 18718, 18748, 18779, 18809,
18840, 18871, 18901, 18932, 18962, 18993, 19024, 19052, 19083,
19113, 19144, 19174), class = "Date"), refined_petroleum_index = c(305.2,
323.1, 302.1, 288.2, 284.8, 286.6, 286.6, 294.2, 290, 290.4,
289.3, 296.5, 298, 298.9, 296.8, 295.5, 289.1, 288.7, 284.3,
284.6, 275.3, 258.4, 249, 213.6, 172, 176.9, 185.5, 175.4, 196.1,
197.2, 194.3, 183.6, 161, 160.7, 160.8, 144.8, 132.1, 119.5,
125.8, 131.9, 141, 151.8, 151.1, 145.2, 149.8, 158.2, 155.1,
162.4, 174.4, 174.8, 169.7, 170.2, 158.8, 156.5, 158.5, 169.4,
184.7, 185.5, 194.7, 200.8, 205.9, 209.8, 202.3, 208.5, 215.6,
220.6, 218, 220.6, 221.9, 232.5, 214.4, 191.1, 174.4, 186.2,
200.3, 212.6, 206.3, 191, 194.6, 191.1, 187.6, 195, 192.1, 200,
198.5, 185.3, 148.9, 91.5, 94.5, 122.6, 140.7, 147.4, 143, 146,
148.4, 171.3, 186.2, 207.4, 226.1, 223.9, 230.9, 237.4, 246.455,
248.072, 255.587, 277.508, 278.616, 270.678, 287.284, 324.794,
366.333, 380.416, 402.415, 455.191, 391.24)), row.names = c(NA,
-115L), class = "data.frame")

Here is the decomposition of the data:

Based on the seasonality in the decomposition, I believe that there is definitely yearly, maybe half a year seasonality, and quarterly data.
I have tried to building the following models:
hw_model <- hw(tsclean(training_hw), seasonal = "additive", h = length(validation_hw), initial = "optimal")

A Holt Winters' model with additive seasonality
dh_regression<- dhReg::dhr(training, XREG = NULL, Range =list(1:6), Frequency = 12, Criteria = "bic", maxp = 5,
    maxq = 5, maxd = 5)

A dynamic harmonic regression model with fourier orders 1-6.
harmonics <- fourier(tsclean(training), K = 6)
arima_model <- auto.arima(tsclean(training), seasonal = TRUE,  allowmean = T, allowdrift = T, biasadj = T,
                          lambda = Lambda, stepwise = F, approximation = F, test = "adf", ic = "aic",
                          xreg = harmonics)

An ARIMA(0,1,1)(2,0,0)[12] w/ errors model with fourier orders of 6 in the xreg. The Lambda is equal to -0.1.
Note: The training time series object has been log transformed. While, no transformation has been conducted on training_hw.
I have not found much success with any of these models so far. The one that has given my best success is the dynamic harmonic regression model as the RMSE and MAPE are lowest.
Anybody have any suggestions on what other models that I can use that might provide a better result than the models that I have built so far.


text:
Q: Is it possible to apply a grayscale image as view mask in SwiftUI? Is it possible to use a views .mask(...) modifier together with a grayscale image. I mean just like one uses a layer mask in Photoshop.
While it is not problem to use an Image as mask view, this results in a simple rectangle mask with the size of the image. The image content is not considered for masking.
I would like use an image as mask to apply a complex opacity mask, e.g. like the cloud in this image

A: The key here is to convert the image to use alpha depending on luminance - a perfect use for the luminanceToAlpha() modifier.
Result:

Code:
struct ContentView: View {
    var body: some View {
        Text("This is a red view with some text") // 1
            .padding(50)
            .background(Color.red)
            .mask { // 2
                Image("cloud") // 3
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 350)
                    .luminanceToAlpha() // 4
                    .fixedSize() // 5
            }
    }
}

How it works:

*

*Text is made, surrounded by padding, with a red background

*We mask the image after applying transformations

*The image is first resized to fit a 350px width

*The image is converted from grayscale to alpha

*The image is a fixed size, meaning it can't be influenced by the space given by the mask


text:
Q: Prove that if $a > b > 0, p > 0$, then $a^p > b^p$
Prove that if $a > b > 0, p > 0$, then $a^p > b^p.$

As I was reading baby Rudin, this fact was a step that Rudin skipped (Theorem 3.20a), but it is not obvious to me how to prove this.
Thanks in advance.
EDIT (relevant definitions and results from exercise 6, chapter 1):
EDIT 2 - Presume $b > 1$.
Let $r = m/n, n>0$, where $m$ and $n$ are integers. Then $b^r = (b^m)^{1/n}$.
It is proved that $b^{r+s} = b^rb^s$. If $x$ is real and if we let $$B(x) = \{  b^r | r \in \mathbb{Q}, r\leq x \}$$
then $b^r = sup  B(r)$ and we define $b^x = sup B(x) $ for any real $x$.
Also it is proved that $b^{r+s} = b^xb^y$, for real $x$ and $y$.
Hopefully that helps, my bad for not including it the first time around.

A: Let $a>b>0$. We go to prove that $a^{p}>b^{p}$ for any $p\in\mathbb{Q}\cap(0,\infty)$.
Firstly, we prove that $a^{n}>b^{n}$ for any $n\in\mathbb{N}$. This
can be proved easily by induction. For, the formula is obviously true
for $n=1$. Suppose that the formula is true for $n=k$, i.e., $a^{k}>b^{k}$,
then $a^{k+1}=a\cdot a^{k}>a\cdot b^{k}>b\cdot b^{k}=b^{k+1}$. By
mathematical induction, the formula is true for all $n\in\mathbb{N}$.
Next, we show that $a^{\frac{1}{n}}>b^{\frac{1}{n}}$ for any $n\in\mathbb{N}$
(Here, we assume that for any $x>0$, $n\in\mathbb{N}$, there exists
$y>0$ such that $y^{n}=x$. Note that $y$ can be shown unique and
is denoted by $x^{\frac{1}{n}}.$). Prove by contradiction, suppose
the contrary that there exists $n\in\mathbb{N}$ such that $a^{\frac{1}{n}}\leq b^{\frac{1}{n}}$.
If $a^{\frac{1}{n}}=b^{\frac{1}{n}},$ we have $a=\left(a^{\frac{1}{n}}\right)^{n}=\left(b^{\frac{1}{n}}\right)^{n}=b$,
which is a contradiction. If $a^{\frac{1}{n}}<b^{\frac{1}{n}}$, then
by the previous result, $\left(a^{\frac{1}{n}}\right)^{n}<\left(b^{\frac{1}{n}}\right)^{n}$.
That is, $a<b$, which is also a contradiction.
Finally, let $p\in\mathbb{Q}\cap(0,\infty)$. Choose $m,n\in\mathbb{N}$
such that $p=\frac{m}{n}$. Then by the first part, $a^{m}>b^{m}$.
By the second part, $\left(a^{m}\right)^{\frac{1}{n}}>\left(b^{m}\right)^{\frac{1}{n}}$.
Hence $a^{p}>b^{p}$.

A: We know that $f^\prime(x)=px^{p-1}$. And we know that both $\dfrac{1}{x}>0$ and $x^p>0$ so it follows that $x^{p-1}>0$. So $f^\prime(x)=px^{p-1}>0$.
So $f$ is increasing on the interval $(0,\infty)$.
So a power function $f(x)=x^p$ is an increasing function when $p>0$.
So by the definition of an increasing function on $(0,\infty)$ $a>b$ if and only if $a^p>b^p$.

A: You are using Rudin's "Principals of Mathematical Induction" and you are doing Chapter 1, Excercise 6.  Which relies very heavily on the Theorem 1.21 and the proof thereof  that;
For any $b > 1$ and $n \in \mathbb N$ there is a unique positive $c$ so that $c^n =b$.  We call such a $c:= b^{\frac 1n}$.
The proof makes use of the least upper bound property and the archimedian principal and the fact that for all $c < b$ then $c^n < b*c^{n-1} < b^2*c^{n-2} < ....< b^n$.  We then consider $C= \sup \{c|c^n < b\}$ and... the proof writes itself.
But HERE's the thing.  In the process of doing this we have established that for all $c < b$ than so that $d= c^n < b$ that $c < b^{\frac 1n} = \sup \{c|c^n < b\}$.  Thus for $d < b$ we have $c = d^{\frac 1n} < b^{\frac 1n}$.
And if that WASN't immediately clear, it'd have to be by contradiction:
If $d^{\frac 1n} \ge b^{\frac 1n}$ then $d=(d^{\frac 1n})^n \ge (b^{\frac 1n})^n = b$ which is a contradiction.
So if we show that it is consistent to define for $p =\frac mn$ that $b^p = (b^{\frac 1n})^m$ we would have $0 < a < b  \iff 0 < a^{\frac 1n} < b^{\frac 1n} \iff a^{\frac mn} < b^{\frac mn}$.
And it'd only take a line to extend that result to $a^x = \sup \{a^q|q< x; q\in \mathbb Q\}< \sup\{a^q|q< x; q\in \mathbb Q\} = b^x$.
Which is why Rudin "took it for granted".
====in recap  ==
For natural numbers it's clear by induction.
If $a^n > b^n > 0$ then $a^{n+1} =a^n*a > a^n*b > b^n*b = b^{n+1}$.
For $p = \frac 1n; n\in \mathbb N$ it's clear by contradiction.
If $a^{\frac 1n}\le b^{\frac 1n}$ we'd have $a = (a^{\frac 1n})^n \le (b^{\frac 1n})^n = b$.
So for rational $p = \frac nm; n,m\in \mathbb n$ then $a^p = (a^n)^{\frac 1m} > (b^n)^{\frac 1m} = b^p$.
ANd for any real $x>0$ we have $a^x = \sup\{a^q|q < x\} > \sup \{b^q|q < x\}$ [admittedly that step would need a sentence or two but it'd be straight forward] $= b^x$.

A: If $p\in \mathbb{N}$ induction mathematical.

A: Here is another potential route through this.
Since $a\gt b\gt 0$ we have $\frac ab\gt 1$ and we might be in a position to say that $\frac ab=1+r$ with $r\gt 0$ and $\left(\frac ab\right)^p=(1+r)^p\gt 1$.
For example we can show that $(1+r)^n\gt 1^m$ for integer $n, m$ so we can do this for $p$ a positive rational.


text:
Q: Fetch Genre name list which have songs in it I am fetching Genre list from media content Provider of android using CursorLoder class.
below is my cursor query to fetch the list of Genre.
 public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // currently filtering.
        Uri baseUri;
        baseUri = MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI;
        String[] STAR = { "*" };
        return new CursorLoader(getActivity(), baseUri, STAR, null, null, null );
    }

Now, i got all the genre list from the media content provider but the problem with the data i got. I also got the genre name which is created before but right now i don't have song in it.
I only want the genre that have songs in it, not the genre name that dont have songs in it.
Can anyone help me in that?
UPDATE
I can able to fetch all the Genre and its Song using below code...
private void getGenresList() {

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

        int index;
        long genreId;
        int count;
        Uri uri;
        Cursor genrecursor;
        Cursor tempcursor;
        String[] proj1 = {MediaStore.Audio.Genres.NAME, MediaStore.Audio.Genres._ID};
        String[] proj2={MediaStore.Audio.Media.DISPLAY_NAME};

         genrecursor=getActivity().getContentResolver().query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI,proj1,null, null, null);
         if(genrecursor.moveToFirst())
         {
             do{
                index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
                System.out.println("GENRE NAME: "+genrecursor.getString(index));
                System.out.println("======================================");

                index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID);
                genreId=Long.parseLong(genrecursor.getString(index));
                uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreId);

                tempcursor = getActivity().getContentResolver().query(uri, proj2, null,null,null);
                System.out.println("Total Songs: "+tempcursor.getCount());
                if(tempcursor.moveToFirst())
                {
                    do{
                        index=tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
                        System.out.println("    Song Name: "+tempcursor.getString(index));

                    }while(tempcursor.moveToNext());
                }
                System.out.println("======================================");
             }while(genrecursor.moveToNext());
         }

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

    }

But, i must have to use two query, one for fetching all the genre and second for filter data with the Genre which have songs. Even i would like to use that in the CursorLoader so i am wonder wonder about how to do that.
Hope you got proper idea what i want with this question.

A: It seems like there is no other method to achieve this so i have just do like below...
With below update i can able to get the Genre list which only have songs in it. The genre list which don't have songs are filtered out.
public Loader<Cursor> onCreateLoader(int id, Bundle args) {

        Uri baseUri;
        if (mCurFilter != null) {
            baseUri = Uri.withAppendedPath(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    Uri.encode(mCurFilter));
        } else {
            baseUri = MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI;
        }

        String[] STAR = { MediaStore.Audio.Genres._ID,
                MediaStore.Audio.Genres.NAME };

        String query = " _id in (select genre_id from audio_genres_map where audio_id in (select _id from audio_meta where is_music != 0))" ;

        return new CursorLoader(getActivity(),
                MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, STAR, query,
                null, null);

    }

In above code i have join the genre table with audio table. with this way i am able to fetch, whether that Genre have songs or not. So now i have only that genre which have songs in it.
Hope this will help others also.
Enjoy Coding... :)


text:
Q: Pass specific information to concrete classes in appropiate way I have question regarding passing by some information to my repositories classes. Currently I have two repositories, CsvRepository and SqlRepository. For both of them, I want to pass some information, currently there is only path to be passed for CsvRepository. As you can see I also have factory pattern class and GetRepository method to get specific object on demand. I do not think this is right place to pass that information from CsvRepository method because it's not the duty of factory method. Could you help me out where this should be passed correctly?
 public enum DataSource
    {
        SqlServer,
        Csv,
        Oracle
    }

    public interface IRepo
    {
    }

    public interface IRepository<T> : IRepo where T : class
    {
        IEnumerable<T> GetRecords();
    }

    public class RepositoryFactory
    {
         // here I would need to pass all information for all repositories - bad idea perhaps
         public static IRepo GetRepository(DataSource repositoryType)
         {
             IRepo repo;

             switch (repositoryType)
             {
                  case DataSource.Csv:
                     repo = new CsvRepository("path"); //perhaps path shouldn't be right passed right here - so where?
                     break;

                  case DataSource.SqlServer:
                     repo = new SqlRepository();
                     break;

                  default:
                     throw new ArgumentException("Invalid Repository Type");
             }

             return repo;
        }
    }

    public class CsvRepository : IRepository<InputData>
    {
          private string _path;

          public CsvRepository(string path)
          {
               _path = path;
          }

          public IEnumerable<IBasic> GetRecords()
          {
              return from line in File.ReadLines(_path)
                  select line.Split(',') into parts
                  where parts.Length == 3
                  select new InputData { Name = parts[0], X = Convert.ToInt32(parts[1]), Y = Convert.ToInt32(parts[2]) };
          }
    }

    // other repository
    public class OracleRepository : IRepository<InputData>
    {
        // to be implemented
    }

    class Form1
    {
         private void FetchData(DataSource repositoryType)
         {
              ClearListBox();

              var repository = RepositoryFactory.GetRepository(repositoryType);
              var people = repository.GetRecords();
         }

         private void CSVFetchButton_Click(object sender, RoutedEventArgs e)
         {
              FetchData(DataSource.Csv);
         }

    private void SQLFetchButton_Click(object sender, RoutedEventArgs e)
    {
        FetchData(DataSource.SqlServer);
    }

    public class InputData : IBasic
    {
        public string Name { get; set; }
        public int X { get; set; }
        public int Y { get; set; }
    }

public interface IBasic
{
}

A: Usually, when your factory needs parameters for concrete implementations - you split factories in two. One with additional parameters and one without it. One of good options is to define interface for factory and create two methods:
public interface IRepoFactory
{
    IRepo GetRepository(DataSource repositoryType);
    IRepo GetRepository(DataSource repositoryType, /*a ton of informations here*/);
}

On the other hand, I always prefer to split interfaces. Read bellow as to why.
BUT, lets first look at what kind of parameters you can pass.
Parameters binded to lifetime of IRepo instance, should be passed in Create method and usually inside constructor, there is no exceptions, for example if you have multiple SQL servers:
public interface IRepoFactory
{
    IRepo GetRepository(string connectionString); //you can specify here concrete SQL server
    IRepo GetTestRepository(string folder); //for example you want to unit test on different folders
}

Parameters binded to lifetime of IRepoFactory, should be passed in factory constructor, because they will be active during entire lifetime of factory (usually it is also lifetime of Application, because factories often used as singletons). For example, you have single SQL server, and don't care what repository is created and to where it is connected:
public interface IRepoFactory
{
    IRepo GetRepository(); //you don't care about SQL server at all
    IRepo GetTestRepository(); //you don't care where test environment allocated
}

public class MyRepoFactory : IRepoFactory
{
    public MyRepoFactory(string connectionString)
    {
       //...
    }

    //implementation
}

So, I split them, because of parameter lifetimes.
At one point you will clearly see, that CsvRepository don't care about SQL connection string but it care about path it is located at. These functionality created dependand on different things and these things have their own lifetimes and so should be split into different factories.
How to manage a ton of those interfaces? Well, factory pattern will not help with these. But IoC pattern will do, and I insist to read it because you can call it somewhat "mainstream" of production development, which has many aplications at testing/refactoring/dependencies management. Read more here.
As to your question, do these steps:

*

*Choose lifetime for you additional parameters

*Choose first or second or both approach described

*Split your factory in two, if you see they become too overloaded with functionality

*Use one of the two IoC pattern implementations to manage your lifetimes and dependencies of those parameters: Service Locator or Dependency Injection (I prefer DI, it is more strict approach)

EDIT realted to IoC usage:
Here is example of how it usually done in Ninject:
public interface IRepo { }
public interface IRepository<T> : IRepo where T : class {}

public interface ICsvRepo<T> : IRepository<T> where T : class { }
public interface ISqlRepo<T> : IRepository<T> where T : class { }
public interface IOracleRepo<T> : IRepository<T> where T : class { }

public interface IRepoX : IRepo { }

public interface ICsvSettings
{
    string Path { get; }
    string FileName { get; }
}

public interface ISqlSettings
{
    string ConnectionString { get; }
    string Username { get; }
    string Password { get; }
}

internal class CsvSettings : ICsvSettings
{
    public string Path { get; set; }
    public string FileName { get; set; }
}

internal class SqlSettings : ISqlSettings
{
    public string ConnectionString { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

internal class CsvRepo<T> : ICsvRepo<T> where T : class
{
    private readonly ICsvSettings _settings;
    public CsvRepo(ICsvSettings settings)
    {
        _settings = settings;
    }
}

internal class SqlRepo<T> : ISqlRepo<T> where T : class
{
    private readonly ISqlSettings _settings;
    private readonly IRepoX _repoX;

    public SqlRepo(ISqlSettings settings, IRepoX repoX)
    {
        _settings = settings;
        _repoX = repoX;
    }
}

internal class OracleRepo<T> : IOracleRepo<T> where T : class
{
    private readonly ISqlSettings _settings;
    private readonly IRepoX _repoX;

    public OracleRepo(ISqlSettings settings, IRepoX repoX)
    {
        _settings = settings;
        _repoX = repoX;
    }
}

internal class RepoX : IRepoX { }

public class RepoModule : NinjectModule
{
    private readonly string _username;
    private readonly string _password;
    public RepoModule(string username, string password)
    {
         _username = username;
         _password = password;
    }
    public override void Load()
    {
        Bind<ICsvSettings>().ToConstant(new CsvSettings
        {
            FileName = "foo",
            Path = "bar"
        }).InSingletonScope();

        Bind<ISqlSettings>().ToConstant(new SqlSettings
        {
            ConnectionString = "foo",
            Password = _password,
            Username = _username
        }).InSingletonScope();

        Bind<IRepoX>().To<RepoX>();

        Bind(typeof(ICsvRepo<>)).To(typeof(CsvRepo<>));
        Bind(typeof(ISqlRepo<>)).To(typeof(SqlRepo<>));
        Bind(typeof(IOracleRepo<>)).To(typeof(OracleRepo<>));
    }
}

And then in your application you do this:
class Program
{
    static void Main(string[] args)
    {
        var kernel = new StandardKernel(new RepoModule("foo", "bar"), /*some other modules here maybe?*/);

        //thousand of code lines later...

        var csvRepo = kernel.Get<ICsvRepo<MyEntity>>();
        var data = FetchData(csvRepo);

        var sqlRepo = kernel.Get<ISqlRepo<MyEntity>>();
        data = FetchData(sqlRepo);

        var oracleRepo = kernel.Get<IOracleRepo<MyEntity>>();
        data = FetchData(oracleRepo);
    }

    static T[] FetchData<T>(IRepository<T> repo)
    {
        throw new NotImplementedException();
    }
}

You can wrap it into factory if you want, but at this point it is not neccesary (you implemented factory on IoC container)

A: Using IOC would be ideal - inject all the repository types and let the container resolve their dependencies, but you could start simpler with a Settings class that contains all the App settings (implementing ISettingsSql, ISettingsCsv, ...) and pass it into your factory so that each repo can get its paths. –
e.g.
Constructor for CsvRespository:
  public CsvRepository(ISettingsCsv settings)
  {
       _path = settings.CsvPath;
  }

Constructor for SqlRepository:
  public SqlRepository(ISettingsSql settings)
  {
       _connectionString = settings.SqlConnectionString;
  }

Next, wrap all these up in an overall settings interface:
  public interface ISettings : ISettingsSql, ISettingsCsv, ...
  {
  }

And now you can implement:
  public class Settings : ISettings
  {
     public string CsvPath {get; set;}
     public string SqlConnectionString {get; set;}
     ...
  }

Create an instance of that class with all your settings in it:
  var settings = new Settings { CsvPath = "...", ... };

And now you can inject that into your factory where it can be used by the factory method:
 public class RepositoryFactory
 {
    ISettings settings;
    public RepositoryFactory (ISettings settings)
    {
       this.settings = settings;
    }

    ...

   public IRepo GetRepository(DataSource repositoryType)
   {
      ...
          return new CsvRepository(this.settings);
   }

The next step would be to use a container to register all repositories and then resolve them as a collection IEnumerable<IRepo> allRepos and change the factory to find the repo that can match the enum (expose the enum on each repo class) and use a loop or a dictionary. The switch statement can then go away.  When you do that, each repo will try to resolve its own ISettingsXXX dependency and so on.


text:
Q: python : getting into imbedded document I have a database "records" within it documents of the type:
{ ..., ..., "grades" : {"good": "40.0", "bad":"22.0"}}

*

*I need to get into the document and define a variable as the sum of the "good" and "bad" grades.

*I don't know how to get inside the imbedded doc,

I tried :
for i in records:
    variable = i['grade.good']

But that doesn't seem to work.
Secondly, the grades are strings, and I need to convert them to integers/
Again, tried
total = int(i['grade.good']) + int(i['grade.bad'])

But that it also wrong.
note that my strings are floating points
Help much appreciated!!

A: instead of i['grade.good'] try i['grade']['good']
retrieve data from dictionary properly
In [11]: d = {"grades" : {"good": "40", "bad":"22"}}

In [12]: d['grades']['good']
Out[12]: '40'

In [13]: total= int(d['grades']['good']) + int(d['grades']['bad'])

In [14]: total
Out[14]: 62

for float number
In [21]: d = {"grades" : {"good": "40.0", "bad":"22.0"}}

In [22]: print float(d['grades']['good']) + float(d['grades']['bad'])
62.0

A: The most elegant solution would be:
good_grades=[grades['good'] for grades in records]

That will return an array with all of your good grades, do the same thing for bad.
Alternatively, you could simply change this line:
variable = i['grade']['good']


text:
Q: Interface method overloading Having two interface and a class. Please see the below code
public interface IBook {
bool Initilize();
}
public interface IGoodBook : IBook
{
string Pages {get; set;}
}
public class Books : IGoodBook{

public string Pages {get; set;}

public bool Initilize(){
    Console.WriteLine("This is Initilize")
}
}

I want to pass few parameters / arguments into class Books Initilize method, how can I do this without modifying interface IBook Initilize() method.
Please advise all posibile option in this regards,

A: public interface IBook {
bool Initilize();
}
public interface IGoodBook : IBook
{
string Pages {get; set;}
}
public class Books : IGoodBook{

public string Pages {get; set;}

public bool Initilize(){
    Console.WriteLine("This is Initilize")
// you need to return bool in your first message still
}

public bool Initilize(string test)
{
  Console.WriteLine("paramter passed" + test);
  return true;
}
}


text:
Q: Make a WebView flutter app with different urls everytime using python I want to create a python form with a textfiled and a button where a user will enter his/her link and it will create a webview flutter apk for that url. I want advice from the community if it is possible or not. If it is possible, please let me know how can I achieve it.

A: Maybe you can achieve this via using a remote server. You can create a connection between your python program and the server, and you can create the apk file in server and send it to your python program.


text:
Q: Print LayoutRoot and Fit To Page I am using Silverlight 5 and VB.Net.
My LayoutRoot is Width=1300.
When I print to paper or an .xps file I am losing the right hand side of the output.
How can I force Silverlight to fit to page?
My code is below. Thanks,
JT
Imports System.Windows.Printing

Partial Public Class Page3
    Inherits Page
    Public WithEvents pd As New PrintDocument()

Public Sub New()
        InitializeComponent()
        pd = New PrintDocument()

Private Sub Button1_Click(sender As Object, ByVal e As RoutedEventArgs) Handles Button1.Click
        pd.Print("People Framework")
    End Sub

    Private Sub pd_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs) Handles pd.PrintPage
        e.PageVisual = LayoutRoot
    End Sub

A: You need to use the PrintableArea parameter to get your page size first.
Look at this blog post silverlight-printing-fit-to-page for a detailed answer. It's for C# but the principle is the same.


text:
Q: How to change font color of Android status bar? I've been trying to change the font color of the status bar using Xamarin (where the Battery, Signal and Clock is)...
Can somebody advice me how to do this?
Thank you

A: I'm not sure what API level your trying to target, but if you can use API 23 specific stuff, you can add the following to your AppTheme styles.xml:
<item name="android:statusBarColor">@color/colorPrimaryDark</item>
<item name="android:windowLightStatusBar">true</item>

when android:windowLightStatusBar is set to true, status bar text color will be able to be seen when the status bar color is white, and vice-versa when android:windowLightStatusBar is set to false, status bar text color will be designed to be seen when the status bar color is dark.
Example:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <!-- Status bar stuff. -->
    <item name="android:statusBarColor">@color/colorPrimaryDark</item>
    <item name="android:windowLightStatusBar">true</item>
</style>

A: if (Build.VERSION.SdkInt > Android.OS.BuildVersionCodes.M)
{
        var activity = Activity; //your activity ref..
        var needWhite = true; //your goal

        // Fetch the current flags.
        var flags = activity.Window.DecorView.SystemUiVisibility;
        // Update the SystemUiVisibility dependening on whether we want a Light or Dark theme.
        if (needWhite)
        {
            activity.Window.DecorView.SystemUiVisibility = flags | (StatusBarVisibility)SystemUiFlags.LightNavigationBar;
        }
        else
        {
            activity.Window.DecorView.SystemUiVisibility = flags ^ (StatusBarVisibility)SystemUiFlags.LightNavigationBar;
        }
}

A: You can change it by changing "colorPrimaryDark" attiribute of "color.xml" file where under android native project.


text:
Q: Creating A Dynamic Page with Local TypeScript Data File - Next.js I'm working on an Event App. I have my event Data stored in my TypeScript file. I'm trying to create a dynamic page for each events once its clicked. I tried creating a [slug].tsx file, but the data is not fetched / getting error.
My codes:
../data/Events.tsx
export const EVENT_DETAILS = [
  {
    id: 0,
    title:
      'test1',
    image: 'event-card-bg',
    industries: ['test', 'test'],
    details: [
      {
        title: '5th - 6th',
        value: 'May, 2022',
        icon: <BiTime style={{ width: '24px', height: '24px' }} />,
      },
      {
        title: 'Event Type',
        value: 'In-Person',
        icon: <BsPeople style={{ width: '24px', height: '24px' }} />,
      },
      {
        title: 'Venue',
        value: 'test Hotel',
        icon: <BiHome style={{ width: '24px', height: '24px' }} />,
      },
      {
        title: 'Location',
        value: 'test location',
        icon: <GoLocation style={{ width: '24px', height: '24px' }} />,
      },
    ],
  },
  {
    id: 1,
    title:
      'test',
    image: 'event-card-bg',
    industries: ['test', 'test'],
    details: [
      {
        title: '5th - 6th',
        value: 'May, 2022',
        icon: <BiTime style={{ width: '24px', height: '24px' }} />,
      },
      {
        title: 'Event Type',
        value: 'In-Person',
        icon: <BsPeople style={{ width: '24px', height: '24px' }} />,
      },
      {
        title: 'Venue',
        value: 'test Hotel',
        icon: <BiHome style={{ width: '24px', height: '24px' }} />,
      },
      {
        title: 'Location',
        value: 'test location',
        icon: <GoLocation style={{ width: '24px', height: '24px' }} />,
      },
    ],
  },
]

../event/EventsList.tsx
import React from 'react';
import { Col, Container, Row } from 'react-bootstrap';
import styled, { css } from 'styled-components';
import { EVENT_DETAILS } from '../../data/events';
import { BREAKPOINTS, mediaBreakpointDown } from '../../theme/breakpoints';
import EventCard from './EventCard';

const StyledEventList = styled.section`
  padding: 40px 100px;
  background-color: ${({ theme }) => theme.colors.whiteSmoke};
  ${mediaBreakpointDown(
    BREAKPOINTS.md,
    css`
      padding: 40px 0;
    `
  )}
`;

const EventList: React.FC = () => {
  return (
    <StyledEventList>
      <Container>
        <Row>
          {EVENT_DETAILS.map((event) => (
            <Col key={event.id} xs={12} md={6} lg={4} className="my-3">
              <EventCard
                id={event.id}
                title={event.title}
                image={event.image}
                industries={event.industries}
                details={event.details}
              />
            </Col>
          ))}
        </Row>
      </Container>
    </StyledEventList>
  );
};

export default EventList;

export async function getStaticProps() {
  const events = await fetch(EVENT_DETAILS).then(res => res.json());
  console.log(events)
  return {
    props: {
      events
    }
  }
}

But nothing got returned on more like it's not compiling and i can't generate my [slug].js file


text:
Q: Maximize active window in terminator I am on xenial and using terminator 0.98.
When I do ctrl + shift + i, terminator opens up a new window.
Sometimes its convenient to maximize the window that was opened.
Is there a keyboard shortcut to do that?
I have tried ctrl + shift + x and nothing happens.
Pardon me if I am too naive here.

A: Press Ctrl + Win + Up
On my standard 16.04 this shortcut allows me to maximize the active window.
There is also:
Ctrl + Win + Down to restore/minimize windows.
Ctrl + Win + Left or Right to dock a window to the left/right half of the screen.

A: To toggle the current of multiple terminals within Terminator between maximized and restored state, use Ctrl + Shift + x.
To use the default window manager keybinding to maximize your Terminator window, see Forivin's answer on this question.


text:
Q:  tag in HTML5 does not show until data is fetched from the database In my HTML5 interface developed on NetBeans 7.4, the interface is designed so that the db data is displayed inside  tags for further editing, like this:
<td>
<input name="lname" value="<c:out value = '${row.lname}'/>">
</td>

The problem is that the  tags are not displayed until the data is fetched. Can this be fixed? Thank you.

A: No, the servlet container / application server needs to execute the query and output the name before it outputs the text, that's just how it works. You could maybe do something with javascript and have it fetch it somehow, i'm not really sure though.

A: Just set type="text"

After specifying the type it will be displayed and if no data is there then it will be blank


text:
Q: AutoMapper: What is the difference between MapFrom and ResolveUsing? Ignoring the ResolveUsing overloads that take an IValueResolver, and looking only at these 2 methods:
void ResolveUsing(Func<TSource, object> resolver);
void MapFrom<TMember>(Expression<Func<TSource, TMember>> sourceMember);

The main difference between these 2 seems to be that ResolveUsing takes a Func<TSource, object>, whereas MapFrom takes an Expression<Func<TSource, TMember>>.
However in client code that actually uses one of these methods with a lambda expression, they seem to be interchangeable:
Mapper.CreateMap<SourceType, DestType>() // uses ResolveUsing
   .ForMember(d => d.DestPropX, o => o.ResolveUsing(s => s.SourcePropY));

Mapper.CreateMap<SourceType, DestType>() // uses MapFrom
   .ForMember(d => d.DestPropX, o => o.MapFrom(s => s.SourcePropY));

So what ultimately is the difference between the above 2 choices? Is one faster than the other? Is one a better choice than the other and if so, when / why?

A: MapFrom has a few extra smarts. For example (from the mailing list):

In MapFrom, I try to be smart about digging in to child properties (much like the normal flattening does). MapFrom is an attempt to mimic flattening, with an added bit of allowing redirection.
  ResolveUsing doesn't have this behavior.

I'm not sure if this is fully documented anywhere (apart from in the source code).

A: In the past I had a long email exchange on the mailing list with the author of Automapper. MapFrom will do null checks all the way trough the expression:

So you can do opt => opt.MapFrom(src =>
  src.SomeProp.Way.Down.Here.Somewhere) and each level will get checked
  for nulls (as it already does for flattening).

A: I just did some benchmarks using the new C# 6 null conditional operator ?.
Consider the following scenario: class A has a child class B, which has a child C, whose Name property we want to flatten into a DTO. I tested two variants:
// using mapfrom
CreateMap<MapFromA, MapFromADto>()
    .ForMember(dto => dto.Name, o => o.MapFrom(a => a.B.C.Name));

// using resolveusing with elvis
CreateMap<ResolveUsingX, ResolveUsingXDto>()
    .ForMember(dto => dto.Name, o => o.ResolveUsing(x => x.Y?.Z?.Name));

I called _mapper.Map<ResolveUsingXDto>(x); or _mapper.Map<MapFromADto>(a); for 1000 different ResolveUsingX x and MapFromA a and took the time using a System.Diagnostics.StopWatch. Here are my results:
Distinct elements per batch: 1000; # batches for average: 25

A->B->C.Name, C is never null.
MapForm - average time taken for 1000x: 5527,84 ticks = 1,44 ms.
ResolveUsing - average time taken for 1000x: 5479,76 ticks =  1,4 ms.

A->B->C.Name, C is null 1/3 of the time.
MapForm - average time taken for 1000x: 72924,4 ticks = 27,44 ms.
ResolveUsing - average time taken for 1000x: 5351,2 ticks =  1,48 ms.

A->B->C.Name, C is null 1/2 of the time.
MapForm - average time taken for 1000x: 107016,92 ticks = 40,52 ms.
ResolveUsing - average time taken for 1000x: 5835,32 ticks =  1,56 ms.

A->B->C.Name, C is null 2/3 of the time.
MapForm - average time taken for 1000x: 141437,96 ticks = 53,64 ms.
ResolveUsing - average time taken for 1000x: 5789,72 ticks =  1,56 ms.

MapFrom has to catch NullReferenceExceptions, which is slower than ResolveUsing with the elvis operator ?.

A: Although in many situations either can be used, based on official documentation there is a difference when it comes to LINQ projections. Detailed explanation can be found here.
Long story short: use MapFrom whenever possible.

A: According to the source code, ResolveUsing is more complicated. The source value can be any object; therefore, you can use any value you want to fill the destination member, such as int or bool that you get by "Resolving" the given object. However, MapFrom only uses member to map from.
/// <summary>
/// Resolve destination member using a custom value resolver callback. Used instead of MapFrom when not simply redirecting a source member
/// This method cannot be used in conjunction with LINQ query projection
/// </summary>
/// <param name="resolver">Callback function to resolve against source type</param>
void ResolveUsing(Func<TSource, object> resolver);

/// <summary>
/// Specify the source member to map from. Can only reference a member on the <typeparamref name="TSource"/> type
/// This method can be used in mapping to LINQ query projections, while ResolveUsing cannot.
/// Any null reference exceptions in this expression will be ignored (similar to flattening behavior)
/// </summary>
/// <typeparam name="TMember">Member type of the source member to use</typeparam>
/// <param name="sourceMember">Expression referencing the source member to map against</param>
void MapFrom<TMember>(Expression<Func<TSource, TMember>> sourceMember);


text:
Q: Flat Points in Irreducible Algebraic Varieties I am trying to understand the paper "Algebraic Methods in Discrete Analogs of the Kakeya Problem" by L. Guth and N. H. Katz.  This paper contains the following lemma:
Let $S$ be the set of points in $\mathbb{R}^3$ on which the polynomial $p$ vanishes, and let $a$ be a regular point of $S$.  Suppose that $S$ contains 3 distinct lines all of which intersect at $a$.  Then $a$ is a flat point.
I'm having a hard time picturing the situation in this lemma.  Can someone give me examples (other than a plane) of irreducible algebraic varieties that contain three distinct lines that meet at a point?

A: $ X = V(z^2-x^2-y^2)$, known as a cone. (See the picture.) However, for any point $p \in X$ other than $0$ there is only one line going through $p$ and contained in $X$.

Indeed, the plane is the only surface which contains three lines going through each of its points.
In higher dimensions, there are more varieties with this property. (For example, you can consider the product $X \times \mathbb{A}^{2}_{\mathbb{C}}$ for an arbitrary $X$.)
If you want a nonsingular example, consider the surface $X$ defined by $z = xy(x-y)$. You probably can't visualise this, but algebraically it is easy to see that there are three lines on $X$ going through $0$. They are the lines defined by $z = x = 0$, $z = y = 0$ and $z = x-y = 0$.
Let me explain how I came up with this example. First, let us look at the "saddle surface" $S = V(z - xy)$. You have probably already seen $S$ at some point. If not, I hope you can find a good picture online somewhere, or maybe visualise it yourself. The point is, that contained in $S$ we find the $x$-axis and the $y$-axis. The reason is that, when we look at $S$ only in the xy-plane which is defined by $z = 0$ the defining equation reduces to $xy = 0$, which corresponds to the two coordinate axes. Now when we want to have three lines on our surface, we can just start with the equation $xy(x-y) = 0$, which describes the coordinate axes and a diagonal line, and then add a parameter $z$ to get $V(xy(x-y) - z) \subseteq \mathbb{R}^{3}$.
If we push this trick further, we can get an arbitrary number of lines in our surface, and I guess it starts looking like this:


text:
Q: scheduled SSIS package creating excel file with date as filename I need some feedback on what is the best way to do what I want to do, allow me to situate.
I have a huge database which receives new inputs constantly. Now I need to have an excel file which shows all the columns of inputs of the past day. So I thought the best way to do this is to use SSIS packages. I never really used SSIS that much so I'm not very sure how wide the possibilities are. So at the moment I'm only capable of creating an SSIS package of ALL my inputs. But I need a new file every day, but also where the filename has the data in it, because the old files will not be deleted etc. So I need to be able to create an .xls file with the date in the filename. Is there an easy way to do this?
I was also wondering if it's possible to automaticly modify the layout for this excel file, especially the column widths, since they are all the default width, which is not very usefull for clients.
I heard it's also possible to create SSIS packages with visual studio, would this make a difference or are the possibilities the same (Keep in mind that I'm a c# programmer)?
Thanks a lot

A: It is possible to create SSIS packages through Visual Studio. When click on new project in Visual Studio, select Business Intelligence Projects->Integration Services Project.
Though different from your situation (i.e., Excel File output), in my situation, for a flat .TXT file output, I had the date as part of flat file name. For this, in my Flat File Connection Manager, in Properties-Expressions->Connection String (Property), I put in the following expression. Similar approach could work in your case as well, specially if you go for a .csv file output.
"[Folder Destination]_" +
(DT_WSTR,4)YEAR(GETDATE()) +
RIGHT("0" + DT_WSTR,2)MONTH(GETDATE()),2) +
RIGHT("0" + (DT_WSTR,2)DAY(GETDATE()),2) +
RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()),2) + ".TXT"

A: @Kashif - Thank you!!
One small typo in your post.
Notice missing open parenthesis on 3rd line:
RIGHT("0" + DT_WSTR,2)MONTH(GETDATE()),2) +

Needs to be:
RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()),2) +

All together:
"[Folder Destination]_" +
(DT_WSTR,4)YEAR(GETDATE()) +
RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()),2) +
RIGHT("0" + (DT_WSTR,2)DAY(GETDATE()),2) +
RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()),2) + ".TXT"

Also, just a note for anyone finding this post, you can replace "[Folder Destination]_" in the above with a path like so:
"C:\\Some\\Path\\to\\File.txt"

Notice the double backslash!!


text:
Q: Easier way to edit multiple HTML files in Xcode? I have multiple HTML files in Xcode that I want to replace below:
<style type="text/css">
with
<style type="text/css">
        @font-face {
             font-family: MyFont;
             src: url('file:///android_asset/fonts/AnmolUniBani.ttf')
        }
        body {
             font-family: MyFont;
        }

Please suggest me if there is any easier way to edit this in Xcode. Perhaps if I can do contains and replace.

A: If you put them in a project together, you should be able to a global search and replace. I believe the keyboard shortcut is Shift-Option-Cmd-F by default.