text:
Q: Is there a way to break a single child element out of a flexible box? The scenario: I have a div#wrapper element with the following css:
div#wrapper {
    display: box;
    box-orient: horizontal;
    width: 100%;
}

This wrapper contains three child <section> elements that, for the sake of clarity, we'll call Sections A, B, and C. So that leaves me with something like this:

Beautiful. Here's the catch: I'm working on media queries now and need to alter this layout when < 800px. Specifically, I need to move Section B below Sections A and C and make it full width. Here's a graphic to help explain:

The question: Is it possible to break a single child element out of its flexible box and alter the layout in this way?

A: The flexbox specs are constantly changing, with the current recommendiation you could use a flex container with row wrapping, set the sections width so that only two of them fit in the wrapper, and use order to put section b at the end:
http://jsfiddle.net/LYnRf/ (tested with Chrome 22 on Windows)


text:
Q: 'System.Data.DataRow' does not contain a public definition for 'GetEnumerator' I am trying to make a conection to a database  that I made on sqlservermanagement
I have make a console application on visual studio 2012
I have this statement
  foreach (DataRow pRow in persoaneSet.Tables["persoane"].Rows)
  {
    Console.Write("\t{0}\t{1}\t{2}", pRow["nrcrt"],pRow["nume"],pRow["codc"]);
    foreach (DataRow cRow in pRow.GetParentRow(relPersCrt)) // **here is the error**
    {
        Console.WriteLine("\t{0}\t{1}\t{2}", cRow["autor"],cRow["titlu"],cRow["cota"]);
    }
  }

Here I have to conect table one to table 2 from my database and here table 1 and I had made like my teacher but unfortunately i recive Error

foreach statement cannot operate on variables of type 'System.Data.DataRow' because 'System.Data.DataRow' does not contain a public definition for 'GetEnumerator'

What must I do here ?
The example of teacher it's working but not mine

A: You don't need foreach as there is only one parent row. Try:
foreach (DataRow pRow in persoaneSet.Tables["persoane"].Rows)
{
    Console.Write("\t{0}\t{1}\t{2}", pRow["nrcrt"],pRow["nume"],pRow["codc"]);

    DataRow cRow = pRow.GetParentRow(relPersCrt);
    Console.WriteLine("\t{0}\t{1}\t{2}", cRow["autor"],cRow["titlu"],cRow["cota"]);
}

Also, you should consider adding extra checks as your code is very prone to unhandled exceptions.

A: You can only use foreach with something which implements the IEnumerable interface. Basically you can only iterate over a collection of things, not a single thing. Your first foreach iterates over a collection of rows, with the second one you're trying to iterate over a single row.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unidirectional or bidirectional relationships in JPA?
Possible Duplicate:
What is the difference between Unidirectional and Bidirectional associations?

Under which circumstances or which criteria should I follow in order to choose between unidirectional and bidirectional relationships in JPA?


text:
Q: Azure KeyVault: How to add Spring properties with hypehen as secrets I have below in my application.properties file.
spring.jpa.show-sql=true

I have Azure KeyVault. All the properties are saved in this KeyVault. But the problem is, If I add the properties which has  hyphen (-), it won't be working as expected.
In KeyVault secret name I am replacing dots with hyphen. When I have hyphens what do I need to do ? Do I need to replace it ?

A: As I think, you can create a list and set the application.properties name as the value, when you store them in the key vault, you can set the name with value that replaces the hyphen into dots, when you want to use the application.properties, they are also in the list, you just need to quote the value with the name that replaced the hyphen into dots from the key vault.
The code will like this:
variable "list_var" {
  type = "list"
  default = ["spring.jpa.show-sql"]
}

data "azurerm_key_vault" "test" {
  name = "azureCommonKeyvault"
  resource_group_name = "charles"
}

data "azurerm_key_vault_secret" "test" {
  name = "${replace(var.list_var[0], ".", "-")}"
  key_vault_id = "${data.azurerm_key_vault.test.id}"
}

output "var_list" {
  value = "${data.azurerm_key_vault_secret.test.value}"
}

The output here:

This is just a possible solution for you. If you need more help or ideas, please let me know.


text:
Q: woocommerce related products by specific categories I am looking for a way to alter the related products functionality to relate one category of products with another. For example:
I have 4 categories: Spoons, Cups, Bowls, Straws.
When you select a product in spoons, I want the related products to only display things from the Bowls Categories.
And when you select Cups I want only items from Straws to show.
I have tried using tags, but I have tens of thousands of products to go through and that would be a nightmare. I have also tried other plugins including WP Related Items (WRI) by WebshopLogic but it does not offer this feature.
ANY help on how to about tackling this issue is greatly appreciated.
I probably have to write my own plugin to do this but I dont have a lot of experience doing that.

A: I think the following procedure will help you get your job done.
When you select a product in spoons category, you should know its 'id' (how to find category ID).
Let's assume for the following that Spoons ID is '12' and Bowls ID is '13'.
You should make a function and pass a parameter. Here the parameter is your current related ID, like '12'. This function would return your related products based on alter category.
function get_related_posts( $relatedID ) {
    switch ( $relatedID ) {
        case "12":
            $id = 13;
            break;
        default:
            $id = 13;
    }
    $query = new WP_Query ( array (
        'post_type' => 'product',
        'tax_query' => array(
            array(
                'taxonomy' => 'your_taxonomy_name',
                'field'    => 'id',
                'terms'    => $id,
            ),
        ),
    ) );
    if ( $query->have_posts () ) {
        while ( $query->have_posts () ) {
            $query->the_post ();
            // "Do your html..... and return it."
        }
        wp_reset_postdata ();
        return "Your Html";
    } else {
        return "Nothing Found";
    }
}

And in your template file you can call this function, e.g. in category page place this code:
echo get_related_posts( 12 );

I think this is the basics. You can find it at WP_Query Codex.
Hope it works for you. I haven't tested it for stability.


text:
Q: Java help reading from a file i have a section of code i just dont know what to do with.  it is supposed to show a dialog box to select a file and when the file is selected it outputs the results in a histograph.  i have everything working except i can not figure out what variable i need to put as text2.
private int[] countLetters2()
 {
  // Count for 26 letters
  int[] count = new int[26];

  //get contents from file
  chooser.showOpenDialog(null);
  File f = chooser.getSelectedFile();

  try
  {
   FileReader fr = new FileReader(f);
   BufferedReader br = new BufferedReader(fr);
   String s;
   while((s = br.readLine()) != null)
   {
    System.out.println(s);   <------simply to see if the reader and buffer were working

   }
  }
  catch(IOException g) {}

  String text2 = ; <------------------------------------this is the problem

  //converts every letter to uppercase
  text2 = text2.toUpperCase();

  //Count occurrence of each letter (case insensitive)
  for (int i = 0; i < text2.length(); i++)
  {
   char character = text2.charAt(i);

   if ((character >= 'A') && (character <= 'Z'))
   {
    count[(int)character - 65]++; // The ASCII for 'A' is 65
   }
  }
  return count; // Return the count array

A: simply collect to your text2 variable inside your while loop.
         String text2 = "";
            try { FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String s="" while((s = br.readLine()) != null) {
text2+=s;
ystem.out.println(s);

            } } catch(IOException g) {}

OR
String s = "";
            try { FileReader fr = new FileReader(f);
            BufferedReader br = new BufferedReader(fr);
            String tmp;
            while((tmp = br.readLine()) != null) {
                System.out.println(s);
                s += tmp;
            } } catch(IOException g) {}

            text2=tmp;

A: Move the loop that counts characgters into the loop where you print lines. Something like
private int[] countLetters2()
 {
  // Count for 26 letters
  int[] count = new int[26];

  //get contents from file
  chooser.showOpenDialog(null);
  File f = chooser.getSelectedFile();

  try
  {
   FileReader fr = new FileReader(f);
   BufferedReader br = new BufferedReader(fr);
   String s;
   while((s = br.readLine()) != null)
   {
    System.out.println(s);
    //converts every letter to uppercase
    String text2 = s.toUpperCase();

    //Count occurrence of each letter (case insensitive)
    for (int i = 0; i < text2.length(); i++)
    {
       char character = text2.charAt(i);

       if ((character >= 'A') && (character <= 'Z'))
       {
        count[(int)character - 65]++; // The ASCII for 'A' is 65
       }
    }
   }
  }
  catch(IOException g) {}

  return count;
 }

A: I think it makes little sense to use a BufferedReader to go through the file line by line and then go through each line character by character. That is unnecessary complicated and inefficient, given that you basically just want to iterate over all characters: this is exactly the functionality a Reader gives  you in the first place.
You could greatly simplify your routine like so:
    [...]

    BufferedReader br = new BufferedReader(fr);
    for (int c; (c = br.read()) > -1;) {
        char character = Character.toUpperCase((char) c);

        if ((character >= 'A') && (character <= 'Z')) {
            count[character - 'A']++;
        }
    }
} catch (IOException g) { /* this is no good */ }

return count;

This way you get rid of text2 altogether, your code is shorter, and your program will run faster (if measurable) because the unnecessary construction of a String is dropped.
P.S.: An unrelated note: make sure you handle the case in which the user clicks "Cancel" in the file chooser dialog.
P.P.S.: Could the user inadvertenly select a directory instead of a proper file in your program? What would happen then?


text:
Q: How to make user created function from GUI into a matlab function that accepts parameters using Symbolic Toolbox I am making a GUI where it needs to get the function that the user has entered in an editText and then plot it.
If the user enters x .* sin(x)+13 then I must make that into a function that receives the values of x and then plot it and I have to use the sym from symbolic toolbox.

A: You can convert a string to an anonymous function using str2func. You will need to add the @(x) 'prefix' to let function know that x is an input:
fun_str = 'x.*sin(x)+13';
fun = str2func(['@(x)' fun_str]);

x = 0:0.1:10;
y = fun(x)

plot(x,y)


text:
Q: Using AND and OR in a where clause I'm having a hard time getting the correct results with this where clause.  I know it is a paraenthesis issue.  Any suggestions?
WHERE a.EVENT_DATE Between &trend_dt  And &enddate
AND a.INDICATOR Not In ('INQUIRY (NOS)','PCC')
And a.INDICATOR2 Not In ('CAT-NA','INQUIRY (NOS)')
And d.ACTIVE In ('C','F')
And d.ARCHIVE_STATUS in ('N','Y')
Or (d.ARCHIVE_STATUS Is Null)

