text:
Q: Java: why does it take several seconds to check if a file exists on an inaccessible Windows drive? Checking for an existing file using any available method is usually very fast, but if the file path includes an inaccessible (network) drive, the check takes several seconds.
Checking for a non-existent drive is no problem ("R:" in the code sample), but checking a known drive that is no longer accessible ("S:"  in the code sample) takes very long time.
Edit: this has a significant effect both when validating a list of recent files (multiply each inaccessible file by 2-4 seconds) and when opening the standard JFileChooser(), which can take 1-2 minutes with a few disconnected drives.
Questions:

*

*Is this a known problem?

*Is there a workaround?

Context:
Java 11 or 17 on Windows 10 with an existing "C:" drive, a non-existent "R:" drive, and a network drive "S:" that is not accessible.
Sample code:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;

public class FileSystemExperiment {

   private static final String[] FILES = {
      System.getProperty("user.home"), // home dir exists
      "/no/such/file",                 // missing file on current drive
      "C:\\no\\such\\file",            // missing file on existing drive
      "R:\\",                          // an unknown drive
      "S:\\",                          // a known but inaccessible drive
   };

   private static long started;

   private static void exists(String... pathStrings) {
      for (String pathString : pathStrings) {
         File file = new File(pathString);
         Path path = file.toPath();
         System.out.printf("%nFile '%s' ...%n", file);

         started = System.currentTimeMillis();
         time("file.exists()", file.exists());
         time("file.lastModified()>0", file.lastModified() > 0);
         time("Files.exists(path)", Files.exists(path));
         time("Files.readAttributes(path)", readAttributes(path) != null);
      }
   }

   private static void time(String msg, boolean exists) {
      System.out.printf("%-30s | %-5s | time=%s ms%n", msg, exists, System.currentTimeMillis() - started);
      started = System.currentTimeMillis();
   }

   private static BasicFileAttributes readAttributes(Path path) {
      try {
         return Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
      }
      catch (IOException e) {
         return null;
      }
   }

   public static void main(String[] args) {
      exists(FILES);
   }
}

Output:

File 'C:\Users\p2r' ...
file.exists()                  | true  | time=1 ms
file.lastModified()>=0         | true  | time=0 ms
Files.exists(path)             | true  | time=2 ms
Files.readAttributes(path)     | true  | time=0 ms

File '\no\such\file' ...
file.exists()                  | false | time=0 ms
file.lastModified()>=0         | false | time=0 ms
Files.exists(path)             | false | time=1 ms
Files.readAttributes(path)     | false | time=0 ms

File 'C:\no\such\file' ...
file.exists()                  | false | time=0 ms
file.lastModified()>=0         | false | time=0 ms
Files.exists(path)             | false | time=1 ms
Files.readAttributes(path)     | false | time=1 ms

File 'R:\' ...
file.exists()                  | false | time=0 ms
file.lastModified()>=0         | false | time=0 ms
Files.exists(path)             | false | time=0 ms
Files.readAttributes(path)     | false | time=0 ms

File 'S:\' ...
file.exists()                  | false | time=7802 ms
file.lastModified()>=0         | false | time=10067 ms
Files.exists(path)             | false | time=7171 ms
Files.readAttributes(path)     | false | time=10047 ms

A: Q1: Yes, this is a known problem, reported in 1999 but still not resolved. See https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4260746:
Situation: You have connections to other computers in Win NT and these computers are not online. You start a JAVA-application (jdk1.2.1) with a JFileChooser. The dialog tries to "see" all the connected computers. Because some other computers are not avaiable, the filechooser-dialog appears after reaching the timeout. It may take 60 to 120 seconds until the dialog appears.
WORK AROUND:
Close the network-connections to the computers that are not  avaiable. The dialog appears just after invoking.
EVALUATION: This is an important performance problem and should be addressed in a not too distant release.
Q2: No, there are no feasible workarounds.
See How can I make JFileChooser behave properly with disconnected network drives?
It seems like it would be a common problem, but I can't find a way to work around it. Possible options I've seen are:

*

*use JFileDialog; replace FileSystemView with one where getRoots() returns a fixed list of drives

*switch to a WAIT cursor before trying to open JFileChooser(s)

*create a JFileChooser at startup and keep it around forever

*try using xfiledialog
In addition to the options mentioned above:

*

*Check and cache availability of all drives using a background thread with a timeout

*Wrap all calls to file operations (e.g. file.exists()) in methods that check the availability of the drive before delegating the call to the file

*Instantiate the JFileChooser with a custom FileSystemView that wraps the default FileSystemView (FileSystemView.getFileSystemView()) and checks the drive status before delegating calls to the wrapped view


text:
Q: A proof of Helly's Intersection Theorem by induction Good evening, I'm reading about the proof of Helly's Intersection Theorem:

The author applies the inductive hypothesis to $D_{1}, \ldots, D_{n-1}$ where $D_{i}=C_{i} \cap H$ for all $i=1, \ldots, n-1$. To apply the inductive hypothesis, we need $D_{i}=C_{i} \cap H \neq \emptyset$ for all $i=1, \ldots, n-1$.
My question: How does it follow that $D_{i}=C_{i} \cap H \neq \emptyset$ for all $i=1, \ldots, n-1$?
Thank you so much for your help!