Thanks!
The problem with the results is that the Indicator 2 field is sometimes blank and it is only returning records where there is something in the Indictator 2 field.
This is the query:
PROC SQL;
CREATE TABLE COMPLAINT_DATA_0 as
SELECT
a.EVENT_DATE,
a.INDICATOR,
a.INDICATOR2,
a.COMMITTEE_ACTION AS REVIEW_TYPE,
a.LEVEL_OF_EXCEPTION AS METHOD_RECD,
a.REFER_TO AS PLAN_NTWK,
b.DESCRIPTION AS SubCategory,
d.CROSSREF2 AS ConProvID,
d.LAST_NAME AS Provider,
a.MED_REC_NO AS MbrID,
a.CONFIRMED_BY AS IndProvID,
a.CODE_15 AS Severity,
MAX(c.INQUIRY_BODY) AS MaxProcStep,
e.Notes,
e.Notes2,
FROM VIPDBA.QA_PEER AS a LEFT JOIN VIPDBA.SYS_LOOKUPS AS b
ON a.INDICATOR2=b.CODE
LEFT JOIN VIPDBA.QA_PEER_INQUIRY AS c
     ON a.LOOKUP_KEY=c.LOOKUP_KEY AND
a.MED_REC_NO=c.MED_REC_NO
LEFT JOIN VIPDBA.MASTER_CRED AS d
    ON a.LOOKUP_KEY=d.LOOKUP_KEY
LEFT JOIN Complaint_Notes AS e
    ON a.LOOKUP_KEY=e.LOOKUP_KEY AND
a.MED_REC_NO=e.MbrID
WHERE a.EVENT_DATE Between &trend_dt  And &enddate
    AND a.INDICATOR Not In ('INQUIRY (NOS)','PCC')
    And a.INDICATOR2 Not In ('CAT-NA','INQUIRY (NOS)')
    And d.ACTIVE In ('C','F')
    And
        ( d.ARCHIVE_STATUS IN ('N','Y')
        OR d.ARCHIVE_STATUS is null)
GROUP a.EVENT_DATE,
a.INDICATOR,
a.INDICATOR2,
b.DESCRIPTION,
d.CROSSREF2,
d.LAST_NAME,
a.MED_REC_NO,
a.CONFIRMED_BY,
a.CODE_15,
e.Notes,
e.Notes2,
d.archive_status,
d.active
ORDER BY
a.EVENT_DATE,
a.INDICATOR2,
b.DESCRIPTION,
d.CROSSREF2,
d.LAST_NAME

;
   run;

A: I think you are looking for this:
WHERE a.EVENT_DATE Between &trend_dt  And &enddate
AND a.INDICATOR Not In ('INQUIRY (NOS)','PCC')
And a.INDICATOR2 Not In ('CAT-NA','INQUIRY (NOS)')
And d.ACTIVE In ('C','F')
And ( d.ARCHIVE_STATUS in ('N','Y') Or d.ARCHIVE_STATUS Is Null )

Use parenthesis to group logic together.

A: A trick to avoid the checking-for NULL (and thus avoiding the need for an OR ...) is to transform the NULL to a comparable value, like in:
WHERE a.EVENT_DATE BETWEEN &trend_dt AND &enddate
AND a.INDICATOR NOT IN ('INQUIRY (NOS)','PCC')
AND a.INDICATOR2 NOT IN ('CAT-NA','INQUIRY (NOS)')
AND d.ACTIVE IN ('C','F')
AND COALESCE(d.ARCHIVE_STATUS, 'N') IN ('N','Y')
   ;

A: Or you can even avoid using OR :)
WHERE a.EVENT_DATE Between &trend_dt  And &enddate
AND a.INDICATOR Not In ('INQUIRY (NOS)','PCC')
And a.INDICATOR2 Not In ('CAT-NA','INQUIRY (NOS)')
And d.ACTIVE In ('C','F')
And COALESCE(d.ARCHIVE_STATUS,'-1') in ('N','Y','-1')

A: Is it that you need to see results where d.ARCHIVE_STATUS in ('N','Y')
Or (d.ARCHIVE_STATUS Is Null) if so, you will probably just need to change it to look like this
WHERE a.EVENT_DATE Between &trend_dt  And &enddate
AND a.INDICATOR Not In ('INQUIRY (NOS)','PCC')
And a.INDICATOR2 Not In ('CAT-NA','INQUIRY (NOS)')
And d.ACTIVE In ('C','F')
And (
      d.ARCHIVE_STATUS in ('N','Y')
      Or
      d.ARCHIVE_STATUS Is Null
    )

This way it will only evaluate d.ARCHIVE_STATUS in ('N','Y') against d.ARCHIVE_STATUS Is Null


text:
Q: Problem with setting raspberry pi3 static ip My raspberry is running Ubuntu mate 16.04.2 . When ever I try to set the IP address for my pi by editing /etc/network/interfaces, my WiFi connection crashes. no matter how I tried to get my connection back there is no use, until I get /etc/network/interfaces to its default state.
Any solution?

A: I'm not sure how much this will help, but here goes.
This is probably happening because the router you are using is configured to set the IPs of all the devices connected to it. And you manually setting the IP is causing the wifi connection to go haywire.
Why do you even want to set your own ip for the pi? Let the router configure the IP for you.


text:
Q: Find matching strings in table column Oracle 10g I am trying to search a varchar2 column in a table for matching strings using the value in another column. The column being searched allows free form text and allows words and numbers of different lengths. I want to find a string that is not part of a larger string of text and numbers.
Example: 1234a should match "Invoice #1234a" but not "Invoice #1234a567"
Steps Taken:
I have tried Regexp_Like(table2.Searched_Field,table1.Invoice) but get many false hits when the invoice number has a number sequence that can be found in other invoice numbers.

A: Suggestions:

*

*Match only at end:
REGEXP_LIKE(table2.Searched_Field, table1.Invoice || '$')

*Match exactly:
table2.Searched_Field = 'Invoice #' || table1.Invoice

*Match only at end with LIKE:
table2.Searched_Field LIKE '%' || table1.Invoice


text:
Q: Process.Start with .NET Core 2.0 on Linux I am trying to start the default web browser open to a link with Process.Start(). I use Process.Start("https://www.google.com"), but my .NET Core App crashes with the following:

Exception has occurred: CLR/System.ComponentModel.Win32Exception An
unhandled exception of type 'System.ComponentModel.Win32Exception'
occurred in System.Diagnostics.Process.dll: 'No such file or
directory'    at System.Diagnostics.Process.ResolvePath(String
filename)    at System.Diagnostics.Process.StartCore(ProcessStartInfo
startInfo)    at System.Diagnostics.Process.Start()    at
System.Diagnostics.Process.Start(ProcessStartInfo startInfo)    at
VPGameHelper.Program.Main(String[] args) in
/home/jj/VPGameHelper/Program.cs:line 30

A: I think this might be what you are looking for:
Process.Start for URLs on .NET Core
The original question was asked here where.
public static void OpenBrowser(string url)
{
    try
    {
        Process.Start(url);
    }
    catch
    {
        // hack because of this: https://github.com/dotnet/corefx/issues/10361
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            url = url.Replace("&", "^&");
            Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            Process.Start("xdg-open", url);
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            Process.Start("open", url);
        }
        else
        {
            throw;
        }
    }
}

Cheers and happy coding!


text:
Q: msvcr100.dll Error - WinXP x64 I am attempting to run a program created in VS2010, on an XP 64bit system. It has run fine on XP-SP3 32bit as well as all Windows 7 versions. However when running on XP 64bit it just crashes when trying to load displaying an error referencing:
ModName: msvcr100.dll ModVer: 10.0.30319.1 Offset:00000000000760d9
I realise the file it references is to do with the 2010 vcredist, which are installed with the program and after checking I had the latest versions found that the ones we were installing required XP-sp3 (which doesn't exist for 64bit XP). So I have tried installing the latest 2010-SP1 Redistributable (which doesn't say it requires XP-SP3) yet the same error still applies.
Has anybody had an error like this when trying to run a program on XP 64bit? Am I possibly looking in the wrong direction in thinking it is caused by the vcredists? Or is it simply impossible to run a program that requires the 2010 vcredists on an XP OS that hasn't got SP3?

A: This problem was solved, it was some old code that made up part of the splash screen on our program and nothing seemingly to do with the vcredists. The program seems to run fine on XP SP2 so evidently it is possible :)


text:
Q: Bind loop index with function parameter How do I correctly bind the value j in the example below?
for (j = 0; j < shorts[i+1].length; j++) {
    $('#Container').append($('<button id="but'+(j+1)+'" type="button" onclick="func(this,j)">'+ values[j]+'</button>'));
)};

A: j should be concatenated as a variable otherwise it would be considered as a string and the onclick method would look like this func(this,j).
This should do it onclick="func(this,'+j+')"
for (j = 0; j < shorts[i+1].length; j++) {
    $('#Container').append($('<button id="but'+(j+1)+'" type="button" onclick="func(this,'+j+')">'+ values[j]+'</button>'));
};

Option 2
You can also do it by binding like this instead of inline onclick method
var $button = $('<button />')
  .attr('id', j+1)
  .text(j+1)
  .on('click', func.bind(null, j+1));
  $('#Container').append($button);

This way the value j+1 will be available to the function.

function func(a){
  alert(a);
}

for (var j = 0; j < 10; j++) {
  var $button = $('<button />')
  .attr('id', j+1)
  .text(j+1)
  .on('click', func.bind(null, j+1));
  $('body').append($button);
};

A: You need to take j out of String and concatenate it properly
fiddle

values = [1, 2, 3, 4, 5, 6, 7, 8, 1, 3];

for (j = 0; j < 10; j++) {
    var div = $('<button id="but' + (j + 1) + '" type="button" onclick="func(this,' + j + ')">' + values[j] + '</button>');
    $('#mydiv').append(div);
}

A: You can do this either by using basic string concats, like so:
$('#Container').append($('<button id="but'+(j+1)+'" type="button" onclick="func(this,'+j+')">'+ values[j]+'</button>'));

Or you can use the properties of the event object to pull information from the element that is being clicked. See the section on srcElement here.
That would be done by defining a function like
function(event){
//pull info from event with
event.srcElement
//use that to decide what to do inside the function
}

and passing that string into your html onClick

A: Append the buttons without the inline click handlers.
Add a delegated click handler, and you can access the button's position using the index() method:

var values= ['a','b','c','d','e','f','g','h','i','j'];