A: For each $i=1, \ldots, n-1$ the set $C_i$ intersects both the $>a$ and the $<a$ sides of $H$, and hence $C_i$, being convex, must also intersect $H$.
Note that $C_i$ intersects the $>a$ side of $H$ because $C_i$ intersects $C_{-n}$.
(Clearly $C_{-n}=\cap_{j\neq n}C_j\subseteq C_i$ so $C_i\cap C_{-n}=C_{-n}$, and $\emptyset\not=C_{-n}$ by hypothesis.)
On the other hand, $C_i$ intersects the $<a$ side of $H$ because $C_i$ intersects
$C_n$, because $i\not=n$ and $|\{i,n\}|=2<n\ge3$.
(Pick $k<n$ with $k\neq i$, then $\emptyset\neq\cap_{j\neq k}C_j\subseteq C_i\cap C_n$.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to center an inline div using css? How can I center an inline div (not its content) using css?
VERY IMPORTANT: the width of the div is unknown (I can not specify it)

A: This is the easiest and most straightforward solution
.center {
  display: table;
  margin: auto;
}

A: If by inline you mean, its CSS display property is set to inline then you can center it by giving the immediate parent container a text-align:center
If you mean a div within another div, you can follow this approach if you can add a wrapper and float both:
How to horizontally center a floating element of a variable width?

A: Wrap it into a div that you can specify the width of and then set the margins of the div in question to: margin: 0, auto;

A: you can probably get away with display:inline-block and text-align:center; on the parent element if you want it it to be "blocky". also you'll probably need to give it a vertical-align:top

A: I solved this.
You should add new div with text-align:center outside your divlike this

which not in center with inline display


text:
Q: how to solve? Expected identifier or '('? I am trying to create a cancel code to webView coming back with other website information. So i am first trying to create the delegate, but i keep getting the following error.
Expected identifier or '('
The error is placed below.
@implementation ViewController
@synthesize webView;

{                                             // Expected identifier or '('

(webView.delegate = nil)

}

- (void)viewDidLoad

{
    [super viewDidLoad];

    NSURL *url = [NSURL URLWithString:@"https://twitter.com/u_bett"];

    NSURLRequest *urlrequest = [NSURLRequest requestWithURL:url];

    [webView loadRequest:urlrequest];

A: This code:
{                                             // Expected identifier or '('

(webView.delegate = nil)

}

Is in the middle of nowhere, it should be inside a method.
What are you trying to achieve?
edited after the comments:
- (void)viewDidLoad

{
    [super viewDidLoad];
    webView.delegate = nil;


text:
Q: controller create method to accept JSON in post route Basically I have a 'requests_controller' with a create method. I'm supposed to add a POST route that lets the create method accept JSON. I'm kind of confused on how the routing part works. Please help!
We don't need a model or any views.  Basically, the controller should accept some JSON like
{url: "http://some-url.com", origin: "some-value-i-will-figure-out-later"}
I have this in my routes.db, but i'm not sure what to put right after the post.
post '' => 'requests#create', :defaults => { :format => 'json' }

A: You can try this out
In routes.rb
post '/requests', to: 'requests#create', :defaults => { :format => 'json' }

Your controller logic
class RequestsController < YourBaseClass
  def create
    #your logic - something like give below
    if @object.save
      render json: { success: t(:success_message) }, status: :ok
    else
      render json: { errors: @object.errors.joins(', ') }, status: :unprocessable_entity
  end
end

Hope this helps.


text:
Q: Preserve whitespace-only element content when deserializing XML using XmlSerializer I have a class InputConfig which contains a List<IncludeExcludeRule>:
public class InputConfig
{
    // The rest of the class omitted
    private List<IncludeExcludeRule> includeExcludeRules;
    public List<IncludeExcludeRule> IncludeExcludeRules
    {
        get { return includeExcludeRules; }
        set { includeExcludeRules = value; }
    }
}

public class IncludeExcludeRule
{
    // Other members omitted
    private int idx;
    private string function;

    public int Idx
    {
        get { return idx; }
        set { idx = value; }
    }

    public string Function
    {
        get { return function; }
        set { function = value; }
    }
}

Using ...
FileStream fs = new FileStream(path, FileMode.Create);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(InputConfig));
xmlSerializer.Serialize(fs, this);
fs.Close();

... and ...
StreamReader sr = new StreamReader(path);
XmlSerializer reader = new XmlSerializer(typeof(InputConfig));
InputConfig inputConfig = (InputConfig)reader.Deserialize(sr);

It works like a champ! Easy stuff, except that I need to preserve whitespace in the member function when deserializing. The generated XML file demonstrates that the whitespace was preserved when serializing, but it is lost on deserializing.
<IncludeExcludeRules>
  <IncludeExcludeRule>
    <Idx>17</Idx>
    <Name>LIEN</Name>
    <Operation>E =</Operation>
    <Function>  </Function>
  </IncludeExcludeRule>
</IncludeExcludeRules>

The MSDN documentation for XmlAttributeAttribute seems to address this very issue under the header Remarks, yet I don't understand how to put it to use. It provides this example:
// Set this to 'default' or 'preserve'.
[XmlAttribute("space",
Namespace = "http://www.w3.org/XML/1998/namespace")]
public string Space

Huh? Set what to 'default' or 'preserve'? I'm sure I'm close, but this just isn't making sense. I have to think there's just a single line XmlAttribute to insert in the class before the member to preserve whitespace on deserialize.
There are many instances of similar questions here and elsewhere, but they all seem to involve the use of XmlReader and XmlDocument, or mucking about with individual nodes and such. I'd like to avoid that depth.

A: To preserve all whitespace during XML deserialization, simply create and use an XmlReader:
StreamReader sr = new StreamReader(path);
XmlReader xr = XmlReader.Create(sr);
XmlSerializer reader = new XmlSerializer(typeof(InputConfig));
InputConfig inputConfig = (InputConfig)reader.Deserialize(xr);

Unlike XmlSerializer.Deserialize(XmlReader), XmlSerializer.Deserialize(TextReader) preserves only significant whitespace marked by the xml:space="preserve" attribute.

A: The cryptic documentation means that you need to specify an additional field with the [XmlAttribute("space", Namespace = "http://www.w3.org/XML/1998/namespace")] whose value is default or preserve. XmlAttribute controls the name of the generated attribute for a field or property. The attribute's value is the field's value.
For example, this class:
public class Group
{
   [XmlAttribute (Namespace = "http://www.cpandl.com")]
   public string GroupName;

   [XmlAttribute(DataType = "base64Binary")]
   public Byte [] GroupNumber;

   [XmlAttribute(DataType = "date", AttributeName = "CreationDate")]
   public DateTime Today;

   [XmlAttribute("space", Namespace = "http://www.w3.org/XML/1998/namespace")]
   public string Space ="preserve";
}

Will be serialized to:
<?xml version="1.0" encoding="utf-16"?>
<Group xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:xsd="http://www.w3.org/2001/XMLSchema"
       d1p1:GroupName=".NET"
       GroupNumber="ZDI="
       CreationDate="2001-01-10"
       xml:space="preserve"
       xmlns:d1p1="http://www.cpandl.com" />

A: I believe the part you are missing is to add the xml:space="preserve" to the field, e.g.:
<Function xml:space="preserve">   </Function>

For more details, here is the relevant section in the XML Specification
With annotation in the class definition, according to the MSDN blog it should be:
[XmlAttribute("space=preserve")]

but I remember it being
[XmlAttribute("xml:space=preserve")]

A: Michael Liu's answer above worked for me, but with one caveat. I would have commented on his answer, but my "reputation" is not adequate enough.
I found that using XmlReader did not fully fix the issue, and the reason for this is that the .net property in question had the attribute:
XmlText(DataType="normalizedString")

To rectify this I found that adding the additional attribute worked:
[XmlAttribute("xml:space=preserve")]

Obviously, if you have no control over the .net class then you have a problem.


text:
Q: Проверить на PHP введенное число на соответствие 1, 10, 100, ..., 10 000 000 Как математически проверить пользовательский ввод: соответствует ли число одному из заданной последовательности: 1, 10, 100, ..., 10 000 000 на PHP. Проверить с помощью preg_match() - не проблема, но как-то не правильно проверять числа функцией, предназначенной для проверки строк.
if (!preg_match('/^10{0,7}$/', $_GET['insert_number'])) {
    echo 'число должно быть 1, 10, 100, 1000 и т.д.';
}

Как назвать последовательность чисел 1, 10, ..., чтобы сообщение об ошибке было более информативным?

A: Всего 8 вариантов, отчего бы не захардкодить? =)
in_array($userInput, [1,10,100,1000,10000,100000,1000000,10000000]);

Ещё странный вариант: смотреть на валидные числа как на двоичные – там ведь только единицы и нули допустимы, длиной не более байта (8 позиций).
function is10x($userInput) {
    $input = trim($userInput); // убрать пробелы по краям и считать строкой
    $binStr = sprintf('%b', intval($input,2)); // перевести в двоичное число и в строку единиц и нулей
    if( $binStr !== $input) return FALSE; // должно пережить двойной перевод без потерь
    return array_sum(str_split($binStr)) === 1; // должно содержать только одну 1
}

Тесты
Сообщение: «Число должно начинаться с единицы и, кроме неё, может содержать только нули»

A: Можно проверить через логарифм, но при этом нужно учитывать что функции log() и log10() всегда возвращают число типа float. Можно применить такой хак:
$y = 10;
$x = pow((string)log10($y),1);

результат работы log10() перегоняем в строку и скармливаем функции pow(), которая выдает int или float в зависимости от полученного результата
if (is_float($x) || $y < 1)
echo "Число не удовлетворяет условию";

var_dump($x);

A: Написал на Java, т.к не пользуюсь PHP
//Проверка на то, является ли число одной из степеней 10:
public boolean is10(int n) {
    if(n==1) return true;
    else if(n<1) return false;
    return n%10==0 && is10(n/10);
}

Ну и попытался конвертировать на PHP:
function is10($n): boolean {
    if ($n == 1) {
        return true;
    } elseif ($n < 1) {
        return false;
    }

    return $n % 10 == 0 && is10($n / 10);
}

A: нельзя ли сделать простым циклом? так как максимальное число 10 000 000
// Функция проверки цисла
function proveritChislo($number){
  // Если число больше 1 можно работать
  while ( $number > 1 ) {
    // Если не заканчивается на 0, значит не правильно
    $ostatok = $number % 10;
    if ($ostatok != 0) {
      return FALSE;
    }
    // убираем последний 0
    $number = ($number - $ostatok) / 10;
  }
  return $number == 1;
}

A: $test="1".str_repeat("0",strlen($input)-1);
if($test % $unput != 0) echo "Ошибка бла-бла-бла";


text:
Q: Converting days/hours/minutes/seconds to hours/minutes/seconds I have a timesheet application that shows how many hours were worked within a given timespan. It works perfectly but when I want to display to total hours worked it shows me this format after 24 hours have been worked: 1.01:06:16. I need to convert this to this format: 25:06:16. I searched but only found every other conversion but not the one I need The table "timespan" is in TIME format. Here is my code:
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
        MySqlConnection con = new MySqlConnection(conSettings.ToString());
        MySqlCommand cmd = new MySqlCommand(@"select timespan as 'Temps' from shopmanager.time_sheet where project_number = @project_number and users_employee_number = @users_employee_number and week_number = @week_number;", con);

cmd.Parameters.AddWithValue("@project_number", username.default_project);
            cmd.Parameters.AddWithValue("@users_employee_number", username.user_id);

            cmd.Parameters.AddWithValue("@week_number", GetWeekNumber());
            DataTable dt = new DataTable();
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            da.Fill(dt);

            object sum;
            sum = dt.Compute("Sum(Temps)", "");
            textBox1.Text = sum.ToString();
            cmd.Parameters.Clear();

Being new to this, I can't seem to figure it out. If someone could help me out, it would be great.
Thanks

A: I found out how to do it. Here is the final code:
object sum;
            sum = dt.Compute("Sum(Temps)", "");
            TimeSpan time = TimeSpan.Parse(sum.ToString());
            string timeForDisplay = (int)time.TotalHours + time.ToString(@"\:mm\:ss");
            textBox1.Text = timeForDisplay;

That works perfectly.


text:
Q: Import a Python module without adding it to the local namespace What I'd like to do
I'd like to import a Python module without adding it to the local namespace.
In other words, I'd like to do this:
import foo
del foo

Is there a cleaner way to do this?
Why I want to do it
The short version is that importing foo has a side effect that I want, but I don't really want it in my namespace afterwards.
The long version is that I have a base class that uses __init_subclass__() to register its subclasses. So base.py looks like this:
class Base:
    _subclasses = {}

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls._subclasses[cls.__name__] = cls

    @classmethod
    def get_subclass(cls, class_name):
        return cls._subclasses[class_name]

And its subclasses are defined in separate files, e.g. foo_a.py:
from base import Base

class FooA(Base):
    pass

and so on.
The net effect here is that if I do
from base import Base

print(f"Before import: {Base._subclasses}")

import foo_a
import foo_b

print(f"After import: {Base._subclasses}")

then I would see
Before import: {}
After import: {'FooA': <class 'foo_a.FooA'>, 'FooB': <class 'foo_b.FooB'>}

So I needed to import these modules for the side effect of adding a reference to Base._subclasses, but now that that's done, I don't need them in my namespace anymore because I'm just going to be using Base.get_subclass().
I know I could just leave them there, but this is going into an __init__.py so I'd like to tidy up that namespace.
del works perfectly fine, I'm just wondering if there's a cleaner or more idiomatic way to do this.

A: If you want to import a module without assigning the module object to a variable, you can use importlib.import_module and ignore the return value:
import importlib

importlib.import_module("foo")

Note that using importlib.import_module is preferable over using the __import__ builtin directly for simple usages. See the builtin documenation for details.


text:
Q: Watir webdriver: uploading files isn't working in SAFARI browser? I am trying to attach file to upload with form in safari browser. Element is searchable but file is not attached.
<input type="file" id="file" name="file" maxlength="255" onchange="copyfile();" style="width: 59px; ">

using following command
b.file_field( :id=>"file" ).set "/Users/......../Desktop/abc"
returns
=> "/Users/......../Desktop/abc"

but file not populate in file field
Any ideas?

A: Issue 4220: The SafariDriver does not support file uploads


text:
Q: Prevent a file to access if for .htaccess: DirectoryIndex if might be very weird question.
I have this:
DirectoryIndex index.php wait.php

the rule is the following: load index.php, the normal site if everything is OK. But in case is a cache is being rewrited, load the wait.php, which consits a "page will loads in some seconds, be patient".
Im trying to lock the index.php:
$f = fopen('index.php', 'r');
flock($f, LOCK_EX | LOCK_NB);
sleep(10); // so cache is beign writed

and when this file ends, lock will be nullified. But this idea doesnt work: I cant open the index.php in Total Commander BUT from another browser appache will load index.php. So its not locked from it after all.

A: DirectoryIndex will only try the next file in the list if the previous file is missing.
Your index.php is not missing, it's simply locked.
You should use your index.php to handle the logic of which file to use, or could even use another script to move or rename the index.php whilst it is being cached.


text:
Q: Additional mask files I used the tool "Extract by Mask" to clip a raster. It resulted in 5 tif images: mask, maskc1, maskc2, maskc3, and maskc4. What are the maskc1-4 files? They're large and I'd like to delete them if they won't effect my normal mask tif. I'm trying to preview them in ArcCatalog but it's taking forever to build pyramids.

A: If anyone is ever wondering the same thing, I deleted them and there were no issues.


text:
Q: How to find the distinct of one column based on other columns I have a data frame like below
col1    col2    col3
A       Z       10
A       Y       8
A       Z       15
B       X       11
B       Z       7
C       Y       10
D       Z       11
D       Y       14
D       L       16

I have to select, for each distinct col1 which of the col2 have max(col3)
Output data frame should look like,
col1    col2    col3
A       Z       15
B       X       11
C       Y       10
D       L       16

How to do this either in R or in SQL
Thanks in advance

A: We can use data.table.  We convert the 'data.frame' to 'data.table' (setDT(df1)), grouped by 'col1', we subset the data.table (.SD) based on the index of max value of 'col3'
library(data.table)
setDT(df1)[, .SD[which.max(col3)], col1]
#     col1 col2 col3
#1:    A    Z   15
#2:    B    X   11
#3:    C    Y   10
#4:    D    L   16

Or we can use top_n from dplyr after grouping by 'col1'.
library(dplyr)
df1 %>%
      group_by(col1) %>%
      top_n(1)

A: SQL answer:
Use NOT EXISTS to return a row if there are no other row with same col1 value that has a higher col3 value.
select *
from tablename t1
where not exists (select 1 from tablename t2
                  where t2.col1 = t1.col1
                    and t2.col3 > t1.col3)

Will return both rows for a col1 if there's a max(c3) tie.

A: Another way of doing in MySQL.
Here is the SQLFiddle Demo
Output : =>
SELECT T1.*
FROM
table_name T1
INNER JOIN
(SELECT col1,MAX(col3) AS Max_col3 FROM table_name GROUP BY col1) T2
            ON T1.`col1` = T2.`col1` and T2.`Max_col3`=t1.`col3`

Hope this helps.


text:
Q: Create Dynamic Rege in Runtime Friends its possible to create javascript dynamic regex at runtime. i create this regex:
[+]?\(?800\)?[+ .]?123?[+ .]?1234

for this 800.123.1234 number. This regex can found/accept this number on page in any format
like:
(800).123.1234
+(800)1231234
+(800)1231234
(800).123.1234
800.123.1234
800.123.1234

Its work fine but i need to create rejex dynamic depends on any number that i feed in input text field. here is my working code example:
http://jsfiddle.net/webdesignerart/ShbMv/
means if two numbers i have on page
800.123.1234 and 855.455.4577
i add this 855.455.4577 number to input text field
then regex have to create dynamic or parse
[+]?\(?800\)?[+ .]?123?[+ .]?1234

in this regex to find this 855.455.4577.

A: You can create your own regular expression object anytime using the new RegExp(str) syntax.
var str = "[+]?\\(?800\\)?[+ .]?123?[+ .]?1234";
var re = new RegExp(str);
re.exec("800.123.1234");

Note, you may need double backslashes on some declarations in order to allow a single backslash to survive into the regular expression constructor.
But, if I really understood what you were doing, there is probably a single regular expression that can be created in advance that will match what you need to match.   For example, you could match all the phone numbers you have in your list with this:
\+?\(?\d\d\d\)?\.?\d\d\d\.?\d\d\d\d

zero or one plus sign
zero or one left paren
3 digits
zero or one right paren
zero or one period
three digits
zero or one period
four digits

Here's a jsFiddle that tests all your test numbers against a regular expression and extracts just the numbers out of each form to make a normalize phone number form: http://jsfiddle.net/jfriend00/43mqV/.  It uses this regular expression:
\+?\(?(\d\d\d)\)?\.?(\d\d\d)\.?(\d\d\d\d)

This is the same as above, but it also captures each group of numbers so we can pick out just the numbers from the matched results.

A: Use \d where for the digits that can be any of 0 - 9.


text:
Q: Html Display apex chart in ContentFlow I am using ContentFlow library to display objects as cover flow view. When I am displaying images , it is working fine . But on using apex charts its view is getting disturbed. Is there any way to display apex charts in proper format using ContentFlow library?
Please provide some solid solution. I tried many things but they did not work


text:
Q: HTML canvas element creating undesired white border There's probably a real simple explanation for this, but I'm struggling really hard to find it. I'm trying to implement a crop picture feature and I'm getting an undesired border on the right and bottom sides of the picture, as seen here: http://imgur.com/Xjtk39K. I think I've narrowed it down to something having to do with the first image translation that happens when I crop the picture. Here's the applicable code (the doubling of the cropped image size in submitPhotoUpload is due to some unknown halving of the picture height in my code. Advice for that would be welcome too):
cropPhoto: function(evt){

    var formType = App.UploadPhotoView.whichForm;

    var canvas = document.getElementById("crop-canvas-preview-"+formType);
    var context = canvas.getContext("2d");
    if(this.canvasHidden){
        canvas.style.display = 'inline';
        App.UploadPhotoView.canvasHidden = false;
    }

    var x1 = App.UploadPhotoView.x1;
    var y1 = App.UploadPhotoView.y1;
    var width = App.UploadPhotoView.width;

    var previewSize = $("#upload-div-"+formType).height() * 0.25;
    var resizeX = App.UploadPhotoView.scalingFactorX;
    var resizeY = App.UploadPhotoView.scalingFactorY;
    var img = document.getElementById("preview-photo-"+formType);

    context.clearRect(0, 0, previewSize, previewSize);
    context.drawImage(img, x1*resizeX, y1*resizeY, width*resizeX,
                      width*resizeY, 0, 0, previewSize*2, previewSize);
},

submitPhotoUpload: function(){
    var formType = "pic";
    if ($('#preview-photo-'+formType).attr('src') != '#') {
        var uploadImage = new Image();
        uploadImage.src = document.getElementById('crop-canvas-preview-'+formType).toDataURL();

        var canvas = document.createElement('canvas');
        canvas.width = uploadImage.width * 3;
        canvas.height = uploadImage.height * 6;

        canvas.getContext('2d').drawImage(uploadImage, 0, 0, canvas.width, canvas.height);

        var newPhoto = App.Photo.createRecord({
            filename: canvas.toDataURL(),
            location: this.get('location'),
            description: this.get('description')
        });
        this.get('store').commit();
        resetPhotoUpload(formType);
    }else{
        this.set('submissionFailed', true);
    }
},

A: The reason is that you are using fractional values with the clearing and clipping.
The clearRect call will clear on sub-pixel basis which means it can leave "half" pixel clipped.
The clip however cannot clip the image with sub-pixels as images are pixel based and will truncate the value to match an integer value, hence you get a small gap in the final result.
Luckily this is easy to get around by simply forcing the values to integer values:
ONLINE DEMO HERE
context.clearRect(0, 0, previewSize|0, previewSize|0);
context.drawImage(img, (x1*resizeX)|0, (y1*resizeY)|0, (width*resizeX)|0,
                  (width*resizeY)|0, 0, 0, previewSize|0, previewSize|0);

Of course, you might consider doing this outside the function call. If you need a more accurate rounding just add 0.5 to the values before doing as here, shifting 0 bits (which force a float number to integer) or use Math.round() instead.
Here is the result:

left: cleared and clipped using frational positions, right: using integer values


text:
Q: Read CSV and Upload Data to Elasticsearch I am iterating the rows one by one of a csv file and I want to insert it into es. I'm new to both python and elastic search.How to convert one csv row and insert it into es one by one

import csv
import json

from elasticsearch import Elasticsearch

es = Elasticsearch(
  [{'host': 'localhost', 'port': 9200}])
 print(es)

def csv_reader(file_obj, delimiter=','):
   reader = csv.reader(file_obj)
   i = 1
   results = []
   for row in reader:
    print(row)
    es.index(index='product', doc_type='prod', id=i,
   body=json.dump([row for row in reader], file_obj))
    i = i + 1
    results.append(row)
    print(row)

 if __name__ == "__main__":
  with open("/home/Documents/csv/acsv.csv") as f_obj:
    csv_reader(f_obj)

But I'm getting this error:

Traceback (most recent call last):
File "/home/PycharmProjects/CsvReaderForSyncEs/csvReader.py", line 25, in  csv_reader(f_obj)
File "/home/PycharmProjects/CsvReaderForSyncEs/csvReader.py", line 17, in csv_reader
es.index(index='product', doc_type='prod', id=i, body=json.dump([row for row in reader], file_obj))
File "/usr/lib/python2.7/json/init.py", line 190, in dump fp.write(chunk)
IOError: File not open for writing

A: Try bulk API.
import csv
from elasticsearch import helpers, Elasticsearch

def csv_reader(file_name):
    es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
    with open(file_name, 'r') as outfile:
        reader = csv.DictReader(outfile)
        helpers.bulk(es, reader, index="index_name", doc_type="type")

for more information about bulk API
https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html

A: The problem is that you are passing file_obj as a parameter for json.dump but the file is only opened for reading. Check the mode parameter for the open function in this link.
Also check the first parameter for the json.dump function, [row for row in reader] gets all the rows in the csv file, but probably you just want to pass one row, so the parameter should be row.
And json.dump writes to a file, probably you should use the json.dumps function, check here

A: can you try this.
Change reader to DictReader and json.dumps(row).
DictReader make input data is python dict. And for in is loop each row in reader, you just try push row is enough
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
print(es)

def csv_reader(file_obj, delimiter=','):
    reader = csv.DictReader(file_obj)
    i = 1
    results = []
    for row in reader:
        print(row)
        es.index(index='product', doc_type='prod', id=i,
                         body=json.dumps(row))
        i = i + 1

        results.append(row)
        print(row)

if __name__ == "__main__":
    with open("/home/Documents/csv/acsv.csv") as f_obj:
        csv_reader(f_obj)


text:
Q: Localizing SQL in Android I'm preparing database definition class for my application. Let me abbreviate it a little:
public class DatabaseDefinition {

     public static class Table {

         public static final String TABLE_NAME = "MyTable";

         public static final int ID_FIELD = "ID";
         public static final String DATA_FIELD = "Data";

         public static final String CREATE_SQL = "CREATE TABLE " + TABLE_NAME + "(" +
             ID_FIELD + " INTEGER PRIMARY KEY," +
             DATA_FIELD + " TEXT)";

         public static String getCreateSql() {

             return CREATE_SQL;
         }
     }
}

I'd like to add some data to this table when the database is being created (very few, like max. 10 entries). The problem is, that this data must be localized. I may store appropriate entries in resources, but I'm not aware of any way of accessing resources without context and I have none in onCreate event of my DatabaseHelper:
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {

    database.execSQL(DatabaseDefinition.GetCreateSql());
}

How can I access resources from here? Or how else should I solve this problem?

A: Use Context.getApplicationContext() or implement own class extending Application, as described here: Using Application context everywhere?


text:
Q: Streamlining the process of running multiple requests at once I have plans for a website which clunkily enough needs to scrape multiple websites at once. I'm thinking of how I can make that as fast as possible, but I don't really know how.
I'm using PHP Simple HTML DOM Parser to scrape a few websites for certain items. It looks something like this:
$html = file_get_html($fullUrl);

$collection = $html->find('div.info');

If I wanna scrape multiple sites at once, can I streamline the scraping process by branching it out  to different PHP-documents, perhaps with separate simple_html_dom.php documents? Where page A makes one request to page B and C each, which individually return data to page A. Will they run simultaneously or just queue up?
I've looked in to PHP-multithreading, and come to the conclusion that it's yet a little bit advanced, and I don't quite understand how to implement the existing templates to my particular code setup.
Any ideas will be highly appreciated. Thank you in advance.

A: If I were you I would definitely look into parallel processing in PHP regardless of what you perceive to be "advanced"
Here is some pseudocode of the general idea:
while(hasMoreSitesForScrapingInQueue){
     if(numOfCurrentlyRunningProcesses < maxNumberOfProcesses){
          // create new process that invokes file_get_html() and completes associated logic
     }
}


text:
Q: Enum Parse C++ Or Analog In C# use code:
enum COMPUTER_NAME_FORMAT
{
        ComputerNameNetBIOS,
        ComputerNameDnsHostname,
        ComputerNameDnsDomain,
        ComputerNameDnsFullyQualified,
        ComputerNamePhysicalNetBIOS,
        ComputerNamePhysicalDnsHostname,
        ComputerNamePhysicalDnsDomain,
        ComputerNamePhysicalDnsFullyQualified
}

string format = "ComputerNameDnsFullyQualified";
(COMPUTER_NAME_FORMAT)Enum.Parse(typeof(COMPUTER_NAME_FORMAT), format)

How use this in C++ ?

A: There is no such function in C or C++. But you can make a std::map<std::string, COMPUTER_NAME_FORMAT> m that does that.
Fill the map by doing m["ComputerNameNetBIOS"] = ComputerNameNetBIOS; etc.
Then use auto f = m.find(format); if (f != m.end()) { ... value is in f.second ... }


text:
Q: Display the city name which has most number of branches I have tried to get city name which has most number of branches .
select C.City_name ,count(B.B_Name)
from tblcity C
inner join
tblBranch B
on c.city_id=B.City_id
group by C.City_name
order by count(B.B_Name) desc

Above code will give me the count of branches for particular city .
Please help me solve to get city name which has most number of branches

A: you can add TOP 1 to your query
select TOP 1 C.City_name ,count(B.B_Name)
from tblcity C
inner join
tblBranch B
on c.city_id=B.City_id
group by C.City_name
order by count(B.B_Name) desc

A: Use DENSE_RANK():
SELECT
    City_Name, cnt
FROM
(
    SELECT
        c.City_name,
        COUNT(b.B_Name) cnt,
        DENSE_RANK() OVER (ORDER BY COUNT(b.B_Name) DESC) dr
    FROM tblcity c
    INNER JOIN tblBranch b
        ON b.city_id = c.City_id
    GROUP BY c.City_name
) t
WHERE dr = 1;

Using TOP 1 WITH TIES would be another option here, but that is specific to SQL Server.


text:
Q: Evaluate Ember template programmatically I need to evaluate an Ember Template programmatically, so that I can generate the HTML that results by evaluating the Ember template within a supplied context.
I want to use this generated HTML to insert into a google maps InfoWindow (small modal that appears when you click on a marker.)
All of the variables will be unbound.
I have tried
Ember.TEMPLATES['templateName']( {context: 'suppliedHere})

but this expects a Ember.RenderBuffer to exist in the data.buffer object

A: Here's another solution, inside your Ember view/component:
var viewClass = Ember.View.extend({ templateName: this.get('contentTemplate') });
var view = this.createChildView(viewClass);
var html = view.renderToBuffer().buffer;

A: Ember uses Handlebars.js for templating.
If you have the template as a string you can use Handlebars directly:
var template = 'Hi {{name}}';
var context = {name: 'John'};
Handlebars.compile(template)(context); //returns "Hi John"


text:
Q: C# Create new object with property values in constructor return Null When a new object of class Foo is created, the constructor is supposed to create a new folder and a new file based on the object properties. But I get NullException (param: path2)?
I found that the object properties has Null value when the constructor is called. But I gave the properties values when I created the object? What am I missing?
My Foo class:
public class Foo
{
    public string Bar { get; set; }
    public string Baz { get; set; }
    public string Source { get { return Path.Combine(Qux, Baz, Bar); } }
    private string Qux { get { return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); } }

    public Foo()
    {
        // Use property values to find or create Directory and File
        if (!Directory.Exists(Path.Combine(Qux, Baz))) Directory.CreateDirectory(Path.Combine(Qux, Baz));
        if (!File.Exists(Source)) File.Create(Source);
    }
}

In my Main class:
// Create a new Foo object with following property values
Foo foo = new Foo { Baz = "corge", Bar = "grault" };

A:
But I gave the properties values when I created the object?

No you didn't.  (Though admittedly it may be a little unintuitive if you're new to the syntax.)
The code is expecting those to be supplied in the constructor.  But you have a parameterless constructor:
public Foo()
{
    //...
}

So when that constructor executes those properties haven't been set and have their default values.
Add the parameters to the constructor itself:
public Foo(string baz, string bar)
{
    Baz = baz;
    Bar = bar;
    //...
}

And then supply them to the constructor:
new Foo("corge", "grault")

What you're doing here:
Foo foo = new Foo { Baz = "corge", Bar = "grault" };

Is the equivalent of this:
Foo foo = new Foo();
foo.Baz = "corge";
foo.Bar = "grault";

The constructor is being called first, before the parameters are set.


text:
Q: Podman cant find an existing absolute path to add I am using podman and trying to map an absolute path on my mac to /opt/flatbuffers on the container.
ADD /Users/bryan/src/git/flatbuffers /opt/flatbuffers

Getting this build error:
STEP 8/9: ADD /Users/bryan/src/git/flatbuffers /opt/flatbuffers
Error: error building at STEP "ADD /Users/bryan/src/git/flatbuffers /opt/flatbuffers": checking on sources under "/var/tmp/libpod_builder2832945314/build": copier: stat: "/Users/bryan/src/git/flatbuffers": no such file or directory

I have verified the absolute path exists and is populated.


text:
Q: How to make text align vertically even when window size changes How to make text align like this, even if the window size changes?

Basically all the text bellow the red text must align perfectly with the red text

A: If you have the luxury of being able to use grid, then sub-grid is designed exactly for this use case. If not, I would recommend using a table. The data looks rather 'tabular' and it's a good use of table.
For a quick conceptual understanding of Subgrid, I refer you to this post: https://dev.to/kenbellows/why-we-need-css-subgrid-53mh

A: you can do this for the parent element
.parent{
      position: relative;
}

and this for the child element
.child{
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
}

A: Try this code.
'display: flex;'
'align-items: center;'
'justify-content: center;'

A: Just add this line in the head section of your HTML code:
<meta name="viewport" content="width=device-width, initial-scale=1">
and this at the bottom of your CSS code:
the number between the braces equals the maximum screen size for your CSS to take effect
@media screen and (max-width: 600px){ //any CSS here is to make it snap into place based on how the window size affects it }

//if you need another window size
@media screen and (max-width: 200px) { //make another one }


text:
Q: Likelihood principle: difference between weak and strong version Does anyone understand the difference between weak likelihood principle and strong likelihood principle?

A: Yes, it's straightforward. The weak LP is within a given model and distribution (it's essentially just the sufficiency principle within a model), whereas the strong LP, SLP, makes the claim (of equivalent evidential import) for pairs of models. Easiest to refer to my paper here: http://errorstatistics.com/2014/09/06/statistical-science-the-likelihood-principle-issue-is-out
fortunately, it turns out the the SLP does not follow from sufficiency and conditionality, as had long been thought.


text:
Q: Latex not opening png and windows not being able to generate bb I'm using TexMaker (on Windows 10), using the pdflatex (F6) and yet I can't open the PNG file in the folder of my .tex
\usepackage{graphicx}
\begin{document}
\begin{figure}[h!]
\includegraphics[width=\linewidth]{File.png}
\end{figure}
\end{document}

so I tried to create an bb file from the PNG. I opened cmd at the folder and typed:
ebb File.png
ebb: file not writable for security reasons: File.bb
ebb: fatal: Unable to open output file File.bb

When clicking in the properties and security of File.png I see that my user both: is the owner of the folder and has all permissions set in (even tho I cannot uncheck any of the permissions I have, weirdly).
The folder which I'm working on has that black square marked on the "read only" attribute (in properties). Which I can't quite keep unchecked even tho I'm the owner of it. What is wrong?
EDIT: Here's what happens when I click on show permissions (>properties >security >advanced >show permissions) my user is the owner.

I can't click on anything even tho I'm the owner.
Edit, the logfile:
    LOG FILE :
This is pdfTeX, Version 3.14159265-2.6-1.40.21 (MiKTeX 20.10) (preloaded format=pdflatex 2020.10.24) 25 OCT 2020 10:47
entering extended mode
**./test.tex
(test.tex
LaTeX2e <2020-10-01> patch level 1
L3 programming layer <2020-10-05> xparse <2020-03-03>
("C:\Program Files\MiKTeX\tex/latex/base\article.cls"
Document Class: article 2020/04/10 v1.4m Standard LaTeX document class
("C:\Program Files\MiKTeX\tex/latex/base\size12.clo"
File: size12.clo 2020/04/10 v1.4m Standard LaTeX file (size option)
)
\c@part=\count175
\c@section=\count176
\c@subsection=\count177
\c@subsubsection=\count178
\c@paragraph=\count179
\c@subparagraph=\count180
\c@figure=\count181
\c@table=\count182
\abovecaptionskip=\skip47
\belowcaptionskip=\skip48
\bibindent=\dimen138
)
("C:\Program Files\MiKTeX\tex/latex/graphics\graphicx.sty"
Package: graphicx 2020/09/09 v1.2b Enhanced LaTeX Graphics (DPC,SPQR)
("C:\Program Files\MiKTeX\tex/latex/graphics\keyval.sty"
Package: keyval 2014/10/28 v1.15 key=value parser (DPC)
\KV@toks@=\toks15
)
("C:\Program Files\MiKTeX\tex/latex/graphics\graphics.sty"
Package: graphics 2020/08/30 v1.4c Standard LaTeX Graphics (DPC,SPQR)
("C:\Program Files\MiKTeX\tex/latex/graphics\trig.sty"
Package: trig 2016/01/03 v1.10 sin cos tan (DPC)
)
("C:\Program Files\MiKTeX\tex/latex/graphics-cfg\graphics.cfg"
File: graphics.cfg 2016/06/04 v1.11 sample graphics configuration
)
Package graphics Info: Driver file: pdftex.def on input line 105.
("C:\Program Files\MiKTeX\tex/latex/graphics-def\pdftex.def"
File: pdftex.def 2020/10/05 v1.2a Graphics/color driver for pdftex
))
\Gin@req@height=\dimen139
\Gin@req@width=\dimen140
)
("C:\Program Files\MiKTeX\tex/latex/l3backend\l3backend-pdftex.def"
File: l3backend-pdftex.def 2020-09-24 L3 backend support: PDF output (pdfTeX)
\l__kernel_color_stack_int=\count183
\l__pdf_internal_box=\box47
) (test.aux)
\openout1 = `test.aux'.
LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 3.
LaTeX Font Info: ... okay on input line 3.
LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 3.
LaTeX Font Info: ... okay on input line 3.
LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 3.
LaTeX Font Info: ... okay on input line 3.
LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 3.
LaTeX Font Info: ... okay on input line 3.
LaTeX Font Info: Checking defaults for TS1/cmr/m/n on input line 3.
LaTeX Font Info: ... okay on input line 3.
LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 3.
LaTeX Font Info: ... okay on input line 3.
LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 3.
LaTeX Font Info: ... okay on input line 3.
("C:\Program Files\MiKTeX\tex/context/base/mkii\supp-pdf.mkii"
[Loading MPS to PDF converter (version 2006.09.02).]
\scratchcounter=\count184
\scratchdimen=\dimen141
\scratchbox=\box48
\nofMPsegments=\count185
\nofMParguments=\count186
\everyMPshowfont=\toks16
\MPscratchCnt=\count187
\MPscratchDim=\dimen142
\MPnumerator=\count188
\makeMPintoPDFobject=\count189
\everyMPtoPDFconversion=\toks17
) ("C:\Program Files\MiKTeX\tex/latex/epstopdf-pkg\epstopdf-base.sty"
Package: epstopdf-base 2020-01-24 v2.11 Base part for package epstopdf
Package epstopdf-base Info: Redefining graphics rule for `.eps' on input line 4
85.
)
<semirreta.png, id=1, 368.1253pt x 99.37125pt>
[1{C:/Users/JoaoV/AppData/Local/MiKTeX/pdftex/config/pdftex.map}] (test.aux) )
Here is how much of TeX's memory you used:
1167 strings out of 480236
17436 string characters out of 2890433
280939 words of memory out of 3000000
17769 multiletter control sequences out of 15000+200000
535555 words of font info for 31 fonts, out of 3000000 for 9000
1141 hyphenation exceptions out of 8191
60i,4n,66p,199b,236s stack positions out of 5000i,500n,10000p,200000b,50000s
<C:/Program Files/MiKTeX/fonts/type1/public/amsfonts/cm/cmr12.pfb><C:/Program F
iles/MiKTeX/fonts/type1/public/amsfonts/cm/cmtt12.pfb>
Output written on test.pdf (1 page, 13448 bytes).
PDF statistics:
15 PDF objects out of 1000 (max. 8388607)
0 named destinations out of 1000 (max. 500000)
6 words of extra memory for PDF output out of 10000 (max. 10000000)

I made a little test:

the real image is suposed to be these two lines: https://ibb.co/yYQCfnd

A: Remove the draft option, this prevents images from showing up


text:
Q: Get Matching Xpath Count Keyword does not return all matching Xpaths I am trying to store a list of all radiobuttons within the page I am working on. The Radio Button amount will change depending on what pagination number I am on.
Right now I am using the code below to find all matching Xpaths and store it within a variable.
*** Keywords ***
Count How Many RadioButtons On Page
    ${Count}    Get Matching Xpath Count    //tr
    ${CountList}    Create List
    : FOR    ${INDEX}    IN RANGE    1    ${Count}
    \    Append To List    ${CountList}    xpath=//tr[${INDEX}]
    log    ${CountList}
    Set Global Variable    ${CountList}

This only stores 11 entries. When the page actually contains 20. For some reason it is missing the other 9 and I cannot figure out why.
At the end, the CountList variable looks like this:
u'xpath=//tr[1]', u'xpath=//tr[2]', u'xpath=//tr[3]', u'xpath=//tr[4]', u'xpath=//tr[5]', u'xpath=//tr[6]', u'xpath=//tr[7]', u'xpath=//tr[8]', u'xpath=//tr[9]', u'xpath=//tr[10]', u'xpath=//tr[11]'

This list should go all the way up to //tr[20]
I can also confirm that using (for example) //tr[12] or onwards, will work correctly. It is just that Get Matching Xpath Count is not pulling all 20 of them for some reason.
Can anyone shine light onto this?
EDIT:
Below is part of the HTML of the page I am trying to count:

 P-DAC-15-790

DATA

..DATA

15

i9

DATA

26-06-2015 14:50

EDIT2:
Ive updated the Get Matching Xpath Count to //div[4]/table/tbody/tr to be a little more specific, and it still only counts 11, not 20
EDIT3:
If I perform the same test on the 2nd page, it works completely fine (returns 20, and loops through 20 rows) But there is no difference between page 1 and 2...

A: Turns out, RF didn't really understand what was going on within the page. So what I did was as I arrive to the page (via the nav bar) to then refresh the current page. It then saw all 20 entries and continued through the for loop as expected.
I don't know if this is a bug within RF for Selenium2Library, But I shouldn't have needed to basically re-initialise the web page when trying to complete logic tasks.
If someone else runs into a similar issue like this - comment below and ill try to assist you :)