for (j = 0; j < 10; j++) {
  $('#Container').append($('<button>' + values[j] + '</button>'));
}

$('#Container').on('click', 'button', function() {
  alert($(this).index());
});


text:
Q: Dependency error with Selenium 3.3.1 and FirefoxDriver I use geckodriver v0.15.0 (Latest release) and Firefox 52.0.1 (64 bits)
Here is my code :
public static void main(String[] args) {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    System.out.println("Page title is: " + driver.getTitle());
    driver.quit();
}

Here is the dependencies for Selenium in my pom (latest version of Selenium) :
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-firefox-driver</artifactId>
    <version>3.3.1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-support</artifactId>
    <version>3.3.1</version>
    <scope>test</scope>
</dependency>

And the exception at runtime :
Exception in thread "main" java.lang.NoSuchMethodError: org.openqa.selenium.net.PortProber.waitForPortUp(IILjava/util/concurrent/TimeUnit;)V
at org.openqa.selenium.firefox.GeckoDriverService.waitUntilAvailable(GeckoDriverService.java:73)
at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:166)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:78)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:644)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:218)

If I add this dependency :
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-remote-driver</artifactId>
    <version>3.3.1</version>
</dependency>

I have got another exception :
Exception in thread "main" java.lang.NoClassDefFoundError: org/openqa/selenium/interactions/Interactive

What dependency is missing? Thank you.
UPDATE
mvn dependency:tree with htmlunit-driver 2.25, selenium-remote-driver 3.3.1, selenium-firefox-driver 3.3.1, selenium-support 3.3.1
[INFO] +- org.seleniumhq.selenium:htmlunit-driver:jar:2.25:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-api:jar:2.53.1:compile
[INFO] |  \- net.sourceforge.htmlunit:htmlunit:jar:2.21:compile
[INFO] |     +- xalan:xalan:jar:2.7.2:compile
[INFO] |     |  \- xalan:serializer:jar:2.7.2:compile
[INFO] |     +- org.apache.commons:commons-lang3:jar:3.4:compile
[INFO] |     +- org.apache.httpcomponents:httpmime:jar:4.5.2:compile
[INFO] |     +- net.sourceforge.htmlunit:htmlunit-core-js:jar:2.17:compile
[INFO] |     +- net.sourceforge.htmlunit:neko-htmlunit:jar:2.21:compile
[INFO] |     |  \- xerces:xercesImpl:jar:2.11.0:compile
[INFO] |     |     \- xml-apis:xml-apis:jar:1.4.01:compile
[INFO] |     +- net.sourceforge.cssparser:cssparser:jar:0.9.18:compile
[INFO] |     |  \- org.w3c.css:sac:jar:1.3:compile
[INFO] |     +- commons-io:commons-io:jar:2.4:compile
[INFO] |     \- org.eclipse.jetty.websocket:websocket-client:jar:9.4.1.v20170120:compile
[INFO] |        +- org.eclipse.jetty:jetty-util:jar:9.4.1.v20170120:compile
[INFO] |        +- org.eclipse.jetty:jetty-io:jar:9.4.1.v20170120:compile
[INFO] |        +- org.eclipse.jetty:jetty-client:jar:9.4.1.v20170120:compile
[INFO] |        |  \- org.eclipse.jetty:jetty-http:jar:9.4.1.v20170120:compile
[INFO] |        \- org.eclipse.jetty.websocket:websocket-common:jar:9.4.1.v20170120:compile
[INFO] |           \- org.eclipse.jetty.websocket:websocket-api:jar:9.4.1.v20170120:compile
[INFO] +- org.seleniumhq.selenium:selenium-remote-driver:jar:3.3.1:compile
[INFO] |  +- cglib:cglib-nodep:jar:3.2.4:compile
[INFO] |  +- org.apache.commons:commons-exec:jar:1.3:compile
[INFO] |  \- net.java.dev.jna:jna-platform:jar:4.1.0:compile
[INFO] |     \- net.java.dev.jna:jna:jar:4.2.2:compile
[INFO] +- org.seleniumhq.selenium:selenium-firefox-driver:jar:3.3.1:compile
[INFO] \- org.seleniumhq.selenium:selenium-support:jar:3.3.1:compile

Update 2
OS: Linux 64 bits

A: Here is the required dependencies (I cleaned the .m2 directory too) :
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.6</version>
</dependency>
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-remote-driver</artifactId>
    <version>3.3.1</version>
</dependency>
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-api</artifactId>
    <version>3.3.1</version>
</dependency>
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-firefox-driver</artifactId>
    <version>3.3.1</version>
</dependency>

A: Maybe you have jar versions conflict error. When I had that bug in my application, I found that it was referring the old Selenium jar. To resolve this, I removed the old jar's and rebuild the project with Selenium 3 jars.
Ensure that you have right libraries added to your project.
the command mvn dependency:tree can help you with this.
Note: when you use the test scope it's mean the the dependency is only available for the test compilation and execution phases, So you must put your code in a Test method or remove the scope tag
Hope this helps.

A: check if you have the selenium-java dependency of the same version as your other dependencies
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.3.1</version>
</dependency>

A: Add System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir")+"\\geckodriver.exe"); to your code.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CheckFireFox {
    public static void main(String[] args) {
        System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir")+"\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
        System.out.println("Page title is: " + driver.getTitle());
        driver.quit();
    }

}

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>StackOverFlow</groupId>
    <artifactId>StackOverFlow</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.3.1</version>
        </dependency>
    </dependencies>
</project>

Console output :
Mar 27, 2017 2:39:01 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Page title is: Google

A: *

*Update the selenium version

*Download the geckodriver and set system path eg "F:\geckodriver-v0.20.1-win64"

*Add following code snippet to your existing code
     DesiredCapabilities capabilities = DesiredCapabilities.firefox();
     capabilities.setCapability("marionette", true);

Now run the script and it will work for you, hope this helps.


text:
Q: Can background processes started from a loop in bash pick up values from a later iteration? In Bash, if I have a while true loop where, at the top of the loop, I set a variable equal to the current date, and in consequent background commands I use this variable (e.g. to name an output file), what would happen if, say, the third execution of date=$(date) comes before the second execution of another command?
I.e.: given the following loop:
while : ; do
    date=$(date)
    backgroundcommand -o $date &
    backgroundcommand2 -o $date &
done

and if commands are executed in the following order:
    date=$(date) # first execution
    backgroundcommand -o $date & # first execution
    backgroundcommand2 -o $date & # first execution
    date=$(date) # second execution
    backgroundcommand -o $date & # second execution
    date=$(date) # third execution
    backgroundcommand2 -o $date & # second execution
    backgroundcommand -o $date & # third execution
    backgroundcommand2 -o $date & # third execution

does Bash keep track of variable states? E.g.: after 3 loops, will I have 3 pairs of files with the same date, or will I have two files, one file and three files with respectively the same name?

A: Anything in a subshell, or any backgrounded command, is a completely separate process; unlike a thread (which shares memory), such a separate process is utterly independent from the parent from which it was forked.
Consequently, the child cannot see updates to variable state which later take place in the parent, so its view of shell variables is strictly that of the variables as they existed when the background process was created.
Thus, the value of $date will always be that of the variable as of the time when the backgroundcommand ... & invocation took place, regardless of whether the parent process has updated the value since.

A: The backgroundcommandX -o $date & will have the $date variable set at the value of the iteration.
You may have a problem with the $date variable that is the same because date as a granularity of 1 sec and if your loop takes less than a second to execute you end up with the same file name.
I would first use a a custom format to avoid spaces in the file name and maybe add miliseconds in the string:
date +"%Y-%m-%d_%H_%M_%S_%N"

Or you can add a pause in the loop:
sleep 2

so you are sure that there will not have 2 similar date string.


text:
Q: "The operation couldn't be completed"/"Operation canceled" error message when saving to a Samba share via Files app I'm using the Files app on my iPhone and iPad to save photos to an SMB network share provided by Samba on an Ubuntu 20.04 server.
Since around iOS/iPadOS 14.5, trying to save a new file to the share results in an error message saying:
The operation couldn't be completed
Operation canceled

Since nothing has changed server-side, this looks like a bug in iOS/iPadOS. How can the described problem be solved?

A: There does not seem to be any documentation from Apple on changes related to SMB in iOS/iPadOS 14.5. However, the following configuration change on the Samba server restores Files app functionality:

*

*Install the Samba package containing VFS modules (on Ubuntu via apt install --no-install-recommends samba-vfs-modules)

*Add the following line to your Samba configuration (on Ubuntu in /etc/samba/smb.conf) in the [global] section or in the relevant share section:
vfs objects = fruit streams_xattr

*Restart Samba (on Ubuntu via systemctl restart smbd.service)

You might need to reconnect the share in the Files app. Afterwards, saving new files to the share should work again.
Documentation for the fruit SAMBA VFS module can be found at https://www.samba.org/samba/docs/current/man-html/vfs_fruit.8.html.


text:
Q: How to check the log of failed deployment by docker-compose on fargate I deploy my project to aws ecs with this command.
docker compose -f docker-compose.fargate.yml up
version: "3.9"

services:

  admindjango:
    image: 6781xxxxxxxx.dkr.ecr.ap-northeast-1.amazonaws.com/st_admin_site:latest
    ports:
      - "8011:8011"
    restart: always
    command: uwsgi --http :8011 --module admin_site.wsgi

  nginx:
    image: 6781xxxxxxxx.dkr.ecr.ap-northeast-1.amazonaws.com/st_nginx:latest
    ports:
      - '80:80'
    depends_on:
      - admindjango