text:
Q: there is no type juggling for constants (I want my string 'REGEX_NAME' like 'REGEX_EMAIL' to become REGEX_NAME like REGEX_EMAIL) I'm having to manually write:
if($pattern == 'REGEX_EMAIL') $pattern = REGEX_EMAIL;
if($pattern == 'REGEX_PASSWORD') $pattern = REGEX_PASSWORD;

Is there an other way?

A: You could use the constant function to get the constant's value by its name:
if (substr($pattern, 0, 6) == 'REGEX_' && defined($pattern)) {
    $pattern = constant($pattern);
}

A: One solution (albeit ridiculous) would be to use an associative array...
$regexs = array('REGEX_NAME' => REGEX_NAME, 'REGEX_EMAIL' => REGEX_EMAIL);


text:
Q: Spring Boot server based on existing WSDL I'm developing a WSDL file and I want to create a server for testing with Spring Boot. As I want to have full control over the WSDL (Spring WS does some things I don't like), I want to write it myself and I would like to create a simple server to test the WSDL.
Is it possible to make Spring WS in the Spring Boot to use my static WSDL and expose it as it is? I don't want to use the dynamically generated WSDL for these reasons:

*

*The generated WSDL can't separate XSDs.

*There are some naming conventions for input and output elements of the operations that are not usable for my project

*As far as I know, the application must be run to create WSDL - it can't be generated during Maven build.

Also I want to use Spring Boot, so there should be one jar file, embedded Tomcat, not a war file.


text:
Q: Prompting user with a print after each Switch-case except case: "0 exit" Instead of making it blank each time the user is finished with a case, I've added a println("Next command?>") in the runCommandLoop method as a cheap solution to my problem. But that also means when case "0" or "exit" is choosen, "Next command?>" is printed out one last time BEFORE shutting down.
Simply put I want it to prompt after every case except "0 shutdown".
Calling the startup method is another option as well I guess but that doesn't make much difference either.
private void startup() {
    System.out.println("\nCommand?>\n" + "1: register new dog\n" + "2: increase age\n" + "3: list dogs\n"
            + "4: remove dog\n" + "0: exit\n");
}

private void runCommandLoop() {
    boolean done;
    do {
        String command = readCommand();
        done = handleCommand(command);
        System.out.println("\nNext command?>");
    } while (!done);
}

private String readCommand() {
    String command = input.registerString();
    return command;
}

private boolean handleCommand(String command) {
    switch (command) {

    case "1":
    case "register new dog":
        dogList.registerDog();
        break;

    case "2":
    case "increase age":
        dogList.increaseAge();
        break;

    case "3":
    case "list dogs":
        dogList.listDogs();
        break;

    case "4":
    case "remove dog":
        dogList.removeDog();
        break;

    case "0":
    case "exit":
        return true;
    default:
        printMenu();
    }
    return false;
}