At first it looks well but failed at last.
And stack is also deleted.
I can guess there are some errors in docker, however stack is deleted, so I can't find any clue about what happened.  Is there any good way to check log or something?
(base) whitebear$ docker compose -f docker-compose.fargate.yml up
WARNING services.restart: unsupported attribute
WARNING services.scale: unsupported attribute
WARNING services.scale: unsupported attribute
[+] Running 20/20
 ⠿ monitor-admin                    DeleteComplete                                                                                358.5s
 ⠿ NginxTaskExecutionRole            DeleteComplete                                                                                242.0s
 ⠿ CloudMap                          DeleteComplete                                                                                352.6s
 ⠿ Cluster                           DeleteComplete                                                                                306.6s
 ⠿ LogGroup                          DeleteComplete                                                                                308.7s
 ⠿ NginxTCP80TargetGroup             DeleteComplete                                                                                242.0s
 ⠿ DefaultNetwork                    DeleteComplete                                                                                306.6s
 ⠿ AdmindjangoTaskExecutionRole      DeleteComplete                                                                                309.7s
 ⠿ LoadBalancer                      DeleteComplete                                                                                307.6s
 ⠿ AdmindjangoTCP8011TargetGroup     DeleteComplete                                                                                307.6s
 ⠿ Default80Ingress                  DeleteComplete                                                                                229.9s
 ⠿ DefaultNetworkIngress             DeleteComplete                                                                                228.9s
 ⠿ Default8011Ingress                DeleteComplete                                                                                228.9s
 ⠿ NginxTaskDefinition               DeleteComplete                                                                                211.9s
 ⠿ AdmindjangoTaskDefinition         DeleteComplete                                                                                276.9s
 ⠿ AdmindjangoServiceDiscoveryEntry  DeleteComplete                                                                                257.6s
 ⠿ NginxServiceDiscoveryEntry        DeleteComplete                                                                                192.3s
 ⠿ NginxTCP80Listener                DeleteComplete                                                                                87.4s
 ⠿ AdmindjangoTCP8011Listener        DeleteComplete                                                                                152.8s
 ⠿ AdmindjangoService                DeleteComplete                                                                                142.9s
AdmindjangoService EssentialContainerExited: Essential container in task exited

A: We have recently introduced the ability to avoid the automatic rollback in CFN but docker doesn't leverage that (AFAIK).
The best option in that case (that's how I do it anyhow) is to monitor closely the deployment and check the task log. The CFN message says that the essential container exited. This means that either the nginx or the admindjango containers (that are deployed in separate ECS services and separate ECS tasks under the same ECS cluster) did not stabilize for the long run and exited. You need to locate them both in the ECS console and explore the container logs to understand what happened (which one failed and why).
I assume this compose comes up just fine locally, I guess?


text:
Q: CSS margin with multiple types Sorry for this dumb question but
I found in a piece of code that looks like
margin-left: 150px;
margin-left: 8%;
margin-left: 7vw;

Can you please explain me who this work? which will be used?
Also can't we write something like:
margin-left: 150px, 8%, 7vm;

I think of this as a short version or something?
EDIT I was asking only about margin-left not about all the properties of margin :)

A: Each next occurrence of CSS rule overwrites previous, so in this example the last one rule will be used. Your shorter form is also invalid. In single line you could define margins for each side:
margin: 10px 5px 2px 8px;

It gives you 10px top margin, 5px right margin, 2px bottom and 8px left margin.

A: If you write this way:
 margin-left: 150px;
 margin-left: 8%;
 margin-left: 7vw;

only margin-left: 7vw; will be accepted because it will override margin-left: 150px; and margin-left: 8%; , margin-left, margin-right , margin-top , margin-bottom only accept a single value.
You could use shorthand for margin like:
margin: margin-top margin-right margin-bottom margin-left
example:
margin: 10px 15px 20px 5px;
So in this shorthand the last one 5px will set as margin left ,
There are two more ways for writing shorthand:
2 values:
margin: (margin-top + margin-bottom) (margin-left + margin-right)
example:
margin: 10px 20px
3 values:
margin: (margin-top) (margin-left + margin-right) (margin-bottom)
example:
margin: 10px auto 20px


text:
Q: Force node to be directly beneath another node I have a graph that's laid out from left-to-right.  There are some elements of this graph, however, that I want to have positioned relative to another node.  For example, if I have this graph:
digraph "Test" {
    rankdir = "LR"
    A -> B
    B -> C
    D -> B
    note -> B

    note [ shape="house" ]
};

It renders like this:

However, I'd like the "note" node to always be positioned directly underneath the node to which it's pointing, like this (manually created) graph:

I've tried experimenting with a subgraph with a different rankdir and fiddling with rank and constraint attributes, but have been unsuccessful in getting this to work, as I've only been playing around with DOT for a couple of days.

A: A general technique for moving nodes around is to create invisible edges.  In your case, you could create an edge from A to note, mark it invisible, and then mark the edge from note to B as non-constraining:
A -> note [style="invis"];
note -> B [constraint=false];

A: You can enumerate the nodes before defining the edges, and then constrain node B to the same rank as node note by putting them in a subgraph:
digraph "Test" {
    rankdir = "LR"
    A;D;
    {rank=same; note; B;}
    C;

    A -> B
    B -> C
    D -> B
    B -> note [dir=back]

    note [ shape="house" ]
};

Please note that in order to have node note below node B, I had to reverse the edge direction and add dir=back to have the arrow drawn correctly.


text:
Q: Power Automate and (exotic) email/domain extensions Created a Power Automate (flow) that sends out emails to users.
However users with a .group domain extension in their email address (ex. user@contoso.group) do not receive the emails.
Other users of the same email do receive the email (and see the correct .group emails in the CC of the email). So the Power Automate ran correctly.
ICT claims not to find anything in the logs of their Exchange, spam filter, virus scanner.
Would it be possible that the Power platform blocks sending out emails to certain/new domain extensions?

A: I think creating proper data loss policy might help in this situation.

*

*Refer this link for more details.

*Create a data loss prevention (DLP) policy


text: Q: A case where Zariski topology of a product is the product topology I'm aware that, in general, the Zariski topology of a product of algebraic varieties is not necessarily the product topology. But what is an example of when the Zariski topology of a product IS the product topology?


text:
Q: What could cause a Java TCP socket to close? I'm trying to use an implementation of an MQTT client specifically Paho Java client in Android, and trying to trace where I get an EOFException  error.
Specifically this happens on in.readByte();.
public final byte readByte() throws IOException {
    int temp = in.read();
    if (temp < 0) {
        throw new EOFException();
    }
    return (byte) temp;
}

Having looked at this exception, it seems to be triggered when I'm attempting to read from a socket that has been closed. This seems to be a network error, that I fail to locate.
My question is what could cause a socket to close? I haven't yet ruled out the chance of it being closed programmatically but in case of an external factor what are the usual causes of a TCP socket closing? Perhaps any more specific reason relating to an Android device?

A: Typically the things that cause a socket to close are:

*

*the client closes the socket

*the server closes the socket, possibly due to a timeout

*the server shuts down and issues a reset, either before shutdown or after restart, which closes the socket

*a firewall times the connection out and effectively closes the socket by issuing a subsequent reset

Without more details on your specific symptoms, it's hard to say which of these is most likely.


text:
Q: TikZ arrow emanating from node at an angle for a distance How do I draw a line of length l and at an angle of a from a circular node N in TikZ?

A: You can access the points around a node with <node name.angle> for example, a.50 will give you a point on the border of node a at an angle of 50 degrees. Further, you can draw a line of length lcm elevated at an angle of t degrees by (t:lcm).
\documentclass[tikz,margin=10pt]{standalone}
\begin{document}
  \begin{tikzpicture}
      \node[draw,circle]  at (0,0) (a) {N};
      %% draw a line of 2cm length from the border of node a at an angle 50. The line is having a slope of tan(50).
      \draw (a.50) -- (50:2cm);
  \end{tikzpicture}
\end{document}

Putting many lines and some make-up ;-)
\documentclass[tikz,margin=10pt]{standalone}
\begin{document}
  \begin{tikzpicture}
      \node[circle]  at (0,0) (a) {N};
      \foreach \angle in {5,10,...,360}{%
      \draw (a.\angle) -- (\angle:2cm);
      }
  \end{tikzpicture}
\end{document}

And some animation:
\documentclass[tikz,margin=10pt]{standalone}
\begin{document}
  \foreach \angle in {1,2,...,360}{%
    \begin{tikzpicture}
      \path (-2,-2.3) rectangle (2,2.3);  %% pad some bounding box
      \node[circle]  at (0,0) (a) {N};
      \draw (a.-\angle) -- (-\angle:2cm);
    \end{tikzpicture}
  }
\end{document}

A: You could also use pins:
\documentclass{standalone}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
  \node [circle,draw,pin={[pin distance=2cm,pin edge={blue,thick}]330:$P_1$},
                     pin=60:$P_2$] at (0,0) {N};
\end{tikzpicture}
\end{document}

Pin P1 represents the default behaviour: gray line of a certain length, while pin P2 is customized. Length is set with pin distance, while pin edge lets you define the colour, the thickness, lets you add an arrowhead or even decorate the path (e.g. a snake path). In both cases what precedes the colon : is the angle that defines the slope of the line.


text:
Q: Jquery Replace with return value of Javascript function OK I am just starting out with jQuery.
I have a page with a table of date-values. Each is wrapped in a tag which I can find with
 $('mytag').
<mytag>2009-10-31</mytag>
How, using Jquery, would I

*

*take each of the source values and

*pass it to a Javascript function

*then replace that source value within the table with the result of the function calculation.

So  <mytag>2009-10-31</mytag>would be replaced with <mytag>Very Late</mytag>
I have the Javascript function written. My question is the jQuery syntax to pass the individual value.

A: Firstly, you will need an element selector, e.g.
$('table')

Will select all <table> elements in your html. So,
$('mytag')

will give you your  elements. You will get a jQuery object (not a DOM object) returned. See http://docs.jquery.com/Selectors
Then you want to call a function for each of your elements. For this we call the .each function, and pass the function to call for each element:
$('mytag').each(function(){
    //function code goes here
});