private void printMenu() {
    System.out.println("Error: wrong command\n" + "The available commands are:\n" + "1: register new dog\n"
            + "2: increase age\n" + "3: list dogs\n" + "4: remove dog\n" + "0: exit");
    return;
}

private void closeDown() {
    System.out.println("Shutting down...");
    input.closeInput();

}

private void run() {
    startup();
    runCommandLoop();
    closeDown();
}

public static void main(String[] args) {
    Interface startup = new Interface();
    startup.run();
}

In case you need to see what the dogList methods do (the arraylist variable name is just temporary):
public void registerDog() {
    String name = input.registerStringLoop("Name");
    String breed = input.registerStringLoop("Breed");
    int weight = input.registerIntPrompt("Weight");
    int age = input.registerIntPrompt("Age");
    Dog dog = new Dog(name, breed, age, weight);
    doggoList.add(dog);
    System.out.println(dog.getName() + " has been added to the register.\n" + dog.toString());

}

public void listDogs() {
    if (doggoList.size() == 0) {
        System.out.println("Error: no dogs found");
    } else {
        System.out.print("Smallest tail length to display?>");
        int smallestTailLength = input.registerInt();
        sortDogs();
        if (smallestTailLength == 0) {
            System.out.println(doggoList);
        } else
            for (Dog s : doggoList) {
                if (s.getTailLength() >= smallestTailLength)
                    System.out.println(s);
            }
    }
}