(See http://docs.jquery.com/Utilities/jQuery.each)
The function in this case is called an Anonymous function
Then you want to reference the current object in the iteration, so we use the DOM this item and wrap it into a jquery object. To get the value, we use the .text() function (http://docs.jquery.com/Attributes/text)
$('mytag').each(function(){
    $(this).text()
});

Note: if it were an input element then you would have used .val()
Passing it to a function is easy:
    ...
    MyFunction($(this).text());
    ...

The text() function has an overloaded implementation which allows you to set the text if you pass a value:
    $(this).text(someval);

So, we can factor this into our code
    ...
    $(this).text(MyFunction($(this).text()));
    ...

Making our final code block:
$('mytag').each(function(){
    $(this).text(MyFunction($(this).text()));
});

A: $('mytag').each(function (index,tag) {
    $(tag).text( myFunc($(tag).text()) );
});

A: $("mytag").each(function() {
   $(this).html("Very Late");

});

A: $('mytag').each(function() {
  $(this).text(someFunction($(this).text()));
});

But, from the sound of your problem, you might be better served by the jQuery-timeago plugin.  For your particular case, you'd possibly want to allow dates in the future:
jQuery.timeago.settings.allowFuture = true;

...and you'd want to create your own language override.  See the language override examples.  You could define several "late" and "very late" values.  You can also pass a function to each one to change the value depending on how many days ago a timestamp was.


text:
Q: How to get smooth numbers efficiently by using dependent iterators in Table I have the following code for getting smooth numbers up to Prime[4] :
g = 100;

t1 = Table[{2^x*3^y*5^z*7^u}, {u, 0, Log[7, g]}, {z, 0, Log[5, g/(7^u)]}, {y, 0, Log[3,g/(7^u*5^z)]}, {x, 0, Log[2, g/(7^u*5^z*3^y)]}]
t2 = Sort[Flatten[t1]]

I am looking for a general solution for k Primenumbers (in ascending order) using Table which refers to iterators appearing in the loop before. I know I can use FactorInteger and Select or fast code from (Creating a Table with varying depth and interdependent limits)  to solve this problem, but how to tackle it using Table? Is there a way to do this? I think the answer lies somewhere in Table with dependent iterator  but here are too many tiwsts for my level of understanding.

A: Clear["Global`*"]

g = 100;

t1 = Table[{2^x*3^y*5^z*7^u}, {u, 0, Log[7, g]}, {z, 0, Log[5, g/(7^u)]}, {y,
    0, Log[3, g/(7^u*5^z)]}, {x, 0, Log[2, g/(7^u*5^z*3^y)]}];

t2 = Sort[Flatten[t1]]

(* {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, 28, \
30, 32, 35, 36, 40, 42, 45, 48, 49, 50, 54, 56, 60, 63, 64, 70, 72, 75, 80, \
81, 84, 90, 96, 98, 100} *)

Generalizing to n primes
smooth[n_Integer?Positive, g_Integer?Positive] :=
 Module[{a, func, factors, iterators,
   primes = Prime /@ Range[n],
   vars = Array[a, n]},
  func = Times @@ (primes^vars);
  factors = #[[1]]^#[[2]] & /@ Transpose[{primes, vars}];
  iterators = {#[[1]], 0, Log[#[[2]], #[[3]]]} & /@
    Transpose[{
      Reverse@vars,
      Reverse@primes,
      g/FoldList[Times, 1, Most@Reverse@factors]}];
  Table[func, Evaluate[Sequence @@ iterators]] // Flatten // Sort // Quiet]

Checking against original calculations
smooth[4, g] == t2

(* True *)


text:
Q: All squares modulo p where p is 3 modulo 4 are 4 powers I would like to prove the lemma:

For every prime $p$ such that $p=3 \:(mod\:4)$ if $a$ is square modulo $p$ (a.k.a there exists a number $b$ such that $a=b^2\:(mod\:p)$), then its 4 power modulo $p$.

But I don't have any lead.
Thanks!

A: The key thing here, one way or another, is to note that $-1$ is not a square modulo $p$. This means that if $b^2=a$ either $b$ or $-b$ is a square. I won't fill in the details because you said you wanted a lead.

A: The following proof is excerpted from one of my answers to an older question . . .

Assume $p$ is a prime, with $p \equiv -1\;\,(\text{mod}\;4)$.

Then $-1$ is not a quadratic residue, mod $p$.

Claim every square in $Z_p$ is also a $4$-th power.

Let $a,b \in Z_p^{*}$, and suppose $a^4=b^4$ in $Z_p$.
\begin{align*}
\text{Then in $Z_p$,}\;\;&a^4=b^4\\[4pt]
\iff\;&a^2=\pm b^2&&\text{[since $Z_p$ is a field]}\\[4pt]
\iff\;&a^2=b^2&&\text{[since $-1$ is not a quadratic residue, mod $p$]}\\[4pt]
\iff\;&a= \pm b&&\text{[since $Z_p$ is a field]}\\[4pt]
\end{align*}
Noting that $b\ne -b$ in $Z_p^*$ (since $p$ is odd), it follows that the map $Z_p^{*} \to Z_p^{*}$ given by $x \mapsto x^4$ is exactly two-to-one, hence the set of $4$-th powers in $Z_p^{*}$ has cardinality $\frac {p-1}{2}$.

But the set of squares in $Z_p^{*}$ also has cardinality $\frac {p-1}{2}$ (since $p$ is prime).

Of course, every $4$-th power is also a square, hence, since the cardinalities are the same, the set of $4$-th powers in $Z_p^{*}$ is the same as the set of squares in $Z_p^{*}$.

Noting that $0$ is both a square and a $4$-th power, it follows, as claimed, that every square in $Z_p$ is also a $4$-th power.


text:
Q: Google Earth data backup Is it possible to have data backup? If so how long?
Except Google Earth is there any other authentic system that can provide cultivations image data of a field for last few years?


text:
Q: How to hide multiple Show/Hide DIV's when another DIV is clicked How do I hide all buttons in the second and third row if a different button is clicked in the first row and if a another button is clicked in the second row it will hide the buttons for that column and show buttons for the column that is clicked? I'm trying to achieve a form similar to http://gazelle.com/ for my website but it's getting a bit difficult for me.
Example: If I click, "iPhone" -- buttons iphone 5, iphone 4s, iphone 4, and iphone 3gs show, then click, "iphone 5" -- buttons at&t, sprint, verizon, unlocked, and other show under the first row, then I change my mind and decide to click "tablet" in the first, the buttons for "tablet" show up but the buttons from iphone 5 go back to hiding but the buttons for "tablet" show up.
<!DOCTYPE html>

        <button>iPhone</button>
        <button>iPod</button>
        <button>Tablet</button>

        <button onclick="showHide('q4'); return false;">iPhone 5</button>
        <button>iPhone 4S</button>
        <button>iPhone 4</button>
        <button>iPhone 3GS</button>

        <button>iPod Touch</button>
        <button>iPod Nano</button>
        <button>Classic iPod</button>

        <button>iPad</button>
        <button>Windows</button>
        <button>Nook</button>

        <button onclick="showHide('q'); return false;">AT&T</button>
        <button>Sprint</button>
        <button>Verizon</button>
        <button>Unlocked</button>
        <button>Other</button>

http://jsfiddle.net/EbbCc/

A: Try This:

<button>iPhone</button>
<button>iPod</button>
<button>Tablet</button>

    <button onclick="subShowHide('1');">iPhone 5</button>
    <button>iPhone 4S</button>
    <button>iPhone 4</button>
    <button>iPhone 3GS</button>

    <button>iPod Touch</button>
    <button>iPod Nano</button>
    <button>Classic iPod</button>

    <button>iPad</button>
    <button>Windows</button>
    <button>Nook</button>

    <button onclick="subSubShowHide('1');">AT&T</button>
    <button>Sprint</button>
    <button>Verizon</button>
    <button>Unlocked</button>
    <button>Other</button>

    <button>test1</button>
    <button>test2</button>
    <button>test3</button>

A: Try this i hope it will solve your requirement.
http://jsfiddle.net/satheeaseelan/Qf5B3/
<!DOCTYPE html>

        <button>iPhone</button>
        <button>iPod</button>
        <button>Tablet</button>

    <button class="iphone5">iPhone 5</button>
    <button class="iphone4s">iPhone 4S</button>
    <button class="iphone4">iPhone 4</button>
    <button class="iphone3gs">iPhone 3GS</button>

    <button class="ipodT">iPod Touch</button>
    <button  class="ipodN">iPod Nano</button>
    <button  class="ipodC">Classic iPod</button>

    <button class="ipad">iPad</button>
    <button class="windows">Windows</button>
    <button class="nook">Nook</button>

    <button class="iphone5 ipodN iphone4s ipad">AT & T</button>
    <button class="nook ipodN iphone3gs ipad">Sprint</button>
    <button class="iphone5 iphone4s windows">Verizon</button>
    <button class="nook ipodN ipodT ipad iphone4">Unlocked</button>
    <button class="iphone5 iphone3gs windows">Other</button>

A: This is sooo bad practice, but here is solution:
You need jQuery for this to work so jQuery needs to be loaded before this script whichever option you decide to use.
Put this in script tag in your  tag. Or in separate javascript document with document ready:
function showHide(obj) {
  $('#' + obj).toggle('fast');
  console.log('#' + obj);
}

Ping me for more elegant and smooth solution


text:
Q: unable to login to mysql console for non root unix users My Issues is that when I am logged in as a normal user on unix server and then try to login as MySQL root. It throws below error but when I am logged in as root to unix server and then try to connect to MySQL command line it allows me. I don't understand why is this happening. and how to resolve it. I want connect to MySQL command line with any normal unix user not root always.
-sh-4.2$ mysql -u root -pPASSWORD
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (13)
-sh-4.2$ su Password:
[root@hostname]# mysql -u root -pPASSWORD
Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL
connection id is 78203 Server version: 5.5.52-log MySQL Community
Server (GPL)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights
reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input
statement.
mysql>


text:
Q: why we shouldn't assert interactions with stubs? I'm reading a book on unit testing which says

Asserting interactions with stubs is a common anti-pattern that leads to fragile tests.

Below is an example:
[Fact]
public void Creating_a_report() {
   var stub = new Mock<IDatabase>();
   stub.Setup(x => x.GetNumberOfUsers()).Returns(10);
   var sut = new Controller(stub.Object);

   Report report = sut.CreateReport();

   Assert.Equal(10, report.NumberOfUsers);
   stub.Verify(x => x.GetNumberOfUsers(), Times.Once);   // <--- Asserts the interaction with the stub, which is not correct
}

I don't quite get it. Let's say if you refactor the code base and change the name/method signature of GetNumberOfUsers method, even though you don't have stub.Verify(x => x.GetNumberOfUsers(), Times.Once);, you still need to modify the code stub.Setup(x => x.GetNumberOfUsers()).Returns(10); to make the test code compile or pass. Whith stub.Verify(x => x.GetNumberOfUsers(), Times.Once); I can at least make sure the code logic is correct (GetNumberOfUsers method will be called, if it doesn't, then there is a serious bug in it, so it is like extra protection)


text:
Q: Two sample one-sided Kuiper Test and KS-statistic With the KS-Test it is possible to conduct a two sample one-sided test between two different random samples $A$ and $B$ to test whether one CDF is larger or smaller than the other, i.e. is $CDF_A$ larger than $CDF_B$.  Standard implementations for this exist, for example MATLAB's kstest2.
So with respect to the above test (is $CDF_A$ larger than $CDF_B$) the KS-statistic will be calculated as $max(CDF_A - CDF_B)$, which can then be used to calculate the p-value.
Is it possible to define a two sample one-sided Kuiper Test? Essentially the question that I want to answer is that whether the two CDFs, $CDF_{A}$  and $CDF_{B}$ differ at the tails and that $CDF_{A}$ is overall larger than $CDF_{B}$.
For example in the image below the two CDFs differ at the tails but absolute value of $D^{+}$ is greater than absolute value of $D^{-}$. So in this case can we use the Kuiper Test to determine that one is greater than the other and how would we calculate the KS-statistic for this case?

A: This is a good question. My answer is it cannot be done properly, and I add

Use the one-sided KS test at your own risks.

For instance, R offers the choice between two.sided, less or greater. I consider this is a mistake because it does not really explain how to interpret the one-sided case. Here is an example that will explain the main issue.
Say that $A$ and $B$ differ only by their variance. For instance assume $A \sim N(0, 1)$ and $B \sim N(0,5)$. The two distributions are different, the null hypothesis is false, so the p-value of the two-sided KS test decreases as the sample size increases. But what happens with the one-sided KS tests? Let us find out with an example.
set.seed(123)
A <- rnorm(100, sd=1)
B <- rnorm(100, sd=5)
ks.test(A, B, alternative="less")
# D^- = 0.44, p-value = 3.909e-09
# Null is rejected. Accept alternative A < B
ks.test(x, y, alternative="greater")
# D^+ = 0.26, p-value = 0.001159
# Null is rejected. Accept alternative A > B

That's right. We have accepted both A < B and A > B. And what takes the cake is that A and B are centered on the same value. Contrary to a popular belief, the one-sided versions of the KS test do not tell  whether one distribution is shifted respective to the other. What do they tell exactly? I am not sure.
The best explanation to understand what happens is your picture. You can see that in this case, both $D_+$ and $D_-$ are large, so both alternatives are accepted. It is also important to understand that by symmetry, $D = D_+$ or $D = D_-$ with probability $1/2$ each. Which statistic "won" does not tell you anything interesting.
To be honest, I do not fully understand your proposal for a one-side Kuiper test, but I foresee that it would have the same difficulties. I wrote a more detailed description of this issue on my blog (see (mis)using the KS test for p-hacking) and in the scientific literature (see The signed Kolmogorov-Smirnov test: why it should not be used). The suggestions from the reviewers Garrett Jenkinson and Desmond Campbell were to use the Wilcoxon test and the $t$ test instead.


text:
Q: Sublime Text 2 Key Bindings - Is there any way to detect left/right modifier keys? Is it possible to make Left Alt+A and Right Alt+A do different things? And of course, other modifier keys.
If not, maybe the following idea would work?
If AppleScript, Python, Ruby, Perl etc. can detect left/right modifiers I can set complicated key bindings in sublime text (like ["cmd+ctrl+shift+alt+a", "cmd+ctrl+shift+alt+a"]) and send those keystrokes with AppleScript or Automator?

A: Yes, Sublime Text 2 does recognise right alt and left alt as separate modifiers.
Just refer to key bindings section of the documentation for the full rules: http://www.sublimetext.com/docs/key-bindings


text:
Q: PHP attachment using SwiftMailer I am learning to use SwiftMailer and I am having trouble getting the attachment to work from a
input type. Shouldn't I only need:
<input name="attachment" id="attachment" type="file">

then
$message = Swift_Message::newInstance()
->attach(new Swift_Message_Attachment(new Swift_File($file), $filename,));

Here is my full code
<?php
if (!empty($_POST)) {

$success = $error = false;

$post = new stdClass;

$file = $_FILES["attachment"]["tmp_name"]; //"attachment" is the name of your input field, "tmp_name" gets the temporary path to the uploaded file.

$filename = $_FILES["attachment"]["name"]; //"name" gets the filename of the uploaded file.

foreach ($_POST as $key => $val)
    $post->$key = trim(strip_tags($_POST[$key]));

    if (empty($post->name) OR empty($post->email))
    $error = true;

else {

    $dir = dirname(__FILE__);

    ob_start();
    require_once($dir.'/pdf.php');
    $pdf_html = ob_get_contents();
    ob_end_clean();

    require_once($dir.'/dompdf/dompdf_config.inc.php');

    $dompdf = new DOMPDF();
    $dompdf->load_html($pdf_html);
    $dompdf->render();
    $pdf_content = $dompdf->output();

    ob_start();
    require_once($dir.'/html.php');
    $html_message = ob_get_contents();
    ob_end_clean();

    require_once($dir.'/swift/swift_required.php');

    $mailer = new Swift_Mailer(new Swift_MailTransport());

    $message = Swift_Message::newInstance()
                   ->setSubject('Order Entry') // Message subject
                   ->setTo(array('ehilse@paifashion.com' => 'Eric Hilse')) // Array of people to send to
                   ->setFrom(array('no-reply@paifashion.com' => 'PAi Order Entry'))
                   ->setBody($html_message, 'text/html') // Attach that HTML message from earlier
                   ->attach(Swift_Attachment::newInstance($pdf_content, 'design.pdf', 'application/pdf')); // Attach the generated PDF from earlier
                   ->attach(new Swift_Message_Attachment(new Swift_File($file), $filename));
    // Send the email, and show user message
    if ($mailer->send($message))
        $success = true;
    else
        $error = true;

}

}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>PAi Cap & Tee Art Pack Order Form</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />

PAi Cap & Tee Art Pack Order Form

        <?php if ($success) { ?>

Congratulations! It worked! Your order has been sent.

        <?php } elseif ($error) { ?>

Sorry, an error occurred. Try again!

        <?php } ?>

        <form method="post" action="" enctype="multipart/form-data">
            <fieldset>
                <legend>Please fill in the following form:</legend>
                    Your Name:*
                    <input type="text" name="name" id="name" class="input" />

                    Your Email:*
                    <input type="text" name="email" id="email" class="input" />

                    Art Pack Number:*
                    <input type="text" name="artpacknumber" id="artpacknumber" class="input" />

                    New Or Revise?*
                    <select name="language" id="language">
                        <option value="NEW">New</option>
                        <option value="REVISE">Revise</option>
                    </select>

                    Due Date:*
                    <input type="text" name="duedate" id="duedate" class="input" />

                    Date Entered:*
                    <input type="text" name="dateentered" id="dateentered" class="input" />

                    Design Name:*
                    <input type="text" name="designname" id="designname" class="input" />

                    Customer:*
                    <input type="text" name="customer" id="customer" class="input" />

                    Account:*
                    <input type="text" name="account" id="account" class="input" />

                    Sales Rep:*
                    <input type="text" name="salesrep" id="salesrep" class="input" />

                    Extension:*
                    <input type="text" name="extension" id="extension" class="input" />

                    Comments:*
                    <textarea name="comments" id="comments" rows="4" cols="40"></textarea>

                    File Upload
.
                    <input name="attachment" id="attachment" type="file">

                    <input type="submit" class="submit" id="submit" value="Submit" />

        </fieldset>

    </form>

Here is my new errors
[27-Dec-2011 14:51:58] PHP Deprecated:  Function set_magic_quotes_runtime() is deprecated in /Applications/MAMP/htdocs/paipdf2/dompdf/lib/class.pdf.php on line 4332
[27-Dec-2011 14:51:58] PHP Deprecated:  Function set_magic_quotes_runtime() is deprecated in /Applications/MAMP/htdocs/paipdf2/dompdf/lib/class.pdf.php on line 4348
[27-Dec-2011 14:51:58] PHP Warning:  require_once(/Applications/MAMP/htdocs/paipdf2/dompdf/include/swift_message_attachment.cls.php) [function.require-once]: failed to open stream: No such file or directory in /Applications/MAMP/htdocs/paipdf2/dompdf/dompdf_config.inc.php on line 194
[27-Dec-2011 14:51:58] PHP Fatal error:  require_once() [function.require]: Failed opening required '/Applications/MAMP/htdocs/paipdf2/dompdf/include/swift_message_attachment.cls.php' (include_path='.:/Applications/MAMP/bin/php/php5.3.6/lib/php') in /Applications/MAMP/htdocs/paipdf2/dompdf/dompdf_config.inc.php on line 194

A: I'm guessing $file and $filename don't carry the actual value of the file path and name.
Assuming the form posting is done correctly, to access the path of an uploaded file you have to use the $_FILES superglobal array, like so:
$file = $_FILES["attachment"]["tmp_name"]; //"attachment" is the name of your input field, "tmp_name" gets the temporary path to the uploaded file.
$filename = $_FILES["attachment"]["name"]; //"name" gets the filename of the uploaded file.
$message = Swift_Message::newInstance()
->attach(new Swift_Message_Attachment(new Swift_File($file), $filename));

Documentation: http://www.php.net/manual/en/reserved.variables.files.php

A: well, there is a problem when including DOMpdf before you include Swiftmailer.
I have not found out why it's wrong, but I do have a solution.
Change this peace of code in 'dompdf_config.inc.php':
function DOMPDF_autoload($class) {
  $filename = mb_strtolower($class) . ".cls.php";
  require_once(DOMPDF_INC_DIR . "/$filename");
}

to this:
function DOMPDF_autoload($class) {
  $filename = mb_strtolower($class) . ".cls.php";
  if (file_exists(DOMPDF_INC_DIR . "/$filename")) {
    require_once(DOMPDF_INC_DIR . "/$filename");
  }
}

Afther that change it works and you can mail your pdf with swiftmailer.
extra information. How I start DomPDF:
require_once("lib/dompdf/dompdf_config.inc.php");
spl_autoload_register('DOMPDF_autoload');
$dompdf = new DOMPDF();
$dompdf->load_html($pdfhtml);
$dompdf->set_paper('a4', 'portrait');
$dompdf->render();
$dompdf->stream("invoice", array('Attachment'=>0));


text:
Q: rlwrap -z pipeto: piping output through pagers I am using rlwrap to colorize prompt in asterisk CLI:
rlwrap -s 99999 -a -pRED /usr/sbin/asterisk -r

I read in man rlwrap that I can also use
rlwrap -z pipeto

to pipe output through a colorizer. I have grc colorizer which works like this:
cat foo | grcat <conf_file>

The above examples colorizes foo using the rules from <conf_file>.
How can I use rlwrap -z pipeto to colorize output from rlwrap through grcat ?

A: pipeto
Unfortunately, rlwrap's built-in filter pipeto does not filter output in the way you desire. I find the documentation rather misleading, but what it does is if you run rlwrap -z pipeto some-shell, then, within the interaction:

*

*if you type commands without any pipe sign (|), those are passed verbatim to some-shell and then the output of that is simply printed;

*if you type command | filter, then command is passed to some-shell to interpret, and the output of that is piped through filter before being printed (where filter is any command you could run from the command line in your Unix shell).
So the good news is you could get the behavior you are looking of, kindof, sortof, by running rlwrap -z pipeto asterisk and then remembering to append | grc to each command you want to pass to asterisk. But that would not be very convenient, would it? Hence outfilter.
outfilter
I suggest creating the following rlwrap filter script:
#! /usr/bin/perl
use lib ($ENV{RLWRAP_FILTERDIR} or ".");
use RlwrapFilter;
use strict;

my $filter = new RlwrapFilter;
my $name = $filter->name;

my $filter_command = join ' ', @ARGV;

$filter->help_text("Usage: rlwrap -z '$name <filter-command>' <command>\n"
                   . "Filter <command> output through <filter-command>");

$filter->output_handler(sub {""});
$filter->prompt_handler(\&prompt);
$filter->run;

sub prompt {
    my $prompt = shift;

    my $output = $filter->cumulative_output;
    $output =~ s/\r//g;

    open (PIPE, "| $filter_command")
        or die "Failed to create pipe: $!";
    print PIPE $output;
    close PIPE;

    return $prompt;
}

Save it as outfilter, make it executable, and then run rlwrap -z './outfilter <coloring-filter>' shell. I tried with:
rlwrap -z './outfilter ccze -A' gosh

which nicely colors Gauche's output. In your case, that would become something like:
rlwrap -z './outfilter grcat grcat-config' asterisk

If you like the filter and want to be able to run it without having to specify its path, you could move it alongside the builtin filters (on my system, that's in directory /usr/share/rlwrap/filters).
Note that the filter as written is probably inefficient (it spawns a new copy of the coloring filter for each interaction with the command shell, because that's the shortest way I could find to have it flush its buffers) and fragile, but if the shell you are interacting with doesn't do any black magic of its own, it should work.


text:
Q: Drawing map with ggplot and draw dots in map I work on a dataset with distilleries of Scotland and I want to visualize their locations on a map.
So I used the following code to draw Scotland and its surrounding like this:
library(SpatialEpi)
library(tmap)
library("sf")
library("rnaturalearth")
library("rnaturalearthdata")
library("rgeos")
library("ggspatial")
library("ggrepel")

world <- ne_countries(scale = "medium", returnclass = "sf")
ggplot(data = world) +
  geom_sf() +
  coord_sf(xlim = c(-13.68, 0.72), ylim = c(54.63, 60.85), expand = FALSE)

Afterwards, I used the Longitude/Latitude-information of the dataset whisky and tried to draw the distilleries as points (the dataset can be downloaded here: whisky):
whisky <- read.csv("whisky_data.csv")
mapdata <- whisky[,c(1,15:16)]
mapdata$Latitude <- as.numeric(mapdata$Latitude)
mapdata$Longitude <- as.numeric(mapdata$Longitude)

coordinates(mapdata)<-~Longitude+Latitude
class(mapdata)

# does it have a projection/coordinate system assigned?
proj4string(mapdata)  # Nope

# check coordinate system of world
st_crs(world)  # +proj=longlat +datum=WGS84

# manually tell R what the coordinate system is
proj4string(mapdata)<-CRS("+proj=longlat +datum=WGS84")

ggplot(data = world) +
  geom_sf() +
  coord_sf(xlim = c(-13.68, 0.72), ylim = c(54.63, 60.85), expand = FALSE) +
  geom_point(data=as.data.frame(mapdata), aes(x=Longitude, y=Latitude), color="red")

But there are no points shown in the map.
I guess I didn't transform the coordinates correctly to be drawn into the world map?
As I'm an absolute beginner in mapping I'm grateful for any help with this!!
Thanks so much! :)

A: Your case is a strong one / whisky, what a lovely word?
Consider this code; it is built on the {sf} package and the ggplot2::geom_sf() function. For more information do have a look at this post on the RStudio forum discussing other options for drawing a map https://community.rstudio.com/t/best-packages-for-making-map-leaflet-vs-ggmap-vs-sf-vs/38403/2?u=jlacko
But one way or the other, this code should get you started.
library(sf) # general spatial manipulation
library(giscoR) # for the shape of Scotland
library(dplyr) # general data frame manipulation
library(ggplot2) # because ggplot...

# Scotland as a spatial object
scotland <- giscoR::gisco_get_nuts(nuts_id = 'UKM',
                                   resolution = '01')

# yer data
distilleries <- read.csv("whisky_data.csv") %>%
  st_as_sf(coords = c("Latitude", "Longitude"), crs = 4326)

# a quick reality check - looks legit
mapview::mapView(distilleries)

# a ggplot object
ggplot() +
  geom_sf(data = scotland, fill = NA, color = "gray45") + # borders of Scotland
  geom_sf(data = distilleries, pch = 4, color = "red") + # the distilleries
  theme_void() +
  labs(title = "Distilleries of Scotland") +
  theme(plot.title = element_text(hjust = 1/2))


text:
Q: Cordova / Gulp best practice I'm trying to setup a Cordova develop/deployment chain using Gulp. I ended with this gulpfile.js, but I'm not really satisfied since I need to kill "gulp watch" task in order to run "gulp deploy" task.
var gulp = require('gulp'),
gutil = require('gulp-util'),
exec = require('gulp-exec');
var spawn = require('child_process').spawn;
var stripDebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');

/**
* Config ogj
*/
var config = {
    jsDir: 'www/assets/js',
    jsDirBrowser: 'platforms/browser/www/assets/js',
    production: !!gutil.env.production
};

/**
* Automatically run 'cordova prepare browser' after any modification
* into the www directory - really useful for development/deplyment purpose
*
* @see watch task
*/
gulp.task('prepare', function () {
    gutil.log('Prepare browser');
    var options = {
        continueOnError: false, // default = false, true means don't emit error event
        pipeStdout: false, // default = false, true means stdout is written to file.contents
        customTemplatingThing: "test" // content passed to gutil.template()
    };
    var reportOptions = {
        err: true, // default = true, false means don't write err
        stderr: true, // default = true, false means don't write stderr
        stdout: true // default = true, false means don't write stdout
    }
    return gulp.src('./**/**')
    .pipe(exec('cordova prepare browser', options))
    .pipe(exec.reporter(reportOptions));

});

/**
* Watch for changes in www
*/
gulp.task('watch', function () {
    gulp.watch('www/**/*', ['prepare']);
});

/**
* Default task
*/
gulp.task('default', ['prepare']);

/**
* Javascript production depolyment.
*/
gulp.task('deploy-js', function () {
    gutil.log('Deploy');
    return gulp.src(config.jsDir + '/*.js')
    .pipe(stripDebug())
    .pipe(uglify())
    .pipe(gulp.dest(config.jsDirBrowser));
});

/**
* Production deployment
* To be run before uploading files to the server with no gulp instaces running
*/
gulp.task('deploy', ['deploy-js']);

Which could be a best practice for develop and deply a Cordova project using Gulp?
[EDIT]
I think the problem is in the "prepare" task: it never returns, probably due a gulp-exec issue, but I really don't know how to debug it.

A: From what I've understood the only issue is that gulp command does not return control to you for you to execute gulp deploy
the prepare task never returns because of the behavior of the watch feature - you've passed control to watch the files so it will return only when you stop watching. It is the expected behavior and not a probably due a gulp-exec issue.
The solution I would adopt in this situation is to run the gulp task in the background, using the native nohup gulp & so that the watching is moved to the background for me to execute deploy.


text:
Q: How to include files in a cron job? I run a cron job on a MediaTemple (gs) hosting, the command is the following:
php5 /home/144061/data/test.php

Inside the php file, and include statement is located.
The cron job returns an error:
Warning: include(../domains/test.com/html/wp-blog-header.php): failed to open stream: No such file or directory in /nfs/c10/h02/mnt/144061/data/delete_seen.php on line 3

Warning: include(): Failed opening '../domains/test.com/html/wp-blog-header.php' for inclusion (include_path='.:/usr/local/php-5.3.15/share/pear') in /nfs/c10/h02/mnt/144061/data/delete_seen.php on line 3

I want to be able to include wordpress header in my cron file so that I can use wordpress functions and database connection in my cron script, what's wrong with my include statement?

A: I resolved with set_include_path('/path/to/my/folder/');
and after
include('my-script.php').

A: If anyone is still struggling with this, please note that your include path must be relative to you CRON path run directory. Otherwise, it won't find the files you're trying to include. For example, in Cpanel, I used the following : require('home/yourdomain/public_html/wp-load.php').
Also, instead of including the header, you should include wp-load.php, which includes all of the core Wordpress functionalities.


text:
Q: Spring Cloud Config server inside a Spring Boot app with MVC I'm inserting a Spring Cloud Config server directly into my existing Spring Boot App, by adding the module dependency and @EnableConfigServer. Everything works as expected except I just realized that the config server URL mapping is hijacking some of my existing API endpoints due to they are sharing the same server.port
For example, I had an existing page at v1/docs/index.html, and this will be now mapped automatically to org.springframework.cloud.config.server.environment.EnvironmentController#labelled which has
    @RequestMapping("/{name}/{profiles}/{label:.*}")
    public Environment labelled(@PathVariable String name, @PathVariable String profiles,

Wondering is there anyway I can separate config server to a different port? Or add a special prefix to it to avoid URL mapping conflicts? Or given the current configurability it's just a bad idea to utilizing existing API servers as a config server?

A: Found the answer I need after reading the document more carefully:)
https://cloud.spring.io/spring-cloud-config/spring-cloud-config.html#_spring_cloud_config_server

To change the location of the server endpoints you can (optionally) set spring.cloud.config.server.prefix, e.g. "/config", to serve the resources under a prefix. The prefix should start but not end with a "/". It is applied to the @RequestMappings in the Config Server (i.e. underneath the Spring Boot prefixes server.servletPath and server.contextPath).


text:
Q: pyowm: Ошибка: 'Weather' object is not callable Попытался написать телеграм бота, который писал бы про погоду в каком-либо городе. Выдаёт ошибку:
Traceback (most recent call last):
  File "main.py", line 19, in <module>
    bot.polling(none_stop=True)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\telebot\__init__.py", line 427,
in polling
    self.__threaded_polling(none_stop, interval, timeout)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\telebot\__init__.py", line 451,
in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\telebot\util.py", line 111, in r
aise_exceptions
    six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\six.py", line 703, in reraise
    raise value
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\telebot\util.py", line 62, in ru
n
    task(*args, **kwargs)
  File "main.py", line 12, in weatherzz
    w = observation.weather()
TypeError: 'Weather' object is not callable

Пробовал:

*

*pip3 uninstall telebot, pip3 install pytelegrambotapi.

Мой код:
from pyowm import OWM
import telebot

bot = telebot.TeleBot('token')
owm = OWM('token')

@bot.message_handler(content_types=['text'])
def weatherzz(message):
    mgr = owm.weather_manager()
    observation = mgr.weather_at_place(message.text)
    w = observation.weather()
    temp = w.temperature('celsius')["temp"]
    answer = "Weather Status: ", w.detailed_status()
    answer += "Temperature: " + str(temp)
    bot.send_message(message.chat.id, answer)

bot.polling(none_stop=True)

A: У Вас ошибки в этой части кода:
w = observation.weather
temp = w.temperature('celsius')['temp']
answer = f'Weather Status: {w.detailed_status}\n'
answer += f'Temperature: {temp}'

*

*observation.weather — это атрибут класса Observation (не метод)

*w.detailed_status — это атрибут класса Weather (не метод)

*answer у Вас является кортежем
Используйте для формирования ответа формат-строки или соответствующий метод.

A: observation.weather это не функция, скобки лишние:
w = observation.weather

A: Вместо observation.weather() попробуйте использовать эти две команды:
w = observation.weather
w.wind()


text:
Q: Best practice for file-based search in rest service I'm helping build a similarity search service for files. One way to search for something is with a GET request, by giving a file's URL, but I also need to allow clients to send the file directly. I have to following options:

*

*Make the client send a GET request with a Payload; it seems this is not recommended -- HTTP GET with request body

*Use something else than GET (maybe a PUT?) for file-based search. The problem is none of the other HTTP methods seems to suit this purpose.
What option would suit best here? I'm not an expert in this field, and I can't figure out what's the right thing to do in this situation.

A: Here is the rule I have always followed with REST.
GET - only querying data and returning a data set.
POST - Creating data in the database
PUT - Modifying data
DELETE - Destroy data in the database.
If you are sending a payload for search params, you can do a GET and put those params (assuming they are name/value pairs) in the query string of the URI.
i.e. http://my.simsearch.com?param1=first&param2=second ...
If you are actually going to change the database then a POST or PUT is in order.
I hope this helps.

A: I ended up sending the payload with a GET request. Even though it's not really recommended, hopefully no libraries will complain about this.


text:
Q: How to print only a first match from each line? I have a file that looks like this:
asd 123 aaa wrqiqirw 123
123 itiewth 123 asno 123
123 132 123 123 123
boagii 123 asdnojaneoienton 123

Expected output is:
123
123
123
123

I will need to search for patterns via regex. Is there any way to implement such a thing?

A: In Perl, simply
perl -lne 'print $& if /\d+/' inputfile

or from stdin:
echo foo 123 bar 456 doo 789 | perl -lne 'print $& if /\d+/'
123

The regex \d+ will match any string of consecutive numbers, and $& refers the matching string.

A: Just a grep should be enough to bring matches of 123 in every line.
It does not makes sense if the match is first ,middle or in the end.
You ask for 123 you get 123 if it is in the line (unless your question is not expressed correctly and you require something different)
$ grep -wo '123' file # -w: word match  -o : return only matched string instead of the whole line (default grep operation)

In case you need to catch with regex the first number of each row (any number - any length) then this will do the job:
cat <<EOF >file1
asd 111 777 aaa wrqiqirw 123
333 123 itiewth 123 asno 123
4444 111 123 123 567
boagii what 666 asdnojaneoienton 123
EOF
grep -Po '^[0-9]+|^.*?\K[0-9]+' file1
#output
111
333
4444
666

A: POSIXLY:
LC_ALL=C sed -e 's/.*\(123\).*/\1/' <file

LC_ALL-C is needed here to prevent sed from crashing or producing unexpected result if the file contained invalid characters in your current locale.
It also produces one entry at a line, but matched the last, not the first.
For matching the first, with ast-open's sed whose EREs support the Perl-style *? non-greedy repetition operator:
LC_ALL=C sed -E 's/.*?(123).*/\1/'

(-E for extended RE will be in next version of POSIX)

A: With grep in every line:
while IFS= read -r line; do printf '%s\n' "$line" | grep -o 123 | head -1; done < filename

That is:

*

*While loop in order to check each line separately.

*grep -o to get only the match instead of the whole line with matches.

*head -1 to take only the first match and not the following ones.

A: sed -e '
   /\n/{P;d;}
   s/12*3/\n&\n/;D
' < inoutfile

A: with awk
re='12*3' awk '{match($0, ENVIRON["re"])}; RSTART{print(substr($0, RSTART, RLENGTH))}' file

A: With pcregrep, with a pattern like 12*3:
pcregrep -o1 '(12*3).*'

With pcregrep or GNU grep -P:
grep -Po '^.*?\K12*3'

(pcregrep works with bytes more than characters, while GNU grep will work on characters as defined in the current locale (and you'd have to make sure the input contains valid text in the current locale)).
Note that GNU grep won't print anything if the pattern matches the empty string.


text:
Q: How to store selected values in useState I am a beginner at React JS. I would like to learn how to store selected values in useState.
The form containts four different drop downs and I want to store this selected values in useState so that at the end of the multi step form, user can go back to edit the fields before sub.
import React, {useState} from 'react';
import './paperdetails.css';
import IncDecCounter from './IncDecCounter'
import {
  Text

} from '@chakra-ui/react';

const PaperDetails = () => {

  const [selected, setSelected] = useState();

  return (

            Type of Paper
            <select>

              <option value="essay">Paraphrasing</option>
              <option value="Custom Writing">Custom Writing</option>
              <option selected value="Dissertation">Dissertation</option>
              <option value="Research Paper">Research Paper</option>
              <option value="essay">Essay</option>
              <option value="Term Paper">Term Paper</option>
              <option selected value="Admission Essay">Admission Essay</option>
              <option value="Coursework">Coursework</option>
              <option value="Book Review">Book Review</option>
              <option selected value="Paraphrasing">Essay</option>
              <option value="Physics Paper">Physics Paper</option>

            </select>

            Study Level
            <select>

              <option value="school">Bachelor</option>
              <option value="college">College</option>
              <option selected value="Bachelor">School</option>
              <option value="Masters">Masters</option>

            </select>

            Number of Pages
            <IncDecCounter />

            Deadline
            <select className='deadline' value={selected} onChange={e=>setSelected(e.target.value)}>
              <option value="1 hour">1 hour</option>
              <option value="3 hours">3 hours</option>
              <option selected value="8 hours">8 hours</option>
              <option value="12 hours">12 hours</option>
              <option value="24 hours">24 hours</option>
              <option value="48 hours">48 hours</option>
              <option selected value="3 days">3 days</option>
              <option value="5 days">5 days</option>
              <option value="7 days">7 days</option>
              <option selected value="14 days">14 days</option>
            </select>
             Will be ready in: {selected}

                Writing instructions
                  *required

              <input className="input-file" id="my-file" type="file"
              accept="application/pdf,application/msword,
              application/vnd.openxmlformats-officedocument.wordprocessingml.document"/>

                  Upload writing Instructions

              <textarea className='text-area_main'
              placeholder='Type your instructions here. Please provide as many details as possible.'></textarea>

Total:

            $0.00

  )
}

export default PaperDetails;

A: How to store multiple values in state
to do this ,you will need to define state for all four select box like this
const [seleccedValue1,setSelectedValue1]=useState(null);
const [seleccedValue2,setSelectedValue2]=useState(null);
const [seleccedValue3,setSelectedValue3]=useState(null);
const [seleccedValue4,setSelectedValue4]=useState(null);

then you will need to handle on change event of each select box like this
       <select onChange={(e)=>{setSelectedValue1(e.target.value)}}>

          <option value="essay">Paraphrasing</option>
          <option value="Custom Writing">Custom Writing</option>
          <option selected value="Dissertation">Dissertation</option>
          <option value="Research Paper">Research Paper</option>
          <option value="essay">Essay</option>
          <option value="Term Paper">Term Paper</option>
          <option selected value="Admission Essay">Admission Essay</option>
          <option value="Coursework">Coursework</option>
          <option value="Book Review">Book Review</option>
          <option selected value="Paraphrasing">Essay</option>
          <option value="Physics Paper">Physics Paper</option>

        </select>

you can do the same for other select boxes as well

A: Here is how you store value of any input field in useState();
const [selected,setSelected] = useState({});
function handleChange(event){
    setSelected({...selected,[event.targe.id]=event.target.value});
}
return(
<select
     id={"id_0"}
     value={selected["id_0"]}
     onChange={(event)=>(handleChange(event))}>

......."your code continue here"
and here is how you handle multiple input fields.
<select  id={'id_1'}  value={selected['id_1']}
         onChange={(event)=>(handleChange(event))}/>
   <select  id={'id_2'} value={selected['id_2']}
         onChange={(event)=>(handleChange(event))}/>

A: Please checkout this question:
It was already answered here:
React JSX: selecting "selected" on selected <select> option


text:
Q: How to get the contents from a URL which is passed as a request parameter I am trying to get the contents from an external URL in my GET call like
http://localhost:8080/getinfo?url=http://hello-ext.com/Serving?cn=display&c=23&pl=VAST&pli=21933633&PluID=0&pos=4729&ord=[timestamp]&cim=1
However, when I debug, I can see the URL is getting truncated to
http://hello-ext.com/Serving?cn=display
omitting the contents after the first '&'. How can I pass the entire URL for my GET method so that I get
String URL = http://hello-ext.com/Serving?cn=display&c=23&pl=VAST&pli=21933633&PluID=0&pos=4729&ord=[timestamp]&cim=1

A: Try
String url="http://hello-ext.com/Serving?cn=display&c=23&pl=VAST&pli=21933633&PluID=0&pos=4729&ord=[timestamp]&cim=1";
String encodedurl=URLEncoder.encode(url,"UTF-8");