public void increaseAge() {
    System.out.print("Enter the name of the dog?>");
    String dogName = input.registerString();
    for (Dog s : doggoList) {
        if (s.getName().equalsIgnoreCase(dogName)) {
            s.increaseAge();
            sortDogs();
            System.out.println(s.getName() + " is now " + s.getAge() + " years old.");
            return;
        }
    }

Thanks in advance.

A: It should be as simple as
if (!done){
    System.out.println("\nNext command?>");
}


text:
Q: phpQuery перебор массива с ссылками на товар Как правильно сделать что-бы был перебор массива file
с библиотекой phpQuery
 $file = [
      "https://digbox.ru/dji_kvadrokopter_dji_spark_alpin_white.html",
      "https://digbox.ru/kvadrokopter_dji_mavic_pro__pult_du_.html",
      "https://digbox.ru/kvadrokopter_dji_phantom_4_pro.html",
    ];

    $product_link = file_get_contents($file);

    phpQuery::newDocument($product_link);

    $product = array();

    $product['_NAME_'] = trim(pq("h1")->text());
    $product['_META_TITLE_'] = trim(pq("h1")->text());
    $product['_QUANTITY_'] = "15";

    $price = pq(".aside-top .price ins")->text();
    $product['_PRICE_'] = preg_replace('~[^0-9]+~','',$price); ;

    $product['_IMAGE_'] = "https://digbox.ru".pq(".product-slider .slider-init li a")->attr('href');

    $product['_IMAGES_'] = '';
    $images = pq(".product-slider .slider-init li a");
    $dublicat_img = $product['_IMAGE_'].",";
    foreach ( $images as $p ) {
        $product['_IMAGES_'].= str_replace("https://digbox.ru,",'',str_replace($dublicat_img,"","https://digbox.ru".$p->getAttribute('href').","));
    }

    $product['_MANUFACTURER_'] = 'DJI';
    $product['_MODEL_'] = str_replace("Арт: ","",pq(".item-info .item-id")->text());
    $atr = pq(".char-list");
    foreach ( $atr as $p ) {
        $p = pq($p);
        $h2 = $p->find('div')->htmlOuter();
        $delimiters = Array('
',"-");
        $attributes = multiexplode($delimiters,$h2);
        foreach ($attributes as $attribute) {
            list($attributeName,$attributeVal) = $attribute;
            $attributeName= preg_replace("/\s{2,}/"," ",trim($attributeName));
            $attributeVal = str_replace(";",'',trim($attributeVal));
            if(!empty($attributeName)){
                $product['_ATTRIBUTES_'] .= "Характеристика|{$attributeName}|{$attributeVal}" . PHP_EOL;
            }
        }
    }

    phpQuery::unloadDocuments();


text:
Q: Finding and changing tuples values I have some tuples already made like so:
public GreenhouseControls() {
        light = new Tuple<>("light", "off");
        fans = new Tuple<>("fans", "off");
        water = new Tuple<>("water", "off");
        power = new Tuple<>("power", "on");
        window = new Tuple<>("window", "good");
        thermostat = new Tuple<>("thermostat","day");
}

and I'm trying to use a setVariable() method in the same class that will take in 2 string (for example, "light" and "on") and would use the first string to search the first variable of the tuple and when a match is found it would replace the second variable with the second string.
I tried adding the tuples to an ArrayList but I can't get the search part to work.
Is there a way to achieve this maybe with either an ArrayList or a HashSet?

Tuple class:
   public static class Tuple<A,B> {
        public final A eventName;
        public final B status;

        public Tuple(A eventName, B status) {
            this.eventName = eventName;
            this.status = status;
        }

        public String toString() {
            return "(" + eventName + ", " + status + ")";
        }
    }

A: You can use a Map to create relationships between keys and values. In your case, a HashMap would be appropriate and would make your code much more concise and easy to read. You can use put(key,value) to set the value of a key and use get(key) to retrieve the value associated with a key.
final Map<String, String> map = new HashMap<>();
map.put("light","off");
//Etc..

//Get value
String light = map.get("light");//"off"
//Update value
map.put("light","on");
light = map.get("light");//"on"

If you are not allowed to change the structure of your code, you can implement it with your Tuple class using foreach loops like so:
import java.util.Arrays;
import java.util.List;
public class GreenhouseControls {
    private final List<Tuple<String,String>> members;
    public GreenhouseControls() {
        members = Arrays.asList(
                new Tuple<>("light", "off"),
                new Tuple<>("fans", "off"),
                new Tuple<>("water", "off"),
                new Tuple<>("power", "on"),
                new Tuple<>("window", "good"),
                new Tuple<>("thermostat","day")
               );
    }

    public void setVariable(final String eventName, final String status) {
        for(final Tuple<String, String> tuple: members) {
            if(tuple.getEventName().equals(eventName)) {
                tuple.setStatus(status);
                return;
            }
        }
        throw new IllegalArgumentException("No event found with eventName " + eventName);
    }

    public String getVariable(final String eventName) {
        for(final Tuple<String, String> tuple: members) {
            if(tuple.getEventName().equals(eventName)) {
                return tuple.getStatus();
            }
        }
        return null;
    }

    public static class Tuple<A, B> {
        private A eventName;
        private B status;

        public Tuple(final A eventName, final B status) {
            this.eventName = eventName;
            this.status = status;
        }

        @Override
        public String toString() {
            return "(" + eventName + ", " + status + ")";
        }

        public B getStatus() {
            return status;
        }

        public void setStatus(B status) {
            this.status = status;
        }

        public A getEventName() {
            return eventName;
        }
    }
}

A: I've implemented how you could do this for a single variable of an object. i.e. "Light".
Is there a reason why you need to have a redundant variable captured as a tuple?
public class GreenhouseControls {

    private String light;

    public String getLightStatus() {
        return light;
    }

   public void setLightStatus(String input)
   {
       if(input == "on" || input == "off")
       this.light = input;
   }

   public static void main(String[] args)
   {
       GreenhouseControls controls = new GreenhouseControls();
       controls.setLightStatus("on");
       System.out.println(controls.getLightStatus());
       controls.setLightStatus("off");
       System.out.println(controls.getLightStatus());
   }

}

A: The easier way is to use HashMap for your requirement as suggested by hev1. But if you still want to make use of the Tuple class, then here is one way of doing it.
Add getter methods to your Tuple class
public class Tuple<A,B> {
    public final A eventName;
    public final B status;

    public Tuple(A eventName, B status) {
        this.eventName = eventName;
        this.status = status;
    }

    public String toString() {
        return "(" + eventName + ", " + status + ")";
    }

    public A getEventName() {
        return eventName;
    }

    public B getStatus() {
        return status;
    }
}

Then collect all your tuples in a List and pass it to your setVariable method. Within this method just check if the given eventName is present in any of the tuples. If yes, then remove that Tuple from the list and create a new Tuple with the given status and add it back to the list. Something like this:
void setVariable(String eventName, String status, List<Tuple>tuples) {
    boolean isRemoved = tuples.removeIf(tuple -> tuple.getEventName().equals(eventName));
    if(isRemoved) {
        Tuple tuple = new Tuple(eventName, status);
        tuples.add(tuple);
    }
}

Hope this helps.


text:
Q: Center collection while pinched I am working on scrolling UICollectionView to the place where I have used pinch gesture. They are 2 ways I've figure out how could I do this :
The first one should be the best but it does not work indeed.
let pinchCenter = CGPoint(x: gesture.location(in: collectionView).x - collectionView.bounds.midX,
                                      y: gesture.location(in: collectionView).y - collectionView.bounds.midY)
            if let index = collectionView.indexPathForItem(at: pinchCenter) {
                collectionView.scrollToItem(at: index, at: .centeredHorizontally, animated: true)
            }

What is doing, it is creating a CGPoint which is a placed exactly on the middle of the pinch gestures (two fingers), but there is no IndexPath in the UICollectionView, so it will not hit a scrollToItem.
Second option is to use only :
let center = gesture.location(ofTouch: 1, in: collectionView)

ofTouch If we point at 1, then the right finger will be taken, if 2 then left, still it's not that what I want, it is not a centered position of the UICollectionView.
Any ideas how could I improve the precision of second option or make the first working ?
EDIT
Third option is to calculate point using pattern for center in the line :
(x1+x2/2, y1+y2/2)

It is going to be :
let leftPinch = gesture.location(ofTouch: 1, in: collectionView)
            let rightPinch = gesture.location(ofTouch: 0, in: collectionView)

            let avg = CGPoint(x: (leftPinch.x + rightPinch.x) / 2, y: (leftPinch.y + rightPinch.y) / 2)

It is going to crash at let leftPinch with NSInternalInconsistencyException.
Thanks in advance!


text:
Q: SSIS Intermittent variable error: The system cannot find the file specified Our SSIS pacakges a structured as one Control package and many child packages  (about 30) that are invoked from the control package. The child packages are invoked with Execute Package Task. There is one Execute Package Task per child package. Each Execute Package Task uses File Connection Manager to specify path to the child package dtsx file. There is one File Connection Manager per child package. Each File Connection Manager has an expression defined for ConnectionString property. This expression looks like this:
@[Template::FolderPackages]+"MyPackage.dtsx"

The file name is different for each package. The variable (FolderPackages) is specified in the SSIS package configuration file.
The error that is generated during run time is

Error 0x80070002 while loading package file "MyPackage.dtsx"

The system cannot find the file specified." The package that fails is different from run to run and sometimes no packages fail at all. This is when run on exactly the same environment/data etc.
I ran FileMon during this error and found out that when the error happens SSIS tries to read the dtsx file from a wrong place, namely from system32. I checked that this is identical to what would happen if @[Template::FolderPackages] variable were empty, but because the very same variable is used for every child package and works for some but doesn't work sometimes for others, I have no expalnation to this fact.
Anything obvious, or time to raise a support call with Microsoft?

A: Are you using Expressions on the SSIS variables directly? Variables with Expressions are calculated each time the variable is referenced by the consuming object which needs to use it. That is where the race condition bug exists, because sometimes the expression doesn't get evaluated if another thread is already evaluating a different variable, and the default value for the variable is provided to the consumer object.
If that matches your design, these two bugs on the connect site discuss the problem, and the workarounds:
https://connect.microsoft.com/SQLServer/feedback/details/332372/ssis-variable-expressions-dont-always-evaluate
A second one at
connect.microsoft.com/SQLServer/feedback/details/406534/ssis-2008-variable-expressions-dont-always-evaluate
A summary of workarounds is
{
- Note the parallel tasks that could run in you SSIS control flow and utilize these expression variables. If you have two tasks side-by-side if each relies upon the same variable, and that variable has an Expression to set its value, then you could hit this.
Manually sequentialize such tasks, so that they don't run in parallel. Ie. Add a green arrow on the control flow, so that the tasks occur in order Task1, Task2, Task3, rather than side-by-side on parallel paths and rather than inside the same container with no paths.

*

*You could avoid variable expressions: Assigning local variables in the required order using a home-made script task that does the same kind of work, so that variables are not evaluated using expressions (ie. the thing which can hit this race condition). In other words, manually assign the variable values at a point in time in your control flow just before they are used. The point of using expressions on variables is to dynamically set a value based on another value whenever it is used, so this acheives a similar design goal but in a manual way.

*Reduce threads to minimize potential: Setting the Dataflow task EngineThreads to 1 and MaxConcurrentExecutables to 1. This will help sequentalize execution of your package to one task at a time, but that has the side effect which may cause slower performance.

*Create and set values on distinct copies of variables at different scope levels in the design, so that they evaluate in different parallel execution scopes and avoid the expression evaluation on parallel threads. Master::Var1, Child1::Var1, Child2::Var1
}

A: A bit of a stab in the dark but...
I've had a similar issue with variables where readonly=false and multiple components were reading the variable at the same time and causing locking issues.
I consistently recreated the problem by running a pair of dataflows that did nothing but reference the variable inside a for loop container and changed the variable to be read only and this resolved the problem.
If you temporarily hardcode the package name does this resolve the issue?

A: Turns out after sending trace info to Microsoft that we are encountering heap corruption. I'll update this question if we get to the bottom of it.
The current suggestion is to disable heap lookaside for dtexec.exe.

A: The official answer to this issue is that it is a bug in SQL 2005 and 2008. Many tasks accessing the same variable cause a race condition, and some tasks get the default value for the expression instead of the evaluated value.
The workaround is to ensure that the default value (the value defined in the property sheet for whatever property you are having trouble with) should be the value that will work in your production environment.
This way, when the race condition happens in prod, SSIS will fall back to the package value, which will still work.
In dev? Well you're just going to have to deal with that manually until we get a bug fix from Microsoft.

A: There is a KB article relating to this issue: http://support.microsoft.com/kb/2448991 which states when and where this was fixed.


text:
Q: Transform app.config file at Asp.Net Core solution publish? I have an ASP.NET Core WebApi project with .NET Framework 4.6.1. And I also have an app.config file that contains endpoints for some WCF services. I have a corresponding app.config for each environment like Dev and Qa and so on. But when I publish the solution it doesn't transform the app.config based on the environment. Do you have any ideas on how I could do that?

A: The solution I came up with is to add a post build command that copies the transformed web configs over the top of the MyProject.exe.config. In order for this to work you will need to copy the assembly redirect from your app.config(output) to your web.config. Then you only need one config file. This is not a great solution and I am going to implement a different way to reference the wcf connections using the appSettings.json and creating the clients in the C# code but, this will work for now. In our continuous integration build, I have a powershell command that does the same after build. One other caveat: I am deploying to IIS and need the web.config authentication settings (for windows auth) so I had to make sure the web.config and MyProject.exe.config both got deployed. This ended up being the same file, IIS using the peices it needs and the WCF client builder using the parts it needs. again we are not going to be using this for long and I would suggest building the WCF client programatically.
Update: I use the appsettings.json to include my environment based settings and added a way to connect to wcf using the system.servicemodel classes in .netStandard. it works great!


text:
Q: Subversion NoClassFoundDefError While using subversion several files where placed into 1 package.
Every thing was working perfectly at this point.
Afterwards somebody replaced that package with 5 other ones and divided all the files amongst them.
And now after "updating" the proper files do appear. With the name of the 1 package gone.
But now i keep getting the error:"java.lang.NoClassDefFoundError/first package name/Main
Where the first package stands for the package that has long been deleted.
For the person who changed this, the program just works fine.
I can only get to compile the program when i delete every package again and replace all of it with 1 package like it was at the start...
Pretty much tried everything, re-install, clean & build, etc...
Any input appreciated.

A: Try searching for files in your project directory containing the old package name. Looks like some project metadata that's not under version control wasn't updated. Then either find and fix it in Netbeans or close Netbeans and edit the files directly (backup first, of course).


text:
Q: Converting standardized betas back to original variables without intercept I am working on a multiple linear regression problem with system defined as :
$Y=\sum_{j=1}^k \beta_jx_j$
I'm using the RidgeCV and LassoCV for the regression, and as mentioned in many places, the standardization of the predictor variables should be done before the Ridge or Lasso regression. Because of the physical definition of my system, I don't want to have the intercept term in the equation, that's why there is no $\beta_0$. But if I standardize the predictors with the normal way :
$z_j=\frac{x_j-\overline{x_j}}{S_j}$
when I convert the standardized betas back to origianl Bs that I want, there will be a term of intercept $\hat{\beta_0}-\sum_{j=1}^k \hat\beta_j\frac{\overline{x_j}}{S_j}$ appear as mentioned in the answer of this question Converting standardized betas back to original variables.
But in my case as I said before, I don't want to have the term of intercept, how can I get my original Bs?
P.S. I'm thinking about standardize the predictors by: $z_j=\frac{x_j}{S_j}$ but I don't know if it makes any sense... I'm new to statistics so please help!

A: First, please reconsider: long experience makes us humbly suspect that even when theory indicates an intercept is unnecessary, nature may intervene in the form of errors or variation from our theory that make an intercept statistically significant and important.  Leaving out the intercept can (greatly) bias all estimates, as well as providing misleading information about the uncertainties in the estimates.
But in the rare situations where an intercept definitely must be omitted, a geometric interpretation of standardization shows us what to do.  Dropping the subscript $j,$ which is not needed for this discussion, your vector $\mathbf{z}$ is the result of orthogonally projecting $\mathbf{x} = (x_1,x_2, \ldots, x_n)$ onto the hyperplane orthogonal to $\mathbf{1}=(1,1,\ldots,1)$ and then rescaling that result to have a unit $L^2$ norm.  Omitting the intercept means not doing the projection.  Thus, the relevant analog of standardization is to rescale the unprojected vector to unit length.  Accordingly, compute
$$S^2 = S(\mathbf{x})^2 = ||\mathbf{x}||^2 = \sum_{i=1}^n x_i^2$$
and then
$$\mathbf{z} = \frac{1}{S}\,\mathbf{x} = \left(\frac{x_1}{S}, \frac{x_2}{S}, \ldots, \frac{x_n}{S}\right).$$

In this context the standardized betas $\tilde\beta_i$ are, by definition, the estimates $\hat\gamma_i$ in the model
$$E[Y/S(\mathbf{y})] = \sum_i\gamma_i\, \mathbf{z}_i = \sum_i \gamma_i\,\frac{\mathbf{x}_i}{S(\mathbf{x}_i)}$$
where $\mathbf{y}$ is the vector of observed responses.  Because (by virtue of the linearity of the expectation operator $E$) this is algebraically identical to the model
$$E[Y] = \sum_i \frac{S(\mathbf{y})\,\gamma_i}{S(\mathbf{x}_i)} \mathbf{x}_i = \sum_i \beta_i\, \mathbf{x}_i,$$
to convert the standardized betas into the estimates $\hat\beta_i$ for this, the original model, equate the coefficients and deduce that for each $i,$
$$\hat\beta_i = \frac{S(\mathbf{y})}{S(\mathbf{x}_i)}\,\tilde\beta_i.$$
This is recognizable as a simple change of units of measurement for $\mathbf{y}$ and $\mathbf{x}_i.$


text:
Q: Team Fortress 2: Hidden Stats on Capture Points for Payload Cart pushing The only information I found is this: https://wiki.teamfortress.com/wiki/Scoreboard#Points
"Pushing the Payload cart for 10 seconds" gives you 1 capture point which will give you 2 overall score points.
However sometimes I feel like I'm pushing the cart for 30 seconds and I don't get a single point. What's going on here? The 10 second rule certainly isn't true.

A: Every player gets 0.1 capture points for every second they push the cart. This does not have to be continuous, or even in the same life, but it does have to be unblocked. It doesn't matter what class you are, what your capture multiplier is, or how many other players are on the cart. Only once your amount of capture points reaches the next whole number does it count, so in essence you get 1 capture point every 10 seconds.
However, this is a mapper-defined value ("partial capture rate"); mapmakers can decide to raise or lower this rate, so some maps can have faster or slower rates of giving out capture points. On most official payload maps this value is 0.1 (hence 10 seconds being the conventional wisdom), but a few are different - for example, it's 0.02 on Upward, so there you have to push the cart for a full 50 seconds to get one capture point.


text:
Q: Update file from a .net website to SharePoint 2010 I need to update files from .asp web site and the files need to store in sharepoint2010 documsnt lib. i need to use sharepoint for bulk document storage.

A: You can use Sharepoint client object to update the items in sharepoint.
Check the following link to perform basic operations on Sharepoint using CSOM.
http://msdn.microsoft.com/en-us/library/office/fp179912(v=office.15).aspx

A: i cant get you what you asking about updating. i think you need to see this link for reference
http://www.codeproject.com/Articles/19717/Uploading-files-to-the-SharePoint-Document-Library
http://www.c-sharpcorner.com/UploadFile/0e18a8/update-a-file-in-a-document-library-in-sharepoint-2013-using/


text:
Q: Declaring and initializing TVarRec (array of const) params I want to define a var or const that I can further use in TClientDataSet SetRange method:
var
  lRangeStart : array of TVarRec;
  lRangeEnd   : array of TVarRec;

procedure SetRange;
begin

   SetLength (lRangeStart, 2);
   SetLength (lRangeEnd  , 2);

  lRangeStart [0] := Field1; // Incompatible types tVarRect and Integer
  lRangeStart [1] := Field2; // Incompatible types tVarRect and Integer
  lRangeEnd   [0] := Field1; // Incompatible types tVarRect and Integer
  lRangeEnd   [1] := Field2; // Incompatible types tVarRect and Integer

   MyDataSet.SetRange (lRangeStart, lRangeEnd);

end;

A: That's not the way it works. You create the arrays differently:
MyDataSet.SetRange([Field1, Field2], [Field1, Field2]);

The compiler takes care of generating the various TVarRec records for you.
You can also have mixed types, if the columns in your index are of different types:
MyDataSet.SetRange([1, 'Testing'], [1, 'Testing']);

To use input from the user instead, just assign the the user input to variables, doing any necessary type conversions, and pass in the variables.
var
  Val1, Val2: Integer;
begin
  Val1 := StrToInt(Edit1.Text);
  Val2 := StrToInt(Edit2.Text);
  MyDataSet.SetRange([Val1, Val2], [Val1, Val2]);
end;

Or, you can do the conversion in-line, but exceptions due to invalid types are an issue:
MyDataSet.SetRange([StrToInt(Edit1.Text), StrToInt(Edit2.Text)],
                    StrToInt(Edit1.Text), StrToInt(Edit2.Text)]);

In order to do so yourself, you'd have to explicitly assign to the appropriate type of each element (which defeats much of the purpose of using an array of const, which is being able to create it on-the-fly in your code and mix types):
SetLength(lRangeStart, 2);
lRangeStart[0].vInteger := 1;
lRangeStart[1].vInteger := 2;


text:
Q: How to sort a text list of files by sizes such as as 1.0M, 2.0G and 3.5K? Here is the content of the text file:

I tried several ways but couldn't find a solution. One of them was:
cat filelist.txt | sort -nk0

Here is text result :
1.3M    /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/Encode/JP/JP.so
1.2M    /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/Encode/KR/KR.so
1.1M    /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/Encode/CN/CN.so
1.0M    /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/Encode/TW/TW.so
190K    /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/Encode/Byte/Byte.so
138K    /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/re/re.so
113K    /usr/perl5/vendor_perl/5.8.4/i86pc-solaris-64int/auto/DBD/Pg/Pg.so
106K    /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/B/B.so
106K    /usr/perl5/5.6.1/lib/i86pc-solaris-64int/auto/re/re.so
104K    /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/POSIX/POSIX.so
14.1K    /usr/perl5/vendor_perl/5.8.4/i86pc-solaris-64int/auto/DBI/DBI.so

A: Use awk to convert the sizes to bytes and then sort with -n:
awk '$1 ~ /M/ { $1=$1*1000000 } $1 ~ /K/ { $1=$1*1000 } $1 ~ /G/ { $1=$1*1000000000 }1' filelist.txt | sort -n


text:
Q: img not displaying on Android I have a simple image in my html which renders fine on my PC, but not on my smartphone:

my folder-structure is as follows:
C:/Maus
  - index.html
  - geschenk.jpg

on my smartphone I copy that folder to my download-folder and open index.html from there. There's no web-server included, I directly open the file from the filesystem.

But on my smartphone the image isn't displayed.

A: Chrome will receive a content scheme from the Files app like:
content://com.google.android.apps.nbu.files.provider/1/file:// ...../index.html

As soon as Chrome 'sees' a content scheme it cannot display pictures as even if Chrome changes the scheme to:
content://com.google.android.apps.nbu.files.provider/1/file:// ...../geschenk.jpg

the provider will not let it access as there is no read permission for it.

A: The Android filesystem structure can't open relative file paths the same way other systems do.
So the answer is you need to use a complete hardcoded file:/// path.
This is not a very good approach since you need to replace all the URLs/paths in your HTML files.
Another approach if you are determined to do so, you can upload all project resources such as images, CSS, javascript to the cloud, like using SDN to access those files and to let the project work. But using the SDN approach it's easier to upload everything including the HTML files to a hosting account.


text:
Q: Why are we interested in the Fundamental Groupoid of a Space? The classical version of the van Kampen theorem is concerned about the fundamental group of a based space. In fact, it says that the functor $\pi_1$ preserves certain types of  pushouts in $Top_*$.
There is also a generalization of the van Kampen theorem that holds for the fundamental groupoid of a space $X$, where in this case it states precisely that the fundamental groupoid functor, $\Pi$, preserves certain colimits in $Top$, namely, those that arise from "nice" open coverings of $X$.
The "groupoid" version of the van Kampen theorem seems to me more conceptual and more elegant than the classical version. Also, the groupoid version allows one to prove the classical version in a more or less easier way.
Although, apart from the conceptual advantages of the groupoid version of van Kampen theorem, I would like to know if we are able to do any interesting calculations using the fundamental groupoid version of the van Kampen. In fact, explicitly describing a groupoid as a colimit of "simpler" groupoids is something that it is not clear at all for me. I would like to know some concrete cases where is it possible to describe the fundamental groupoid of a space, using this generalization form of the van Kampen theorem, and, if possible, to calculate the fundamental group directly from our calculation of $\Pi(X).$

A: The simplest natural example is to use the van Kampen theorem (in Ronnie Brown's version) to work out the fundamental group(oid) of the circle. The details are in his book Topology and Groupoids (http://groupoids.org.uk/topgpds.html).  That source also discusses colimits of groupoids in this context. If you look around on Ronnie's home pages (http://groupoids.org.uk) you can find discussion of many of the points that you raise.

A: I confess, in 1965 or so,  I first thought that the version of the SvKT (Seifert-van Kampen Theorem) for the fundamental groupoid enabled us to get rid of base points.  But then I wanted to calculate the fundamental group of the circle, and gradually realised that we needed $\pi_1(X,A)$, the fundamental groupoid on a set of $A$ of base points chosen according to the geometry.
and for which covering space methods are not ideal. In fact one needs combinatorics and combinatorial group(oid) theory to calculate individual $\pi_1(X,a)$ from $\pi_1(X,A)$. See my book Topology and Groupoids and also the classic 1971 book (downloadable) by Philip Higgins, Categories and Groupoids.
Groupoids model homotopy 1-types.  So one first determines  the 1-type before calculating an individual fundamental group.
This idea is nicely modelled in higher dimensions: one can calculate some 2-types and higher types as "big" algebraic objects inside which are the homotopy groups which one might want. The methods are explained more in a talk given in Paris on June 5, 2014, at the IHP, available on my preprint page.
As Mariano points out, this has been discussed elsewhere on stackexchange and mathoverflow.
July 14: The most general version of the SvKT is given in [41]  (downloadable) on my publication list,
R. Brown and A. Razak, `A van Kampen theorem for unions of
non-connected  spaces'', Archiv. Math. 42 (1984) 85-88.
in the form of a coequaliser statement when given  an open cover and a set $A$ (of ``base points'' which meets each path component of each 1-,2-, and 3-fold intersections of the sets of the cover. The style of proof goes back to Crowell's original version, and has the advantage of generalising to higher dimensions. For example, in
[32] R. Brown and P.J. Higgins, ``Colimit theorems for relative homotopy
groups'', J. Pure Appl. Algebra 22 (1981) 11-41.
The retraction from the version for the full fundamental groupoid, $A=X$, to this version is quite difficult to manage and is done in May's "Concise..." book, without the refinement on the conditions, but I feel is the wrong way to go, though it is quite elegant for the pushout version in dimension 1.
July 17, 2014: Actually I have missed out on three reasons why one is interested in the fundamental groupoid $\pi_1 X$.

*

*The notion of fibration of groupoids is relevant to topology particularly in construction of  operations of groupoids on homotopy sets, and exact sequences. If $p: E \to B$ is a fibration of spaces then $\pi_1 p: \pi_1 E \to \pi_1 B$ is a fibration of groupoids. This is exploited in Chapter 7 of Topology and Groupoids. See for example arXiv:1207.6404 for other current uses of the algebra of groupoids, and in particular fibrations.

*Similarly if $p: E \to B$ is a covering map of spaces then on applying $\pi_1$ we get a covering morphism of groupoids.  Thus a map is modelled by a morphism, and this often makes the theory easier to follow (IMHO!), particularly with regard to questions of lifting maps.  See Chapter 10 of T&G.

*If $G$  is a (discrete)  group acting on a space $X$ then it also acts on the fundamental groupoid $\pi_1 X$. So we have not only orbit spaces $X/G$ but also orbit groupoids $(\pi_1 X)/\!/G$. There is a canonical morphism $(\pi_1 X)/\!/G \to \pi_1(X/G)$ and there are useful conditions which ensure  this is an isomorphism, e.g.  $X$ is Hausdorff, has a universal cover, and the action is properly discontinuous. See Chapter 11 of T&G. One example given there is the cyclic group $Z_2$ acting on $X \times X$ whose orbit space is the symmetric square of  $X$. Under useful conditions, its fundamental group is that of $X$ made abelian. It would be good to see lots more examples.
Aug 17, 2016:  I can now refer to my answer to my own mathoverflow question on the relation of the van Kampen Theorem to the notion of descent.
Oct 17, 2016: I should add that a whole area of research into the use of strict higher groupoids in algebraic topology, one part of which is described in the book Nonabelian Algebraic Topology, (EMS 2011, 703 pages),  arose out of seeking generalisations to higher dimensions of the use of the fundamental groupoid.
December 23, 2016 It may be useful to point out that a new volume by Bourbaki "Topologie alg'ebrique" Ch 1-4, (Springer) 2016, uses the fundamental groupoid extensively, and relates its use to descent theory. It does have results on orbit spaces, but no example of applications. It does not use the fundamental groupoid on a set of base points.
December 9, 2019  It should be remembered that homotopy groups of a pointed space were introduced at the 1932 ICM at Zurich, by E. Cech, but the idea was not welcomed because of their abelian nature, so that they did not seem satisfactory higher dimensional versions of the fundamental group. The idea was taken up by Hurewicz, and the fascination and utility of homotopy groups led to the idea of a nonabelian version being regarded as a mirage, though the early homotopy theorists were fascinated by the action of the fundamental group on the higher homotopy groups (a comment of J,H.C. Whitehead, 1958).
We now know that you can construct higher analogues of the fundamental groupoid  for certain structured spaces, e.g. filtered spaces and $n$-cubes of pointed spaces. For the filtered case, see this 2011 book.
Note that the fascination and difficulty of the study of higher homotopy groups may, since these groups  are defined only for pointed spaces, have deterred people from considering the possible uses of the many pointed case. Also the use of groupoids in algebraic topology has been in the past dismissed by many.
Nonetheless, there is the basic fact of life (to use a term of JHCW)  that while "group objects in the category of groups are abelian groups", that is not so if the word "group" is replaced by "groupoid". In view of the importance of group theory in maths and science, it is reasonable to ask of the potential significance of that basic fact of life.
The questioner asks: " explicitly describing a groupoid as a colimit of "simpler" groupoids is something that it is not clear at all for me". This is answered in Appendix  B of Nonabelian Algebraic Topology.
More information on the history of fundamental groupoids and higher homotopy groupoids is in the Open Access article available from its link Mathematics Intelligencer.
Can someone explain why the more general theorem in NOT usually given?

A: I'm very fond of Ronnie Brown's proof of the Jordan curve theorem using the groupoid version of the van Kampen theorem. I find it easier to understand and reproduce than other comparably elementary proofs, such as Munkres' argument using covering spaces (which can be found in his textbook Topology: a first course). I guess this application isn't really a calculation, as requested, but I hope you like it.
(I guess I should mention that a small gap in the proof is filled in in this short note.)


text:
Q: Run time error 53 file not found for some files in directory I wrote a program to prompt the user to select a folder filled with .txt files and then extract information.
There are some files it cannot find and gives me a run time error 53 file not found despite the file being in the folder.
Debugging points to the 'Open MyFile For Input As #1' line.
If I specify the file path and run the macro it extracts the information so the file path is correct.
I looked at this solution
Excel VBA - Run-time error '53': File not found. But file was found
basically specifying a directory then trying to read each file from that directory but I get the same error.
Here is the original code to prompt the user to select a folder than read each file in the folder.
Sub read()
'PURPOSE: Send All Data From Text File To A String Variable

    Dim TextFile As Integer
    Dim FilePath As String
    Dim FileContent As String

    Dim MyFolder As String, MyFile As String

'Opens a file dialog box for user to select a folder

    With Application.FileDialog(msoFileDialogFolderPicker)
       .AllowMultiSelect = False
       .Show
       MyFolder = .SelectedItems(1)
       Err.Clear
    End With

'create a new object for files in that folder and apply the for/loop as below
    Dim objFSO As Object
    Dim objFolder As Object

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.getFolder(MyFolder)

    Dim fls As Object
    Dim i As Integer
    i = 1
    For Each fls In objFolder.Files

'File Path of Text File

    MyFile = Dir(MyFolder & "\" & fls.Name, vbReadOnly)

'Determine the next file number available for use by the FileOpen function

    TextFile = FreeFile

'Open the text file

    Open MyFile For Input As #1

A: by using the line you actually stripping the file name of its path
MyFile = Dir(MyFolder & "\" & fls.Name, vbReadOnly)

simply make it
MyFile = MyFolder & "\" & fls.Name


text:
Q: Control size of HTML map tips frame? I am using map tips to display geo-tagged images on QGIS 2.16.3, but I'm running into problems trying to control the overall size of the map tip pop-up frame.
I have followed the advice on other questions (e.g. Change size of frame for qgis map tip containing text) but it doesn't solve my problem...
This is what I'm using:

[%CONCAT('')%]

[% "DESCR" %], [% "image" %]

This shows the photo, with text below. However, the 'div' doesn't expand beyond about 400px wide so it limits how large the photo can be displayed - the map tip window then shows scroll bars to view the 'overflow' image and text below (as it does if I set the image size larger than the div, as expected) - I haven't found any documentation suggesting there is a limit to the pop-up map tip, but maybe it exists somewhere?
Before anyone asks why I need a large map tip and it would use up lots of my screen, I know that - I have specific desire to see the images as large as I can rather than just a 'thumbnail', and map tips are a great way of introducing an extra dimension to the map.
As a related follow up (which I can post separately if that helps) - is it possible to change the x,y location of the map-tip pop-up. It looks like it appears below-right of the point that I hover - can it be centre-centre, for example. Obviously when I've got a large pop-up, it would be good to be able to see all of it!
I've also found that if I have another layer that uses a similar map tip, but without the 'div' statement within the same project, it displays as (approx) 100px high and 400px wide. Odd behaviour... I know I can get round that by setting a 'div', but that's not the point!

A: I've done a little experimentation in this area with QGIS 3.0.0, and that appears to limit the dimensions of the Map Tip frame to exactly half the size of graphics area.
That implies that limit is baked into software, rather than being configurable within the project or layer.


text:
Q: why is this formula for a circle giving me an ellipsoid in Javascript but a circle in Python? I adapted the following code for python found on this page:
for a Javascript equivalent.
import math

# inputs
radius = 1000.0 # m - the following code is an approximation that stays reasonably accurate for distances < 100km
centerLat = 30.0 # latitude of circle center, decimal degrees
centerLon = -100.0 # Longitude of circle center, decimal degrees

# parameters
N = 10 # number of discrete sample points to be generated along the circle

# generate points
circlePoints = []
for k in xrange(N):
    # compute
    angle = math.pi*2*k/N
    dx = radius*math.cos(angle)
    dy = radius*math.sin(angle)
    point = {}
    point['lat']=centerLat + (180/math.pi)*(dy/6378137)
    point['lon']=centerLon + (180/math.pi)*(dx/6378137)/math.cos(centerLat*math.pi/180)
    # add to list
    circlePoints.append(point)

print circlePoints

The distance between these points is constant, as it should be.
My JS version is, as far as I know, equivalent:
  var nodesCount = 8;
  var coords = [];

  for (var i = 0; i <= nodesCount; i++) {
    var radius = 1000;
    var angle = Math.PI*2*i/nodesCount;
    var dx = radius*Math.cos(angle);
    var dy = radius*Math.sin(angle);

    coords.push([(rootLongitude + (180 / Math.PI) * (dx / EARTH_RADIUS) / Math.cos(rootLatitude * Math.PI / 180)),(rootLatitude + (180 / Math.PI) * (dy / EARTH_RADIUS))]);
  }

But when I output this, the coordinates are not equidistant from the center.
This is enormously frustrating -- I've been trying to debug this for a day.  Can anyone see what's making the JS code fail?

A: You somehow got lat/lon reversed.

var linkDistance = 10; //$('#linkDistance').val();
var nodesCount = 8;
var bandwidth = "10 GB/s";
var centerLat = 35.088878;
var centerLon = -106.65262;
var EARTH_RADIUS = 6378137;

var mymap = L.map('mapid').setView([centerLat, centerLon], 11);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw', {
  maxZoom: 18,
  attribution: 'Map data © OpenStreetMap contributors, ' +
    'CC-BY-SA, ' +
    'Imagery © Mapbox',
  id: 'mapbox.streets'
}).addTo(mymap);

function drawNext(centerLat, centerLon) {
  var coords = [];

  for (var i = 0; i < nodesCount; i++) {
    var radius = linkDistance * 1000;
    var angle = Math.PI * 2 * i / nodesCount;
    var dx = radius * Math.cos(angle);
    var dy = radius * Math.sin(angle);

    var lat = centerLon + (180 / Math.PI) * (dy / 6378137);
    var lon = centerLat + (180 / Math.PI) * (dx / 6378137) / Math.cos(centerLon * Math.PI / 180);

    coords.push([lat, lon]);
  }

  for (var i = 0; i < coords.length; i++) {
    new L.Circle(coords[i], 500, {
      color: 'black',
      fillColor: '#f03',
      fillOpacity: 0.1
    }).addTo(mymap);
    console.log("added circle to: " + coords[i]);
  }

}

drawNext(centerLon, centerLat);

var popup = L.popup();

function onMapClick(e) {
  popup
    .setLatLng(e.latlng)
    .setContent("You clicked the map at " + e.latlng.toString())
    .openOn(mymap);
}

mymap.on('click', onMapClick);
#mapid {
  height: 500px;
}

<link href="https://npmcdn.com/leaflet@1.0.0-rc.2/dist/leaflet.css" rel="stylesheet"/>