text:
Q: Zend Framework - Override module
I'm working on multi-website CMS in Zend Framework.
I've came to a point where I need to override module from application/ folder in my website/application folder.
A bit better explanation of my issue:
    Here's tree of my application (important part):
library/
application/
        module1/
            controllers/
            models/
            ....
        module2/
            controllers/
            models/
            ....
websites/
  website1.com/
       application/
            module1/
                controllers/
                models/
                ....

So what I need to do is that module1/ in websites/website1.com/application/ override module1/ in application, IF it exists. I want everything in module1/ in websites folder to override everything in main application folder.
I'd also like if there are 2 controllers in this module1 (for example IndexController and TestController) and if I put only TestController in websites folder under module1/controllers to override ONLY TestController from Application folder and to get IndexController from main folder.
Sorry if I failed to explain exactly what I'm trying to achieve. If there's something unclear, please ask.
Thank you.

Edit:
Okey, first of all - thanks for your comments.
Reason for having websites/ folder is, mostly because of vhost as I prefer that all of my websites have separate (public?) folders, and reason for having one library with application folder is because, obviously, upgrade reasons (so when I, for example, upgrade Zend - I don't need to upgrade it for every website).
I'll most likely rarely use overriding option for controllers, and yes, I'd even prefer if I could, for example, extend main Controller (for example - IndexController) and override some functions, but I thought that's way harder then override whole class.
Here's full structure of my application:
 library/ - Library folder contains Zend and many other classes that I'll use in my application.
     Zend - Zend Framework
     MyCMS - Classes from my old CMS.
 sites/ - Folder that contains websties.
     website_1 - Website one.
         application/ - Application folder for website one. If I need to redefine module or something. So, if I need to override module: main_module, I'll  create folder main_module here with files that I want to override.
         config/ - Configuration for website_1 - if I need to override, for example, application.ini
         lang/ - Language files for this specific website.
         templates/ - Templates folder for website (layouts and templates). By the way, I'm using smarty.
             default/ - Main template.
                 layout/ - Layouts for Zend View.
                 css/
                 js/
                 images/
                 modules/
         files/ - Place to upload files in, for this website. This will contain user avatars and stuff.
         index.php - Main file that runs bootstrap and application.
         Bootstrap.php - Inherited bootstrap. In case I need to override some functions from default bootstrap.
 application/ - Main folder that contains application modules and stuff.
    main_module/
         configs/ - Module configuration.
             config.ini
         controllers/ - Controllers for this module.
         modules/ - Submodules. There are like boxes that I display on website. For example, if my main module is "news", here, I'll make new sub-module to display box with statistics.
             submodule/
                 services/ - XML/JSON/whatever service. If someone targets controller in services with specific parametars, it'll return response in requested format.
                     controllers/ - Services will only have controllers.
                 configs/ - Configuration for this submodule.
                 controllers/ - Controllers for this submodule.
                 models/ - Models for this submodule.
                 lang/ - Language files for this submodule.
                 template/ - Templates for this submodule.
                     helpers/
                     css/
                     js/
                     images/
                     index.html
         models/ - Models for main module.
         lang/
         services/  - Main module will also have services. See submodule services for explanation.
             controllers/
         template/
             helpers/
             css/
             js/
             images/
             index.html
     Bootstrap.php  - This is main bootstrap file that every website's bootstrap file will extend (and override some methods - if needed).

A: Update
Even though I highly discourage your directory structure, it's your application and you should structure it however you like.
To load multiple controllers, you should create a Front Controller Plugin to add paths to the controller directories stack
class My_Controller_Plugin_Paths extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch()
    {
        // Something like this...
        // Would be best to load paths via config/database or somewhere
        $dispatcher = Zend_Controller_Front::getInstance()->getDispatcher();
        $dispatcher->addControllerDirectory('/path/to/website1.com/controllers')
                   ->addControllerDirectory('/path/to/website2.com/controllers');
    }
}

This is entirely untested, but you get the idea. Just make sure you register the plugin with the Front Controller in you bootstrap

I'd agree with @Laykes. This is a badly structured application.
I'm not sure of your exact requirements, but if it were my application, I would try to structure it like this:
/application
    /modules
        /default
            /controllers
                /IntexController.php      // Default_IndexController
                /Website1com
                    /IndexController.php  // Default_Website1com_IndexController (possibly extends Default_IndexController)

Here you can see a properly structured class inheritance without creating totally separate, and probably duplicate, application folder.
Autoloading anything like this though totally depends on you and your priorities. You could do a number of things, each with their own +ve's and -ve's.

*

*You could throw all paths into your include_paths in the order you want

*Check files exist and load from a front controller plugin

To name a couple.


text:
Q: Collecting in map using Collector.toMap I am not able to get my head around a simple problem.
I have a map of type X and it needs to be transformed into map of type Y
mapOfTypeX.entrySet().stream().map(e-> transform(e)).collect(Collector.toMap(....));

The transform function takes the entry set and gives back Map of type Y e.g Map<key,SomeClassObjectAsValue>
public Map<key,SomeClassObjectAsValue> transform(Map.Entry<String,Person> entry){}

I am not sure what to pass to the Collector.ToMap function. The existing code is an imperative code and it passes the map of type Y to the transform function and doing map.putall

A: Basically, you need to use the collect function instead of using toMap wrapper.
mapOfTypeX.entrySet().stream()
          .map(e-> transform(e))
          .collect(HashMap::new, HashMap::putAll, HashMap::putAll);

A: You could use flatMap of streams and combine all entries from all maps recieved from transform method as:
Map<key,SomeClassObjectAsValue> newMap =
    mapOfTypeX.entrySet()
        .stream()
        .flatMap(e -> transform(e).entrySet().stream())
        .collect(Collectors
            .toMap(Map.Entry::getKey, Map.Entry::getValue,(oldValue, newValue) -> oldValue));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which book to choose? i learned user space programs(with sys calls and ipc).Now i need to jump into kernel space-building modules and device drivers particularly.I have googled a lot and most sites project codes like rocket science.With what book/pdf can I get a good start?
thanks in advance..

A: I think you can try Robert loves book (3rd Edition, Kernel development), and if you are interested in Linux device drivers (try Oreilly Linux device drivers book, 3rd edition).
Linux Device Drivers, 3rd Edition by Jonathan Corbet, Alessandro Rubini and Greg Kroah-Hartman
Linux Kernel Development (3rd Edition) by Robert Love.
May be later you can refer
understanding the Linux kernel for more advance stuff.
before doing Kernel programming, do some reading on Operating systems concepts ( THIS IS A GOOD BOOK
Operating System Concepts by Abraham Silberschatz, Peter B. Galvin and Greg Gagne - ANY EDITION)
Those are really good books to start Kernel development.
Hope this helps.
Cheers,
Tharanga


text:
Q: Nullable Interface does not trigger CS8602 I've encountered a few times now where I have nullable enabled and a property or field marked as a nullable interface type (with an appended ?), then if I go to use the property or field without a null check, I receive no error. (I would expect CS8602 - Dereference of a possibly null reference., and in concrete type properties and fields I do receive this error).
I am not sure if this is a Roslyn bug or something I don't adequately understand.
Additional information:

*

*.NET 5

*C# 9

namespace dotnet_scratch {

    interface IFoo {
        string? name { get; set; }

        void fooAction ();
    }

    interface IFooGeneric<T> {
        string? name { get; set; }
        void fooAction( );
    }

    public class FooClass {
        IFoo? fooInterface;
        IFooGeneric<string>? fooInterfaceString;

        FooClass? fooClass;

        void doStuff( ) {
            System.Console.WriteLine( fooInterface.name );
            System.Console.WriteLine( fooInterfaceString.name );
            fooInterface.fooAction();
            fooInterfaceString.fooAction();
            fooClass.fooAction();
        }
        void fooAction () {}
    }
}

In the capture, the three highlighted errors are labeled:
(field) IFooGeneric<string>? FooClass.fooInterfaceString
'fooInterfaceString' may be null here.

Dereference of a possibly null reference. [dotnet_scratch]csharp(CS8602)

Additionally mousing over fooInterface.fooAction() and fooInterfaceString.fooAction() say:
'fooInterfaceString' is not null here.
My question is why is a property or field marked as IInterfaceType? not flagged as being potentially Nullable as is the case with the concrete typed properties and fields?

A: The compiler's view of whether the variable can have a null value or not has nothing to do with the type of the variable is a class or whether it's an interface - it's whether it's previously been dereferenced.
You received warnings for these two lines:
System.Console.WriteLine( fooInterface.name );
System.Console.WriteLine( fooInterfaceString.name );

... because that's the first time each of those variables has been dereferenced. But the compiler assumes that if both of those lines have executed without throwing an exception, then the later uses of the same variables:
fooInterface.fooAction();
fooInterfaceString.fooAction();

... will be fine. Neither variable can be null by this point in the execution flow, because otherwise one of the earlier lines would have thrown an exception. (The "nullability flow" doesn't take into account the possibility that another thread could change the value of the variable in the middle.)


text:
Q: Which structure to use with JUNIT test? I have a Number of tests. Each test contains different commands verify() and command(). The order and number of times I need to check these vary though depending on the test. How can I structure this in a convenient way. I have been playing with Suites and Categories but can´t find a good solution. in the JUNIT GUI I would like to see the Testname and bellow it the teststeps command or verify. Any ideas?

A: I have found that with maven and modern IDEs, the usefulness of test suites is not all that apparent.
Maven will run all your tests by default; and any IDE will allow you to run all your tests or select tests to run, by package, for example. I generally find that creating tests classes within different packages is all the organization I every really utilize.
It worries me that you say the "order and number" of times you need to test vary. I am not clear on exactly what you mean, but if you mean that in order for a test to pass, it is dependent on the order (and times) that other tests execute, then you need to re-architecture your tests. (Particularly in the case of unit tests.)
No test should ever depend on another test. Execution order is not guaranteed, and may execute differently in different environments, or could even be executed in parallel.
Look at @Before, @After, @BeforeClass, @AfterClass (http://junit.sourceforge.net/doc/faq/faq.htm#organize_3) for more info on initialization of tests. I'm not sure if that is the solution to your problem, though.


text:
Q: Error when trying to acces parent folder in Electron/Node.js I'm trying to check whether a path in a parent directory is a file or a directory.
My file system looks like this:

*

*files/

*

*html/

*

*index.html

*javascript/

*

*index.js

*test/

*

*test.jpg

Electron is started from the parent directory of files/.
My code in the index.js file:
console.log(`file://${__dirname}/../test/test.jpg`);
console.log(fs.lstatSync(`file://${__dirname}/../test/test.jpg`).isFile());

When I start Electron I get two messages in the log. The first one is the path of the picture I want to access (test.jpg). When I paste this path into my browser, the picture is shown, so it is the correct path.
But the second message is an error:
Uncaught Error: ENOENT: no such file or directory, lstat

And then the same path in single quotation marks ('').
I used to have the index.js and the index.html file in the same path from which electron is started from (parent folder of files/) and it worked, so I guess that it has problems accesing a parent folder.
How can I solve this?

A: The Node fs module works with file paths, not URLs, so you need to pass a valid path to fs.lstatSync:
fs.lstatSync(`${__dirname}/../test/test.jpg`).isFile()


text:
Q: Add data rows to XML table in C# I'm trying to figure out how to store data using C#.
I'm new to C# data storage, having used PHP and MySQL to do this kind of thing in the past. After doing some research, it seems that using XML serialization is the way to go but I'm not quite sure of all the details.
So far, I've created my table with several columns:
private void SerializeDataSet()
{
    XmlSerializer ser = new XmlSerializer(typeof(DataSet));

    // Creates a DataSet for user info
    DataSet vault = new DataSet("vault");
    DataTable table_users = new DataTable("users");
    DataColumn last_name = new DataColumn("last_name");
    DataColumn first_name = new DataColumn("first_name");
    DataColumn birthdate = new DataColumn("birthdate");
    DataColumn role = new DataColumn("role");
    table_users.Columns.Add(last_name);
    table_users.Columns.Add(first_name);
    table_users.Columns.Add(birthdate);
    table_users.Columns.Add(role);

    // adds table
    vault.Tables.Add(table_users);

    // serialized table
    string filename = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Resources) + "Vault_Tec_storage";
    TextWriter writer = new StreamWriter(filename);
    ser.Serialize(writer, vault);
    writer.Close();
}

Now what I can't figure out how to do, is actually add the data to that table. For example, if I wanted a method to process a user registration for John Doe, born 10/15/1975 with role "0," how would I go about doing that?

A: you might want to try the DataSet ReadXml()
Usage is something like this:
using (StreamReader reader = new StreamReader("C://filepath.xml"))
{
     byte[] fullByte = Encoding.ASCII.GetBytes(reader.ReadToEnd());
     DataSet dataSet = new DataSet();
     MemoryStream mStream = new MemoryStream(fullByte);
     mStream.Position = 0;
     dataSet.ReadXml(mStream);

     /*
     while DEBUGGING, you'll notice here that your `dataSet` is now populated by
     collection of tables. These table came for each sub nodes followed with an
     internal ID as relationship between nodes. From here, you may add values in
     your table like the usage below.
     */

     // ex. if Table is like this
     // Name | Age
     // John | 09/10/2015
     DataTable dt = dataSet.Tables[0];

     dt.Rows.Add(
       // array of objects
       new object[] { "New John", "09/11/2015" }
     );

     //OR

     DataRow dr = dt.NewRow();
     dr["Name"] = "New John";
     dr["Age"] = "09/11/2015";
     dt.Rows.Add(dr);
}

hopefully this helps, if you have a specific case you're struggling at, kindly line it under the comment section, we'll help you out.
Thanks!

A: Try this
private void SerializeDataSet()
        {
            // Creates a DataSet for user info
            DataSet vault = new DataSet("vault");
            DataTable table_users = new DataTable("users");
            table_users.Columns.Add("last_name", typeof(string));
            table_users.Columns.Add("first_name", typeof(string));
            table_users.Columns.Add("birthdate", typeof(DateTime));
            table_users.Columns.Add("role", typeof(int));

            // adds table
            vault.Tables.Add(table_users);
            table_users.Rows.Add(new object[] { "Doe", "John", DateTime.Parse("10/15/1975"), 0 });

            // serialized table
            string filename = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Resources) + "Vault_Tec_storage";
            vault.WriteXml(filename);
        }


text:
Q: how to get the count of specific field from different objects in an array in JS var Universities = [{
    "State": "ILLINOIS",
    "University": "North Park University",
    "Place": "Chicago"
}, {
    "State": "VERMONT",
    "University": "University of Vermont",
    "Place": "Berlington"
}, {
    "State": "FLORIDA",
    "University": "North Wood University",
    "Place": "Midland"
}, {
    "State": "NEW YORK",
    "University": "Pace State University(undergradations& post graduations",
    "Place": "NY"
}, {
    "State": "ILLINOIS",
    "University": "University of North Alabama",
    "Place": "Florence"
}, {
    "State": "ILLINOIS",
    "University": "Louisiana Technology University",
    "Place": "Ruston"
}, {
    "State": "North Carolina",
    "University": "East Carolina University",
    "Place": "Green Ville"
}, {
    "State": "ARKANSAS",
    "University": "Arkansas State University",
    "Place": "Jones boro"
}, {
    "State": "Oklahoma",
    "University": "University of Tulsa",
    "Place": "Tulsa"
}, {
    "State": "ILLINOIS",
    "University": "Rush University",
    "Place": "Chicago"
}]

How many UNIVERSITIES are there in ILLINOIS state?
Please check and help me out.

A: if i understand your question correctly , maybe use filter can figure it out :
var result = Universities.filter(function (ele) {
    return ele.State == 'ILLINOIS';
});

console.log(result);


text:
Q: How to tell ModemManager to ignore some or all of tttyUSB*? I want to tell ModemManager to leave my Tungsten E (Palm Pilot) alone. I'm running Ubuntu 16.04.6 LTS
My logs tell me:
Jul 30 22:00:41 bat kernel: usb 1-1.1: new full-speed USB device number 29 using ehci-pci
Jul 30 22:00:41 bat kernel: usb 1-1.1: New USB device found, idVendor=0830, idProduct=0060
Jul 30 22:00:41 bat kernel: usb 1-1.1: New USB device strings: Mfr=1, Product=2, SerialNumber=5
Jul 30 22:00:41 bat kernel: usb 1-1.1: Product: Palm Handheld
Jul 30 22:00:41 bat kernel: usb 1-1.1: Manufacturer: Palm, Inc.
Jul 30 22:00:41 bat kernel: usb 1-1.1: SerialNumber: PalmSN12345678
Jul 30 22:00:41 bat kernel: visor 1-1.1:1.0: Handspring Visor / Palm OS converter detected
Jul 30 22:00:41 bat kernel: usb 1-1.1: Handspring Visor / Palm OS converter now attached to ttyUSB0
Jul 30 22:00:41 bat kernel: usb 1-1.1: Handspring Visor / Palm OS converter now attached to ttyUSB1
Jul 30 22:00:41 bat mtp-probe[5886]: checking bus 1, device 29: "/sys/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.1"
Jul 30 22:00:41 bat mtp-probe[5886]: bus: 1, device: 29 was not an MTP device
Jul 30 22:00:43 bat snapd[1623]: hotplug.go:193: hotplug device add event ignored, enable experimental.hotplug
Jul 30 22:00:43 bat snapd[1623]: hotplug.go:193: hotplug device add event ignored, enable experimental.hotplug
Jul 30 22:00:45 bat ModemManager[1303]: <warn>  (ttyUSB1): port attributes not fully set
Jul 30 22:00:45 bat ModemManager[1303]: <warn>  (ttyUSB0): port attributes not fully set
Jul 30 22:01:27 bat ModemManager[1303]: <warn>  (ttyUSB0): close blocked by driver for more than 7 seconds!
Jul 30 22:01:33 bat ModemManager[1303]: <info>  Creating modem with plugin 'Generic' and '2' ports
Jul 30 22:01:33 bat ModemManager[1303]: <warn>  Could not grab port (tty/ttyUSB1): 'Cannot add port 'tty/ttyUSB1', unhandled seria
Jul 30 22:01:33 bat ModemManager[1303]: <warn>  Could not grab port (tty/ttyUSB0): 'Cannot add port 'tty/ttyUSB0', unhandled seria
Jul 30 22:01:33 bat ModemManager[1303]: <warn>  Couldn't create modem for device at '/sys/devices/pci0000:00/0000:00:1a.0/usb1/1-1
Jul 30 22:02:04 bat ModemManager[1303]: <warn>  (ttyUSB0): close blocked by driver for more than 7 seconds!

I want to prevent ModemManager from trying anything with /dev/ttyUSB[01] or even /dev/ttyUSB*.

A: Create a udev rule file, e.g. /etc/udev/rules.d/80-palm.rules:
ATTRS{idVendor}=="0830", ATTRS{idProduct}=="0060", ENV{ID_MM_DEVICE_IGNORE}="1"

Reload the udev rules:
udevadm control --reload-rules && udevadm trigger

Plug in your Palm device.


text:
Q: Entity Framework not sending Where clauses as WHERE clauses to SQL Server I have a simple DB that has Sites, and each Site has a bunch of Posts.
I'm trying to get all the "Public" Posts of a certain Site (I have a variable called site that is already an instance brought by EF)
The first obvious thing is:
  var posts = from post in site.Posts
              where post.Public == true
              orderby post.PublicationTime descending
              select post;

This brings me what I want, but looking into SQL Server Profiler, the WHERE only is filtering the Public field, not the Site. In fact, running in SQL Server the query that Profiler captures indeed brings back all the posts from all the sites (and this is obviously being filtered in the ASP.Net side later).
Then I tried:
  var posts = from post in db.Posts
              where post.Site == site && post.Public == true
              orderby post.PublicationTime descending
              select post;

Same result.
Am I doing something fundamentally stupid here?
Does Entity Framework ALWAYS filter in the client-side?
Thanks!
Daniel

A: In case anyone has a problem with this using method syntax:
If you pass a Func<TEntity,Boolean> to the .Where method, the filter function is applied after the query returns from the database.  This is because the return value of the .Where method returns an IEnumerable.  On the other hand, if you pass an Expression<Func<TEntity,Boolean> to the .Where method, the filter function generates a where clause that is sent to the database.  This is because the .Where returns an IQueryable.  As long as you stick with IQueryables you are building the query to send to the database.  When you return an IEnumerable, everything before the method is used to create the query and everything after the IEnumerable is applied to what is brought back.  This only really matters if you are storing your lambda function in a variable.  If you pass the lambda directly into the .Where method, you generally don't have an issue.  Hope this helps!!
IEnumerable Where: https://msdn.microsoft.com/en-us/library/bb549418(v=vs.110).aspx
IQueryable Where: https://msdn.microsoft.com/en-us/library/bb535040(v=vs.110).aspx

A: You need to understand the difference between LINQ to Entities and LINQ to Objects. It is incredibly important to keep track of this when working with the Entity Framework.
When you issue a query against an ObjectContext, then you are working in LINQ to Entities. This will return an IQueryable. As long as you are working with a variable of type IQueryable, you can further compose the query with the LINQ API, and when you finally enumerate the result, it will be converted to SQL.
But you say:

(I have a variable called site that is already an instance brought by EF)

Here you are querying a property of an object, so you are working in LINQ to Objects, not LINQ to Entities. This means that your query has a different provider, and will not be converted to SQL.
Regarding your second query:
var posts = from post in db.Posts
            where post.Site == site && post.Public == true
            orderby post.PublicationTime descending
            select post;

The EF doesn't let you do identity comparisons on instances in L2E. You have to compare the key instead. Try:
var posts = from post in db.Posts
            where post.Site.Id == site.Id && post.Public
            orderby post.PublicationTime descending
            select post;

BTW, I changed post.Public == true to post.Public. I think it's cleaner.


text:
Q: Problems with rider and xamarin.forms creating a solution cross platform using host linux system I have Linux as my base system
but when creating a cross platform solution in rider
create the entire project,
but it gives me an error with the ios solution,
I understand that ios does not compile on linux and there are alternatives on windows and
the option to pair with a mac or use the cloud
but I only create the project and it won't let me update
the Android solution,
my question is
How can I create a Cross Platform solution and delete the iOS solution?
I understand I can create a Native Android solution, but that is not the case,
What files can I configure to remove the iOS solution? in a cross platform project, of course.
It also won't let me update Xamarin.Android.Support,
I tried to remove the iOS solution but it gives me an error.


text:
Q: python xml and csv extract i have 2 set of files - (1) CSV file (the main file) (2) XML file.
CSV file -
emp_id
1
2
3
4

XML File -
<employee>
    <emp id="1" />
    <emp id="2" active="yes">
        <tag k="age" v="55" />
    </emp>
    <emp id="3" active="yes">
        <tag k="name" v="scott" />
    </emp>
    <emp id="4" active="no">
        <tag k="address" v="Texas" />
    </emp>
    <emp id="5" gender="male"/>
    <emp id="8" />
    <emp id="9" />
    <emp id="10" />
    <emp id="11" />
</employee>

My objective is have a csv file where the emp_id from the csv file is matched with the XML file, and only the matched emp_id is created in the new csv file. I need 2 csv files like below -
1st file.
emp_id,active,gender
1,,
2,yes,
3,yes,
4,no,
5,,male

2nd file.
emp_id,key,value
2,age,55
3,name,scott
4,address,Texas

I can read the CSV file in pandas, and XML file in Python. But don't know how to combine them and extract keys and value from the XML
Any help is appreciated.

A: Another method.
from simplified_scrapy import SimplifiedDoc, utils
empIds = ['1', '2', '3', '4', '5']
# empIds = [id.strip() for id in utils.getFileLines('your csv file path')[1:]]

xml = '''<employee>
    <emp id="1" />
    <emp id="2" active="yes">
        <tag k="age" v="55" />
    </emp>
    <emp id="3" active="yes">
        <tag k="name" v="scott" />
    </emp>
    <emp id="4" active="no">
        <tag k="address" v="Texas" />
    </emp>
    <emp id="5" gender="male"/>
    <emp id="8" />
    <emp id="9" />
    <emp id="10" />
    <emp id="11" />
</employee>
'''
# xml = utils.getFileContent('your xml file path')

rows1 = [['emp_id', 'active', 'gender']]
rows2 = [['emp_id', 'key', 'value']]
doc = SimplifiedDoc(xml)
for id in empIds:
    emp = doc.select('emp#' + id)
    if emp:
        rows1.append([id, emp.get('active'), emp.get('gender')])
        tags = emp.selects('tag')
        if tags:
            for tag in tags:
                rows2.append([id, tag['k'], tag['v']])

utils.save2csv('csv1.csv', rows1, newline='')
utils.save2csv('csv2.csv', rows2, newline='')

Result csv1:
emp_id,active,gender
1,,
2,yes,
3,yes,
4,no,
5,,male

Result csv2:
emp_id,key,value
2,age,55
3,name,scott
4,address,Texas

A: First df: Read XML and create DataFrame
import xmltodict
with open('XmlFile.xml') as fd:
    xmlfile = xmltodict.parse(fd.read())
df_xmlfile = pd.DataFrame(xmlfile["employee"]["emp"])
df_xmlfile.columns = [col.replace("@","") for col in df_xmlfile.columns]

Read CSV as DataFrame
df_csvfile = csvfile=pd.read_csv("CsvFile.txt")

Join boths dfs
df_first = df_csvfile.join(df_xmlfile[["active", "gender"]])

Second df:
Get rows containing a tag, unpack those rows to get the keys and values and create second df
df_temp = df_xmlfile[~df_xmlfile["tag"].isna()][["id", "tag"]]
df_second = pd.DataFrame({"emp_id": df_temp["id"],
              "key": [row["@k"] for row in df_temp["tag"]],
              "value": [row["@v"] for row in df_temp["tag"]]})

A: Lets create first dataframe:
# this dataframe should be read from csv in your case
df = pd.DataFrame({
    'emp_id':[1, 2, 3, 4, 5]
})

Than define XML:
xml = '''<employee>
    <emp id="1" />
    <emp id="2" active="yes">
        <tag k="age" v="55" />
    </emp>
    <emp id="3" active="yes">
        <tag k="name" v="scott" />
    </emp>
    <emp id="4" active="no">
        <tag k="address" v="Texas" />
    </emp>
    <emp id="5" gender="male"/>
    <emp id="8" />
    <emp id="9" />
    <emp id="10" />
    <emp id="11" />
</employee>'''

Read data from XML:
d = defaultdict(list)
# here we read XML from string, in your case it should be read from file
root = et.fromstring(xml)
emps = root.xpath('//employee/emp')
# iterate over elements "emp" and extract data
for emp in emps:
  # here we extract attributes id, active and gender
  d['id'].append(int(emp.get('id')))
  d['active'].append(None if emp.get('active') is None else emp.get('active'))
  d['gender'].append(None if emp.get('gender') is None else emp.get('gender'))
  # here we extract age
  age = emp.find('./tag[@k="age"]')
  d['age'].append(None if age is None else age.get('v'))
  # here we extract address
  address = emp.find('./tag[@k="address"]')
  d['address'].append(None if address is None else address.get('v'))

Than create dataframe from dict:
df_xml = pd.DataFrame(d)

Than merge data using emp_id / id columns:
df_merged = pd.merge(df, df_xml, left_on = 'emp_id', right_on='id', how = 'inner')
del df_merged['id']

df_merged.head(10)

Output:


text:
Q: Accessing WidgetCenter from Objective-C App I have an existing Objective-C app and have developed a SwiftUI iOS 14 Widget for it. So far so good. Now I am trying to reload the timeline from my Objective-C app. I understand that there are no Objective-C api for accessing WidgetCenter, so I have implemented the bridging steps outlined in Apple's documentation (at least I think I have since I am totally new to Swift). I cannot seem to be able to get Widget Center nor WidgetCenter.shared.reloadAllTimelines()recognized in my Objective-C app. I have tried many approaches with no success, so I must be doing something wrong. Any help or suggestions would be greatly appreciated.

A: I faced with the same issue. The solution for this was to create a swift file for example: WidgetKitHelper. Create the assigned swift-objc header with that too (bridging header file) if it not generated automatically you can add it by manually (search for it).
In the helper object you can get access to widgetkit, and if you do the rest to be able to see the swift code from your objc code, you can use this as a wrapper.
Tips:
import WidgetKit

@available(iOS 14.0, *)
@objcMembers final class WidgetKitHelper: NSObject {

    class func reloadAllWidgets(){

        #if arch(arm64) || arch(i386) || arch(x86_64)
        WidgetCenter.shared.reloadAllTimelines()
        #endif

    }
}

obj-c code:
First import the swift code by adding:
#import "YourProjectName-Swift.h"

Then you can use:
[WidgetKitHelper reloadAllWidgets];


text:
Q: print forums under common category How would I do to print the forums under the common category?
Like if I have 3 forums with the same cat_id I want to print them together under the category. You understand?
Its hard to explain. Like this:
Category 1
Forum 1
Forum 2
Category 2
Forum 45
Forum 74
Not
Category 1 Forum 1
Category 1 Forum 2
CREATE TABLE `forums` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`forum_name` varchar(80) NOT NULL DEFAULT 'New forum',
`forum_desc` text,
`cat_id` int(10) unsigned NOT NULL DEFAULT '0'
 PRIMARY KEY (`id`)
)

CREATE TABLE `categories` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`cat_name` varchar(80) NOT NULL DEFAULT 'New Category'
PRIMARY KEY (`id`)
)

My english is poor im sorry
while ($row=mysql_fetch_assoc($query)) {

echo $row['cat_name'].$row['forum_name'];

}

A: I assume you have the working query?
 $old_cat = '';
 while ($row=mysql_fetch_assoc($query)) {
    if($row['cat_name'] != $old_cat){
        echo $row['cat_name']."
\n";
        $old_cat = $row['cat_name'];
    }
    echo $row['forum_name']."
\n";
 }


text:
Q: OOP Java: Better to extend a class or create a new instance of the subclass? I'm having trouble with the concepts of object oriented programming.
Is it better to extend a class or create a new object within a class?
Under which circumstances would you extend a subclass versus creating a new instance of that subclass within the calling class? The example is in Java but I imagine the concepts will work in other OOP languages.
I appreciate your insights
class Mini {
// I want to use the members of this class in another class
    int myInt;

    public Mini(int myInt){
        this.myInt = myInt;
    }

    public int myMethod(){
        return this.myInt;
    }
}

// should I create a new instance of Mini here?
class Maxi {
    Mini myMini = new Mini(5);

    public Maxi(){
        int miniInt = myMini.myMethod();
        System.out.print(miniInt );
    }
}

// or should I have Maxi extend Mini?
class Maxi extends Mini {
    public Maxi(int myInt){
        System.out.print(this.myInt);
    }
}

A: You extend a class when it has an is-a relationship. For example, a Cat is an Animal. A Cat is not a CatFood but it might use CatFood.
In your case, I'm not sure what MiniMaxi are, but it doesn't sound like Maxi is a Mini, rather it uses one.
In general, try to favor composition (using objects) over inheritance, especially in single inheritance languages like java.

A: The best answer to that question is another question: does class B use class A or does class B build on class A?

A: Well one question you should ask yourself is what other uses will this class have? Will you still need the functionality of this class in the subclass? Will you have more classes that will also inherit mini?
The goal is to save duplication. You need to know more about your use case to be sure.
I would really only inherit if you have more than one thing extending the top class and using its functionality and variables. If you are just using for a method signature interface is usually a better bet.

A: *

*In first case is an aggregation relation, named has-a. Class Maxi has a attribute, whose type is class Mini.

*In second is an inheritance relation, named Is-a. Class Mini is subclass of class Maxi and Maxi is supclass of class Mini. When a class Maxi is extended, the new class inherits all the fields (protected or public data and methods) of the class Mini.

A: The distinction between "is-a" and "has-a" is very important and critical. If you are not sure about "is-a" relation, never use inheritance. So if you know that conceptually B is not A then don't use inheritance for B. Also if you are being tempted to inherit from a class just to reuse some functionality, never do that - use "has-a" composition/aggregation techniques.


text:
Q: Question: Concurrent queue with max concurrency (per cacheKey) this is more of a opinionated question. I do have a working solution, but I'm not 100% comfortable with it, as it has it's flaws.
Maybe someone can help me to improve this.
Goal:
I have an external api that only allows 4 calls to be made concurrently against it (for each user). Our app can impersonate multiple users at once.
So the issue comes, if more than 4 calls are made against the api simultaneously. (sometimes more than 20 calls are made)
Using a batched approach with Promise.all and chunking would be very inefficient, as the calls have a different runtime each.
Ideally, the queue would work FIFO and as soon as one call finishes, the next call is started. At the current standing, I created 4 own FIFO queues with somewhat of a Promise chain and I fill these evenly (if all are running).
The problem that I have is, that I do not know how long a request is running.
So choosing one of the queues can lead to an overall longer runtime as necessary.
The calls are automatically rejected after 30s from the external api, so no dead lock here.
Another problem that I have is, that I have to return the data provided from the api to a dependency. The queue is called/filled from withan a callback function...
This is wrapped in a Promise itself, so we can wait as long as we want.
But storing the values in a cache for later retrieval is no option either.
So long story short, here is the code
class QueuingService {
    /** ~FIFO queue */
    private static queue: Record<string, { promise: Promise<Function>, uuid: string }[]> = {};
    private static MAX_CONCURRENCY = 4

    /** cacheKey is used as cachekey for grouping in the queue */
    public static async addToQueueAndExecute(func: Function, cacheKey: string) {
        let resolver: Function | null = null;
        let promise = new Promise<Function>(resolve => {
            resolver = resolve;
        });
        //in the real world, this is a real key created by nanoId
        let uuid = `${Math.random()}`;

        Array.isArray(this.queue[cacheKey])
            ? this.queue[cacheKey].push({ promise: promise, uuid: uuid })
            : this.queue[cacheKey] = [{ promise: promise, uuid: uuid }];

        //queue in all calls, until MAX_CONCURRENCY is reached. After that, slice the first entry and await the promise
        if (this.queue[cacheKey].length > this.MAX_CONCURRENCY) {
            let queuePromise = this.queue[cacheKey].shift();
            if (queuePromise){
                await queuePromise.promise;
            }
        }
        //console.log("elements in queue:", this.queue[cacheKey].length, cacheKey)

        //technically this wrapping is not necessary, but it makes to code more readable imho
        let result = async () => {
            let res = await func();
            if (resolver) {
                //resolve and clean up
                resolver();
                this.queue[cacheKey] = this.queue[cacheKey].filter(elem => elem.uuid !== uuid);
            }
            //console.log(res, cacheKey, "finshed after", new Date().getTime() - enteredAt.getTime(),"ms", "entered at:", enteredAt)

            return res;
        }

        return await result();
    }
}

async function sleep(ms:number){
    return await new Promise(resolve=>window.setTimeout(resolve,ms))
}

async function caller(){
    /* //just for testing with fewer entries
    for(let i=0;i<3;i++){
        let groupKey = Math.random() <0.5? "foo":"foo"
        QueuingService.addToQueueAndExecute(async ()=>{
            await sleep(Math.floor(4000-Math.random()*2000));
            console.log(i, new Date().getSeconds(), new Date().getMilliseconds(),groupKey)
            return Math.random()
        },groupKey)
    }
    */

    for(let i=0;i<20;i++){
        let groupKey = Math.random() <0.5? "foo":"foo";
        let startedAt = new Date();
        QueuingService.addToQueueAndExecute(async ()=>{
            await sleep(Math.floor(4000-Math.random()*2000));
            console.log(i, new Date().getTime()-startedAt.getTime(),groupKey)
            return Math.random()
        },groupKey)
    }

}
caller()

Also, here is a playground with the code to play around with:
https://www.typescriptlang.org/play?#code/MYGwhgzhAECKCuBTeBLAdgcwMqIE4DcVhFoBvAWACgBIAegCp7oA-AMQElWB5aARySTR6tKtQAOuFPjAAXEhBmyifAYgBc0AEqJgAe1wATADwLJmADRloE3QFsUEddAAKuOw8RHW8NMBkpdNAA+S3hUAw1TdAxoAF8AbQBdIOgAXjJYgG5RCSlZeUV-YGgAWQBBAA0AfQBhLgA5GoBVTU0AUUaATTToABYqUQYmYDBgAAtEAGlEAE9oB2h4RwNoSGgR8cQAa1noADN9aAw3eDFo+bRoGQmVZBJhHPgAIxBlBSViyBnfVYMDABVdAg7mU0AY2gAPHTwOQACj2PmAGm8vn8gUsGwm0xmkRkZgwAEoyKJqCBEDJoLhEBBdCB8HhkYi0ZcAD7QNDwEAgHocrnZGik8nWNz2Rw8xAAdxcIo8XiZAWCsKpNLpJFSKQoAuoytp9NwPR1qv51GosQJ-OglqtltotHQVxuVLA3Il+hABks1wWCzAlMQzugOzmwCdchWTzmaDAaF07AMJLJFLCKBW6QABgASUglWRjAB0uGjBjssIJsTT-IGArKuELMzzDhrddhXogef4d3imKms0SBJJ1AA-A6HO3VF3Rlje3mxEsxrDSML3I4NDZRYhQuENMmVmaBxpW2PO93sYkevFF2uPKuZY5Nynt+E4olKwLbR3BPbndyRlyIKE0H8blymqOpGhadounmGAnU2Aw82gMo9jkfVrlkSwIFeYgHRIPYUFwBRoEQQDcDmItVglMAUApa4SCvRwSRQPZoBbMZRw-RAJ02U88zJTBrmgFJDxA2oGmaVoOhqToiU1E1BQpDjXGXNURzbDiuKnGZEjzCA2OQ0tjRNJiWMU29EAJWS5LASjqNuJAlPXGczIta1XMtWISQ8yg3JtWg9DQFVEF43QMFhAAiRAyVsYiZBge0OLUMLPTYtTxxPac+Iwa4MUnHsZn7SgSVtORxjQIhvzmVtoAlQsxDOTBoPZXQKTQHRqQgMBSMsJ4YXmClbDAHYYBkXR1l0AwSFsfQSCdAwwBeEgUFsMZdATIVlU5Cl0i+H5SzSDUB0TP0YG2myKQRXwDIHYylWpXU8Bkgc6FoQ16VWMF1jJaNFjEJ7XrwK6tWoQ91PSrSehBtLcp4vCQBQ2FIsQWx9qIqK8x3aAAEJUnSHdzQHLyfNc21-MC4LQuVHLuNmSwwrwgKJhWMBkLwJL2UlaAABF8lLPMMHJf4lsQPaAFoiMAvBEAMMoZD5gWhdLcwwtsCA2YiiWqSZmREssGLJelmQCoHKkZHgXBLmVQyvJJE2zcuayqIpDa4cB00qGtygduKC6-AVaBMMQRAxFhFW1A5Wwnge2TbfNijHfZqUHI8W6VXpdUJXQYsJR0+Xot0GEU-u8wVYJAqPa9-Z5UCdZvwBiyqGtBhoFtAArJZzsOOQFHODOBL2SU8HFvEUGpBurQOXBYSOlBUgABkyFAjAAZgXgBqVf6+8nyjuOfOxGxHoc2uAsixLIkjFnvMAFZhzp3RdDCxKDgfse3OBVBMBwAgiCCsA-kBd+iBQTgihMAGEwsK6lnVJqIm1oHa2QDkHWER98x7BAPfSevRZ7YJFigk+YIz70AAEzYNnqXFysCxoBVpEFdBoUUCWFalKbmcICRyxkDgfyBgICKwTlzHmbD+YyBKCgLkHguE8IJOYXepxsQFUoZaGOlw8GFgIbYUsr9XKxGkScfesx5FWkJlaB4W9LSaInlPIUM956LxIWvDeMDt5ChkXouY6QVGn3UefS+N9oB3wfk-e+YUKGuSOu8XAYYZbimYQIkJ1p37RC-oQYgeY-4AiBKoYBkJoRwkgQSaBmiibwIpIg4OeC0EYNhFgnBHi1GlmIaQ8hhSfKkxoeTWEDC+EsOFoI3OPSRbhMibLIRgtoqKxcXI5pbklGlFzPg4sXiplxB0XvSZpi4iaPdlQX8ZJJ4EiAA


text:
Q: Regenerate current url with additional GET parameter In a Symfony 2.7 app, with Twig, I want to create generate pagination buttons.
I have a search page, with optional GET parameters :

*

*Empty :
www.[...].com/search

*Search by name :
www.[...].com/search ?name=john

*Search by name and sort by relevance :
www.[...].com/search ?name=john&sort=relevance

*Search by name and sort by relevance, page 2 :
www.[...].com/search ?name=john&sort=relevance&p=2
More than 10 possibles parameters, so I don't want to define a route pattern with all optional parameters.
Then, when I display the search results, I want to link next pages :
www.[...].com/search?name=john&sort=relevance &p=2
www.[...].com/search?name=john&sort=relevance &p=3
www.[...].com/search?name=john&sort=relevance &p=4
In the TWIG template I tried it so :
{% set param = app.request.get('_route_params') %}
{% if param is null %}
    {% set param = {'p': page} %}
{% else %}
    {% set param = param|merge({'p': page}) %}
{% endif %}

{{ page }}

But, because the optional parameters are not defined in the route, they are not in request.get('_route_params') and the link builded only define ?p=X.
Is there any other way to get queried GET parameters and to edit them creating a new url with an other p ?

A: In your twig template, you can use:
app.request.query.all

to get all your query parameters


text:
Q: remotely copy from Windows source by running scp on Linux I want to copy files remotely in a script from windows machine to Linux machine.
On the Linux machine I run the below command
scp user@remotehost:\D\mySrcCode\somefile.cpp .

I am getting an error
scp: DmySrcCodesomefile.cpp: No such file or directory

The file somefile.cpp is located at D:\mySrcCode on windows side.
Any ideas on what I am missing ?

A: You probably should quote or backslash the backslashes in the path.
If your interactive shell is GNU bash, read its §3.1.2 quoting chapter.
You could try:
 scp user@remotehost:\\D\\mySrcCode\\somefile.cpp .

Consider also using other (more appropriate) tools, like rsync or git.
You might also use exec(3) from your C program to run  /usr/bin/ssh, or look into libssh.
You could change your login shell (see chsh(1) and /etc/shells so shells(5)) to more user friendly alternatives such as zsh or fish. They could give you some warning (depending on how they are configured or used) or some autocompletion (with the tabkey).
PS. Your problem is not ssh specific. You might replace scp with echo to understand it more.


text:
Q: Android - How can Services run in background? To my understanding, on android, Services run on the UI thread. I'm a little confused as to how services can run in the background - Should that not block the UI thread? How come they can both be on the main thread and run in the background at the same time?

A: Services run on the main thread by default, but they run in the background from the user's perspective - there's no screen backing the Service.
If you want your service to execute on a background thread, either use a Service subclass and provide your own threading - via a new Thread, the Java Executor framework, RxJava, AsyncTask, or use an IntentService subclass for "one-shot" type of tasks.

A: You can easily organize execution in background by yourself. But, if you want to perform single continious job once, consider using IntentService - it will run in separate thread and then finish.
On the other hand, ordinary Service ca run indefinitely and you can bind to it.
There is a few ways you can organize background tasks - AsyncTask, separate Thread, and, the most powerfull and convenient way- use rxJava library
Here is a code how you can execute some operation in background thread and process results on main thread with rxJava:
String arg = "132";
        Observable.defer(() -> Observable.just(arg))
                // start operation on background thread from
                // thread pool
                .subscribeOn(Schedulers.computation())
                .map(arg -> {
                    // do you processing here
                    String result = "123";
                    return result;
                })
                // switch to main thread
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(v -> {
                    // process results
                    Log.i("My service", "result: " + v);
                }, error -> {
                    // handle error
                });

As you can see, this is very convenient way of managing background operation, but, more importaint, you can switch threads as task progresses.

A: Service is always run on UI Thread
But If you run a service in UI thread then UI will be blocked.
So within the help of Thread or Asynctask you can call a service via Sap-rate Thread so that UI will not be blocked


text:
Q: Beautiful Soup extracting all text between two tags, some of the text within the div is tagless So, I have been at this for a while now, I am using BeautifulSoup4 and I am attempting to get all the text between the first
 tag and the first
 tag. The problem is that .next and nextSibling all appear to skip tagless text.
This is what I am trying as of now
start = article_content(text="Description")[0]
end = soup.find_next(class_='title')
spell_description = ""
item = start.next
while item != end:
    try:
        new_text = item.extract()
        if new_text != '':
            strip_newline = str(re.sub(r'\n\s*\n', '\n\n', new_text))
            spell_description += strip_newline + '\n'
    except Exception as e:
        print(e)
    item = item.next

This is the HTML

Description

      You detect magical auras. The amount of information revealed depends on how long you study a particular area or subject.

1st Round: Presence or absence of magical auras.

2nd Round: Number of different magical auras and the power of the most potent aura.

3rd Round: The strength and location of each aura. If the items or creatures bearing the auras are in line of sight, you can make Knowledge (arcana) skill checks to determine the school of magic involved in each. (Make one check per aura: DC 15 + spell level, or 15 + 1/2 caster level for a nonspell effect.) If the aura eminates from a magic item, you can attempt to identify its properties (see Spellcraft).

Magical areas, multiple types of magic, or strong local magical emanations may distort or conceal weaker auras.

Aura Strength: An aura's power depends on a spell's functioning spell level or an item's caster level; see the accompanying table. If an aura falls into more than one category, detect magic indicates the stronger of the two.

Lingering Aura: A magical aura lingers after its original source dissipates (in the case of a spell) or is destroyed (in the case of a magic item). If detect magic is cast and directed at such a location, the spell indicates an aura strength of dim (even weaker than a faint aura). How long the aura lingers at this dim level depends on its original power:

            Original Strength
            Duration of Lingering Aura

            Faint
            1d6 rounds

            Moderate
            1d6 minutes

            Strong
            1d6 x 10 minutes

            Overwhelming
            1d6 days

Outsiders and elementals are not magical in themselves, but if they are summoned, the conjuration spell registers. Each round, you can turn to detect magic in a new area. The spell can penetrate barriers, but 1 foot of stone, 1 inch of common metal, a thin sheet of lead, or 3 feet of wood or dirt blocks it.

Detect magic can be made permanent with a permanency spell.

 Detect Magic, Greater

output as of now
'You detect magical auras. The amount of information revealed depends on how long you study a particular area or subject.\n'

expected output
You detect magical auras. The amount of information revealed depends on how long you study a particular area or subject.

1st Round: Presence or absence of magical auras.

2nd Round: Number of different magical auras and the power of the most potent aura.

3rd Round: The strength and location of each aura. If the items or creatures bearing the auras are in line of sight, you can make Knowledge (arcana) skill checks to determine the school of magic involved in each. (Make one check per aura: DC 15 + spell level, or 15 + 1/2 caster level for a nonspell effect.) If the aura eminates from a magic item, you can attempt to identify its properties (see Spellcraft).

Magical areas, multiple types of magic, or strong local magical emanations may distort or conceal weaker auras.

Aura Strength: An aura's power depends on a spell's functioning spell level or an item's caster level; see the accompanying table. If an aura falls into more than one category, detect magic indicates the stronger of the two.

Lingering Aura: A magical aura lingers after its original source dissipates (in the case of a spell) or is destroyed (in the case of a magic item). If detect magic is cast and directed at such a location, the spell indicates an aura strength of dim (even weaker than a faint aura). How long the aura lingers at this dim level depends on its original power:

Original Strength
Duration of Lingering Aura
Faint
1d6 rounds
Moderate
1d6 minutes
Strong
1d6 x 10 minutes
Overwhelming
1d6 days

A: I would use BeautifulSoup to find the first h3 element then use next_sibling()
to find the next elements until h1 is reached and print the NavigableStrings like this:
from bs4 import BeautifulSoup, NavigableString, Comment

html = """

stuff you dont want

Description

      You detect magical auras. The amount of information revealed depends on how long you study a particular area or subject.

1st Round: Presence or absence of magical auras.

2nd Round: Number of different magical auras and the power of the most potent aura.

3rd Round: The strength and location of each aura. If the items or creatures bearing the auras are in line of sight, you can make Knowledge (arcana) skill checks to determine the school of magic involved in each. (Make one check per aura: DC 15 + spell level, or 15 + 1/2 caster level for a nonspell effect.) If the aura eminates from a magic item, you can attempt to identify its properties (see Spellcraft).

Magical areas, multiple types of magic, or strong local magical emanations may distort or conceal weaker auras.

Aura Strength: An aura's power depends on a spell's functioning spell level or an item's caster level; see the accompanying table. If an aura falls into more than one category, detect magic indicates the stronger of the two.

Lingering Aura: A magical aura lingers after its original source dissipates (in the case of a spell) or is destroyed (in the case of a magic item). If detect magic is cast and directed at such a location, the spell indicates an aura strength of dim (even weaker than a faint aura). How long the aura lingers at this dim level depends on its original power:

            Original Strength
            Duration of Lingering Aura

            Faint
            1d6 rounds

            Moderate
            1d6 minutes

            Strong
            1d6 x 10 minutes

            Overwhelming
            1d6 days

Outsiders and elementals are not magical in themselves, but if they are summoned, the conjuration spell registers. Each round, you can turn to detect magic in a new area. The spell can penetrate barriers, but 1 foot of stone, 1 inch of common metal, a thin sheet of lead, or 3 feet of wood or dirt blocks it.

Detect magic can be made permanent with a permanency spell.

 Detect Magic, Greater

stuff you dont want
"""

soup = BeautifulSoup(html, 'lxml')
ret =[]
tag= soup.find('h3')
while True:
    if tag is None or tag.name == 'h1':
        break
    if isinstance(tag, NavigableString) and not isinstance(tag, Comment):
        ret.append(tag.strip())
    elif tag.text is not None:
        ret.append(tag.text.strip())
    tag = tag.next_sibling
print("\n".join(ret))

Outputs:
Description
You detect magical auras. The amount of information revealed depends on how long you study a particular area or subject.

1st Round
: Presence or absence of magical auras.

2nd Round
: Number of different magical auras and the power of the most potent aura.

3rd Round
: The strength and location of each aura. If the items or creatures bearing the auras are in line of sight, you can make Knowledge (arcana) skill checks to determine the school of magic involved in each. (Make one check per aura: DC 15 + spell level, or 15 + 1/2 caster level for a nonspell effect.) If the aura eminates from a magic item, you can attempt to identify its properties (see Spellcraft).

Magical areas, multiple types of magic, or strong local magical emanations may distort or conceal weaker auras.

Aura Strength
: An aura's power depends on a spell's functioning spell level or an item's caster level; see the accompanying table. If an aura falls into more than one category,
detect magic
indicates the stronger of the two.

Lingering Aura
: A magical aura lingers after its original source dissipates (in the case of a spell) or is destroyed (in the case of a magic item). If detect magic is cast and directed at such a location, the spell indicates an aura strength of dim (even weaker than a faint aura). How long the aura lingers at this dim level depends on its original power:

Original Strength
Duration of Lingering Aura

Faint
1d6 rounds

Moderate
1d6 minutes

Strong
1d6 x 10 minutes

Overwhelming
1d6 days

Outsiders and elementals are not magical in themselves, but if they are summoned, the conjuration spell registers. Each round, you can turn to detect magic in a new area. The spell can penetrate barriers, but 1 foot of stone, 1 inch of common metal, a thin sheet of lead, or 3 feet of wood or dirt blocks it.

Detect magic
can be made permanent with a
permanency
spell.


text:
Q: How to run wget inside Ubuntu Docker image? I'm trying to download a Debian package inside a Ubuntu container as follows:
sudo docker run ubuntu:14.04 wget https://downloads-packages.s3.amazonaws.com/ubuntu-14.04/gitlab_7.8.2-omnibus.1-1_amd64.deb

I get
exec: "wget": executable file not found in $PATH

I've already installed wget with docker as follows:
run ubuntu:14.04 apt-get install wget

How can I download a file?

A: I had this problem recently where apt install wget does not find anything. As it turns out apt update was never run.
apt update
apt install wget

After discussing this with a coworker we mused that apt update is likely not run in order to save both time and space in the docker image.

A: If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su then apt-get install -y wget

A: You need to install it first. Create a new Dockerfile, and install wget in it:
FROM ubuntu:14.04
RUN  apt-get update \
  && apt-get install -y wget \
  && rm -rf /var/lib/apt/lists/*

Then, build that image:
docker build -t my-ubuntu .

Finally, run it:
docker run my-ubuntu wget https://downloads-packages.s3.amazonaws.com/ubuntu-14.04/gitlab_7.8.2-omnibus.1-1_amd64.deb


text:
Q: Run multiple function in python I am writing a program for Raspberry Pi that is utilizing multiple function in classes. I have one class that is dedicated to determining when a capacitive touch sensor is clicked and another one class dedicated to determining the weight from HX711 chip. I want to automatize all: when click the capacitive sensor the cell start the weight scale and then, when I click the capacitive sensor for the second times the system call the function cleanAndExit() but I don't know how I can do this stuff.
import time
import sys
import RPi.GPIO as GPIO
from hx711 import HX711
GPIO.setmode(GPIO.BCM)

padPin = 21
GPIO.setup(padPin, GPIO.IN)

class WeightScale:

    def cleanAndExit(self):
        print "Clean GPIO..."
        GPIO.cleanup()
        print "Complete!"
        sys.exit()

    def cliccato(self):
            hx = HX711(5, 6)
            hx.set_reading_format("LSB", "MSB")
            hx.reset()
            hx.tare()
            hx.set_reference_unit(-421)
            while True:
                time.sleep(0.1)
                n = 100

 //Run for max 100 seconds and create an array with the last value from weight scale sensor

                for i in range (1, n):
                    val = max(0, int (hx.get_weight(5)))
                    add = []
                    hx.power_down()
                        hx.power_up()
                        time.sleep(0.6)
                    add.append(val)
                    add1 = []
                    add1.append(add[-1:])
                    print add1
                    time.sleep(1)

class TouchSensor:

    def click(self):
        alreadyPressed = False
        while True:
            padPressed =  GPIO.input(padPin)
            if padPressed and not alreadyPressed:
                print "click"
                time.sleep(2)

c=WeightScale()
t=TouchSensor()

A: In order you to correctly create a class, you need to define an init method with in the class definition. So for example:
class TouchSensor:
    def __init__(self):
        self.padPin = 21

    def click(self):
        alreadyPressed = False
        while True:
            padPressed =  GPIO.input(padPin)
            if padPressed and not alreadyPressed:
                print "click"
                time.sleep(2)

Then once you create your object of that class, it is initialized with padPin = 21. Then you use the methods within each class to perform what you're calling 'functions.'
t = TouchSensor()
t.click()

Try making adjustments and post whatever errors you end up with!

A: I make some adjustments to my code:
   import time
import sys
from multiprocessing import Process
import RPi.GPIO as GPIO
from hx711 import HX711
GPIO.setmode(GPIO.BCM)

padPin = 21
GPIO.setup(padPin, GPIO.IN)

class WeightScale:

    def cleanAndExit(self):
            print ("Clean GPIO...")
            GPIO.cleanup()
            print ("Complete!")
            sys.exit()

    def pesatura(self):
         hx = HX711(5, 6)
         hx.set_reading_format("LSB", "MSB")
         hx.reset()
         hx.tare()
         hx.set_reference_unit(-421)
         while t.status==True:
                    time.sleep(0.1)
                    n = 100
                    for i in range (1, n):
                         val = max(0, int (hx.get_weight(5)))
                         add = []
                         hx.power_down()
                         hx.power_up()
                         time.sleep(0.6)
                         add.append(val)
                         add1 = []
                         add1.append(add[-1:])
                         print (add1)
                         time.sleep(1)
        cleanAndExit()

class TouchSensor:

    def __init__(self):
        self.status = False

    def changeStatus(self):
        if self.status == False:
            self.status = True
            print (self.status)
        else:
            self.status = False
            print (self.status)

    def click(self):
        while True:
            padPressed =  GPIO.input(padPin)
            if padPressed:
                print ("click")
                t.changeStatus()

            alreadyPressed = padPressed
            time.sleep(0.5)

c=WeightScale()
t = TouchSensor()

if __name__ == '__main__':
    p1 = Process (target = t.click())
    p1.start()
    p2 = Process (target = c.pesatura())
    p2.start()

I have added a multiprocessing function and method changeStatus for the button click,I want to use it to start the loop of pesatura(self) when self.status==True and after, when self.Status== False (another click) start  cleanAndExit(). But when I start the script it gives me the error ''cleanAndExit() takes exactly 1 argument (0 given)''.


text:
Q: simple ROS script terminating without displaying errors I am using ROS melodic on ubuntu 18.04, turtlebot 2.
I tried to create a simple ROS program, that tries to make the bot follow a specified path. My gazebo world looks like this:

The task is to try to make the bot follow the white path. The approach is to use the bot's camera to keep clicking photos using of its environment,and save it as "image.jpg", at a particular rate. This job is done by a program known as take_photo_mod.py. Now, there is another program "goforward_mod.py" that does two things: Processes image.jpg using openCV functions , and finds out the angle which the bot should move with the vertical to be aligned with the path.  It's angular velocity is controlled by this angle. If the angle (error) is zero, then the bot simply moves forward at a velocity 0.2 units (and zero angular velocity) If there's some error, then the angular velocity is set using that error, and linear velocity is set to zero.
The openCV aspect is working flawlessly and I have tested it numerous times. However, whenever I run the entire program (including the goforward aspect) through the terminal, the program immediately ends, and gives no error. I tried to remove the openCV aspect from the code, and made the "error" variable, a constant, and I set the angular velocity by simply using a P-controller. This code should simply make the turtlebot  rotate around the z axis but again, the script simply terminates without showing any errors.
#!/usr/bin/env python

import rospy
import cv2
import numpy as np
import math as m
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from geometry_msgs.msg import Twist

class GoForward():

    def _init_(self):
        rospy.init_node('GoForward', anonymous=False)
        rospy.loginfo("To stop TurtleBot CTRL + C")
        rospy.on_shutdown(self.shutdown)
        self.cmd_vel = rospy.Publisher('cmd_vel_mux/input/navi', Twist, queue_size=10)
        r = rospy.Rate(10)
        move_cmd = Twist()
        turn_cmd= Twist()
        w=0
        vx=0

        while not rospy.is_shutdown():
            #frame=cv2.imread("image.jpg",1)
            #error=extract(frame)
            error=-0.47

            if(error==0):
                vx=0.2
                w=0
                move_cmd.linear.x = vx
                move_cmd.angular.z = -w
                self.cmd_vel.publish(move_cmd)

            else:
                vx=0
                kp=0.15
                w=kp*error
                turn_cmd.linear.x=vx
                turn_cmd.angular.z = -w
                self.cmd_vel.publish(turn_cmd)

            r.sleep()

    def shutdown(self):
        rospy.loginfo("Stop TurtleBot")
        self.cmd_vel.publish(Twist())
        rospy.sleep(1)

if __name__ == '__main__':
    try:
        GoForward()
    except:
        rospy.loginfo("GoForward node terminated.")

Neither "To stop TurtleBot CTRL + C", nor "GoForward node terminated." is printed on the terminal. The terminal simply displays the value of the error variable , and then the program finishes. It appears as if GoForward() is not executing at all.....what can be the causes for this?

A: A couple of things here. While it isn't really a fatal problem with python ROS nodes, you should probably be launching it via rosrun or roslaunch.
That being said, your error is actually python syntax. You missed a set of _ in _init_(). Change it to def __init__(self):


text:
Q: str vs Timestamp type indices and "loc" result type Why having a DataFrame with str type index for dates returns a Series, whilst Timestamp equivalent returns a DataFrame with single row?
df = pd.read_csv('file.csv')
df.dt = pd.to_datetime(df.dt, format='%Y-%m-%d')

type(df.loc['2018-01-01']) # pandas.core.frame.DataFrame
>>

vs
df = pd.read_csv('file.csv')
df.dt = pd.to_datetime(df.dt, format='%Y-%m-%d').dt.strftime('%Y-%m-%d')

type(df.loc['2018-01-01']) # pandas.core.series.Series
>>


text:
Q: The curious case of backshifting I've always found backshifting to be one of the most challenging parts of English grammar. My current issue involves using it in questions and negations.
Recently, I got into a conversation about Russia with a guy, who clearly lacked knowledge on the topic, and as a result appeared ignorant. I then asked him:

"Why do you make it sound like Russia is some backward hellhole?"

To which he replied:

"I didn't say Russia is backward"

And here my problem ensues. For some reason I feel like he should have said "I didn't say Russia was backward", though I don't have any idea why. It just sounds more idiomatic to my non-native ear.
Another similar issue struck me during some other conversation. This time, when talking about some comic book characters, the girl I was talking to asked me:

What did you say his name was?

Although I deem it correct, I immediately started to wonder: would "What did you say his name is?" be as viable in this case?
Slight edit: what about the utterance "I had no idea you were/are this tall!"? The same applies, i.e. "were" seems more fitting?
Of course, if you manage to find any other problems with my grammar, I'd be really glad if you could point them out.

A: Backshifting can be a difficult thing to understand. As an option, it's up to the speaker whether or not to use it. Generally, though, the backshifting occurs because it's implying content that is dropped in the final sentence. Let's take your examples:

*

*"You are tall!" ends up getting back shifted because there is an implication that the notification occurred in the past. Thus the shift occurs because the full thought is: "I had no idea you were this tall when you were described to me."

*"What did you say his name was?" operates on the same principle, as the notification occurs in the past. "What did you say his name was when you mentioned him a bit ago?"
So when you uttered your query to the speaker, you were expecting this construction, but since your question wasn't back shifted, neither was the response. There could be many reasons for this, but I would wager that the speaker may have been (at least slightly) flustered by your antagonistic question and formatted the simplest response. The fact that they only replied with one of the adjectives you used -- and the less vitriolic one at that -- speaks to a message and tone meant to be apologetic.


text:
Q: AttributeError: The layer has never been called and thus has no defined input shape I'm tring to build an autoencoder in TensorFlow 2.0 by creating three classes: Encoder, Decoder and AutoEncoder.
Since I don't want to manually set input shapes I'm trying to infer the output shape of the decoder from the encoder's input_shape.
import os
import shutil

import numpy as np
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense, Layer

def mse(model, original):
    return tf.reduce_mean(tf.square(tf.subtract(model(original), original)))

def train_autoencoder(loss, model, opt, original):
    with tf.GradientTape() as tape:
        gradients = tape.gradient(
            loss(model, original), model.trainable_variables)
        gradient_variables = zip(gradients, model.trainable_variables)
        opt.apply_gradients(gradient_variables)

def log_results(model, X, max_outputs, epoch, prefix):
    loss_values = mse(model, X)

    sample_img = X[sample(range(X.shape[0]), max_outputs), :]
    original = tf.reshape(sample_img, (max_outputs, 28, 28, 1))
    encoded = tf.reshape(
        model.encode(sample_img), (sample_img.shape[0], 8, 8, 1))
    decoded = tf.reshape(
        model(tf.constant(sample_img)), (sample_img.shape[0], 28, 28, 1))
    tf.summary.scalar("{}_loss".format(prefix), loss_values, step=epoch + 1)
    tf.summary.image(
        "{}_original".format(prefix),
        original,
        max_outputs=max_outputs,
        step=epoch + 1)
    tf.summary.image(
        "{}_encoded".format(prefix),
        encoded,
        max_outputs=max_outputs,
        step=epoch + 1)
    tf.summary.image(
        "{}_decoded".format(prefix),
        decoded,
        max_outputs=max_outputs,
        step=epoch + 1)

    return loss_values

def preprocess_mnist(batch_size):
    (X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()

    X_train = X_train / np.max(X_train)
    X_train = X_train.reshape(X_train.shape[0],
                              X_train.shape[1] * X_train.shape[2]).astype(
                                  np.float32)
    train_dataset = tf.data.Dataset.from_tensor_slices(X_train).batch(
        batch_size)

    y_train = y_train.astype(np.int32)
    train_labels = tf.data.Dataset.from_tensor_slices(y_train).batch(
        batch_size)

    X_test = X_test / np.max(X_test)
    X_test = X_test.reshape(
        X_test.shape[0], X_test.shape[1] * X_test.shape[2]).astype(np.float32)

    y_test = y_test.astype(np.int32)

    return X_train, X_test, train_dataset, y_train, y_test, train_labels

class Encoder(Layer):
    def __init__(self, units):
        super(Encoder, self).__init__()
        self.units = units

    def build(self, input_shape):
        self.output_layer = Dense(units=self.units, activation=tf.nn.relu)

    @tf.function
    def call(self, X):
        return self.output_layer(X)

class Decoder(Layer):
    def __init__(self, encoder):
        super(Decoder, self).__init__()
        self.encoder = encoder

    def build(self, input_shape):
        self.output_layer = Dense(units=self.encoder.input_shape)

    @tf.function
    def call(self, X):
        return self.output_layer(X)

class AutoEncoder(Model):
    def __init__(self, units):
        super(AutoEncoder, self).__init__()
        self.units = units

    def build(self, input_shape):
        self.encoder = Encoder(units=self.units)
        self.encoder.build(input_shape)
        self.decoder = Decoder(encoder=self.encoder)

    @tf.function
    def call(self, X):
        Z = self.encoder(X)
        return self.decoder(Z)

    @tf.function
    def encode(self, X):
        return self.encoder(X)

    @tf.function
    def decode(self, Z):
        return self.decode(Z)

def test_autoencoder(batch_size,
                     learning_rate,
                     epochs,
                     max_outputs=4,
                     seed=None):

    tf.random.set_seed(seed)

    X_train, X_test, train_dataset, _, _, _ = preprocess_mnist(
        batch_size=batch_size)

    autoencoder = AutoEncoder(units=64)
    opt = tf.optimizers.Adam(learning_rate=learning_rate)

    log_path = 'logs/autoencoder'
    if os.path.exists(log_path):
        shutil.rmtree(log_path)

    writer = tf.summary.create_file_writer(log_path)

    with writer.as_default():
        with tf.summary.record_if(True):
            for epoch in range(epochs):
                for step, batch in enumerate(train_dataset):
                    train_autoencoder(mse, autoencoder, opt, batch)

                # logs (train)
                train_loss = log_results(
                    model=autoencoder,
                    X=X_train,
                    max_outputs=max_outputs,
                    epoch=epoch,
                    prefix='train')

                # logs (test)
                test_loss = log_results(
                    model=autoencoder,
                    X=X_test,
                    max_outputs=max_outputs,
                    epoch=epoch,
                    prefix='test')

                writer.flush()

                template = 'Epoch {}, Train loss: {:.5f}, Test loss: {:.5f}'
                print(
                    template.format(epoch + 1, train_loss.numpy(),
                                    test_loss.numpy()))

    if not os.path.exists('saved_models'):
        os.makedirs('saved_models')
    np.savez_compressed('saved_models/encoder.npz',
                        *autoencoder.encoder.get_weights())

if __name__ == '__main__':
    test_autoencoder(batch_size=128, learning_rate=1e-3, epochs=20, seed=42)

Since the encoder's input shape is used in the build function of the decoder, I'd expect that when I train the autoencoder the encoder is built first, then the decoder, but that doesn't seem to be the case. I've also tried to build the encoder in the build function of the decoder by calling self.encoder.build() at the start of the decoder's build function, but it didn't make any difference. What am I doing wrong?
Error I am receiving:
AttributeError: The layer has never been called and thus has no defined input shape.

A: You were almost there, just overcomplicated things a bit. You are receiving this error because Decoder layer is dependent on the Encoder layer which wasn't built yet (as the call to build was unsuccessful) and it's input_shape attribute was not set.
Solution would be to pass correct output shapes from AutoEncoder object like this:
class Decoder(Layer):
    def __init__(self, units):
        super(Decoder, self).__init__()
        self.units = units

    def build(self, _):
        self.output_layer = Dense(units=self.units)

    def call(self, X):
        return self.output_layer(X)

class AutoEncoder(Model):
    def __init__(self, units):
        super(AutoEncoder, self).__init__()
        self.units = units

    def build(self, input_shape):
        self.encoder = Encoder(units=self.units)
        self.decoder = Decoder(units=input_shape[-1])

Notice I have removed @tf,function decorator as you are unlikely to get any efficiency boost (keras already creates the static graph under the hood for you).
Furthermore, as one can see, your build is not dependent on input_shape information so all the creation can be safely moved to the constructor like this:
class Encoder(Layer):
    def __init__(self, units):
        super(Encoder, self).__init__()
        self.output_layer = Dense(units=units, activation=tf.nn.relu)

    def call(self, X):
        return self.output_layer(X)

class Decoder(Layer):
    def __init__(self, units):
        super(Decoder, self).__init__()
        self.output_layer = Dense(units=units)

    def call(self, X):
        return self.output_layer(X)

class AutoEncoder(Model):
    def __init__(self, units):
        super(AutoEncoder, self).__init__()
        self.units = units

    def build(self, input_shape):
        self.encoder = Encoder(units=self.units)
        self.decoder = Decoder(units=input_shape[-1])

    def call(self, X):
        Z = self.encoder(X)
        return self.decoder(Z)

    def encode(self, X):
        return self.encoder(X)

    def decode(self, Z):
        return self.decode(Z)

Above begs a question whether separate Decoder and Encoder layers are really needed. IMO those should be left out, which leaves us only with this short and readable snippet:
class AutoEncoder(Model):
    def __init__(self, units):
        super(AutoEncoder, self).__init__()
        self.units = units

    def build(self, input_shape):
        self.encoder = Dense(units=self.units, activation=tf.nn.relu)
        self.decoder = Dense(units=input_shape[-1])

    def call(self, X):
        Z = self.encoder(X)
        return self.decoder(Z)

    def encode(self, X):
        return self.encoder(X)

    def decode(self, Z):
        return self.decode(Z)

BTW. You have an error in sample but that's a minor you can handle on your own no doubt.


text:
Q: Run blocking function at startup Nodejs I try to use sonos (https://www.npmjs.org/package/sonos) to return an array of the players i have on my network. I would like to use the sonos.search function to find players for me at startup and afterwards update the array with new players if connected to the network.
Since sonos.search is asynchronous the rest of the code will execute before all players are added to the array at startup. How can I block the code to run the sonos.search once for 10 seconds at startup building an array of players that is on the network and then liste/search for new players and add to array if connected?
-

A: Trying to go against the asynchronous behavior of nodejs is generally not the best approach to a problem.
If you want the rest of your code to be executed after sonos has loaded the players, it should be called from within the callback of the asynchronous function.
If you really want to wait 10 seconds before launching the rest of your code though, you can use the setTimeout() function.
setTimeout(function() {
    codeToBeExecutedAfter10Secs();
}, 10000);

A: You can try :
https://github.com/luciotato/waitfor
to make sync call. It works with fibers and has many method to "wait" for something.
EDIT : a little example of using it assuming you use mongoskin to access data
var wait =require('wait.for');

wait.launchFiber(function(){
    var obj = getAsyncData();
});

function getAsyncData(){
   return wait.forMethod(db.collection('data'), 'find');
}

And I think MeteorJS framework use this library to handle sync functions.


text:
Q: How to make autocomplete dropdown list appear only at the bottom and define the number of visible results I added an autocomplete textView to my app
It works great, just as i want, but
now i want to say that the maximum visible results is 3, and that it'd be always at the bottom of the textview (The textview itself is in the middle of the screen always)
How do i do that ?

A: I remember having messed with that a time ago, and all I was able to find is a kind of workaround I didn't like too much for this, since there's no native method for that, but should work. Basically, it consists on calling .setDropDownHeight(int height) method.
As you may see, what you provide is a height, so you're not specifying the number of items. So you need to take the height of one of the rows and set the height of your dropdownlist to: number_of_items * height.
yourAutoCompleteTV.setDropDownHeight(your_layout_view.getHeight() * 3);

For the second problem problem, I think this is a space problem within your layout. You'll probably have to make yourself sure that there is always enough space below your TextView to show all the suggestions and it will open always downwards, so simply tune up your layout for this.


text:
Q: When pushlishing MVC project to server, bootstrap.css edits don't migrate I have an MVC project that I built in Visual Studio 2013 and when I publish the project up to Windows Server 2012, any changes I made in the bootstrap.css file don't migrate. I know it is just that file specifically because any changes I made to the Site.css file appear on the server. Everything else works except the one bootstrap.css file.
I really don't want to have to pull out the changes in bootstrap.css, it would take a lot of searching. Is this problem common? Has anyone even heard about this issue?

A: I had an idea to take the code from my bootstrap.css file and minify it manually, then copy it into the boostrap.min.css file. After doing that, I published the project back up to my server and everything is now working as expected.

A: In Visual Studio's Properties pane (for the file in question) check that the Copy To Output Directory property is set to Copy Always.
Also, in the Publish settings dialog, on the Settings tab,
expand the File Publish Options collapsible region and make sure Remove additional files at destination is checked (turned on).


text:
Q: jQuery Created Nested List Based on Attribute I get stuck when trying to implement recursive logic in jQuery--I don't have much practice with it. I have a simple need, which is to nest unsorted lists by class. What I have is two dynamic lists on a page (they're generated by two CAML queries). The first list will be the top level
 and the second list will be nested. The first list has
s with numeric id's and the second list has
s with numeric classes that match the id's that they have to be nested under. i.e.:

Parent Item 1

Parent Item 2

Child 1

Child 2

Child X

There will be an undetermined number of parents and child
s over time. Also, if it's better to use a different attr than class for the children that's fine. Ultimately I'll want to add more classes for CSS. Any help would be greatly appreciated.

A: Working example here: http://jsfiddle.net/rkCKT/
Assuming this markup:

Parent Item 1

Parent Item 2

Child 1

Child 2

Child X

this would work:
$(document).ready(function(){
    $('ul.children li').each(function(){
        probable_parent = $('ul.parents li#' + $(this).attr('class'));
        if (probable_parent.length)
        {
            if (!probable_parent.find('ul').length) probable_parent.append('
');
            $(this).detach().appendTo(probable_parent.find('ul'));
        }
    });
});

Edit:
As soon as you add any classes to the .children lis for presentational reasons, everything will be broken.
For this and half a million other reasons, if your document is HTML5, I strongly suggest using proper attributes for the parent-child relationship. Ideally, the markup would look something like this:

Parent Item 1

Parent Item 2

Child 1

Child 2

Child X


text:
Q: How to get url of uploaded file to google drive in android using Drive API? I need to get the link of the video that I upload it to google drive so that I can open the video in the web browser, I can upload a video file to google drive and can get also the file ID using the following code:
private void UploadFile(final DriveId driveId)
{
    Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
        @Override
        public void onResult(@NonNull DriveApi.DriveContentsResult driveContentsResult)
        {
            if (!driveContentsResult.getStatus().isSuccess())
            {
                Log.e(TAG, "Error while trying to create new file contents");
                return;
            }
            OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream();
            Toast.makeText(context, "Uploading to drive....", Toast.LENGTH_LONG).show();
            final File theFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/VideoFiles/testVideo.mkv");
            try
            {
                FileInputStream fileInputStream = new FileInputStream(theFile);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fileInputStream.read(buffer)) != -1)
                {
                    outputStream.write(buffer, 0, bytesRead);
                }
            } catch (IOException e1)
            {
                Log.i(TAG, "Unable to write file contents.");
            }
            MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(theFile.getName()).setMimeType("video/mkv").setStarred(false).build();
            DriveFolder folder = driveId.asDriveFolder();
            folder.createFile(mGoogleApiClient, changeSet, driveContentsResult.getDriveContents()).setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>() {
                        @Override
                        public void onResult(@NonNull DriveFolder.DriveFileResult driveFileResult)
                        {
                            if (!driveFileResult.getStatus().isSuccess())
                            {
                                Log.e(TAG, "Error while trying to create the file");
                                return;
                            }
                            Log.v(TAG, "Created a file: " + driveFileResult.getDriveFile().getDriveId());
                        }
                    });
        }
    });
}

I tried to get the video url using the following code:
DriveFile file = Drive.DriveApi.getFile(googleApiClient,driveId);
                            DriveResource.MetadataResult mdRslt = file.getMetadata(googleApiClient).await();
                            if (mdRslt != null && mdRslt.getStatus().isSuccess()) {
                                String link = mdRslt.getMetadata().getWebContentLink();
                                Log.d("LINK", link);
                            }

But then I got "Cannot resolve symbol 'googleApiClient'
Any suggestion please?

A: Ok, I found the solution, first I have to get the completed file ID by using the change events listener, then we can add "drive.google.com/open?id=" to the file ID, so the complate url will be drive.google.com/open?id=FileID.
here is my answer:
public class Uploader extends Activity implements ConnectionCallbacks,OnConnectionFailedListener{
private static final String TAG = "Google Drive Activity";
private static final int REQUEST_CODE_RESOLUTION = 1;
private static final  int REQUEST_CODE_OPENER = 2;
private GoogleApiClient mGoogleApiClient;
public DriveFile file;
private String FOLDER_NAME = "GD_VideoFile";
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onResume()
{
    super.onResume();
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
    mGoogleApiClient.connect();
}

@Override
protected void onStop()
{
    super.onStop();
    if (mGoogleApiClient != null) {

        mGoogleApiClient.disconnect();
    }
    super.onPause();
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult result)
{
    Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
    if (!result.hasResolution()) {

        GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
        return;
    }

    try {

        result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);

    } catch (SendIntentException e) {

        Log.e(TAG, "Exception while starting resolution activity", e);
    }
}

@Override
public void onConnected(Bundle connectionHint)
{
    Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();

    if (mGoogleApiClient != null)
    {
        check_folder_exists();
    } else
    {
        Log.e(TAG, "Could not connect to google drive manager");
    }
}

@Override
public void onConnectionSuspended(int cause)
{
    Log.i(TAG, "GoogleApiClient connection suspended");
}

@Override
protected void onActivityResult(final int requestCode,
                                final int resultCode, final Intent data)
{
    switch (requestCode)
    {
        case REQUEST_CODE_OPENER:
            if (resultCode == RESULT_OK)
            {
                DriveId mFileId = data.getParcelableExtra(
                        OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
                Log.e("file id", mFileId.getResourceId() + "");
                String url = "https://drive.google.com/open?id="+ mFileId.getResourceId();
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
            }
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
    }
}

private void check_folder_exists()
{
    Query query = new Query.Builder().addFilter(Filters.and(Filters.eq(SearchableField.TITLE, FOLDER_NAME), Filters.eq(SearchableField.TRASHED, false))).build();
    Drive.DriveApi.query(mGoogleApiClient, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
        @Override
        public void onResult(@NonNull DriveApi.MetadataBufferResult result)
        {
            if (!result.getStatus().isSuccess())
            {
                Log.e(TAG, "Cannot create folder in the root.");
            } else
            {
                boolean isFound = false;
                for (Metadata m : result.getMetadataBuffer())
                {
                    if (m.getTitle().equals(FOLDER_NAME)) {
                        Log.e(TAG, "Folder exists");
                        isFound = true;
                        DriveId driveId = m.getDriveId();
                        UploadFile(driveId);
                        break;
                    }
                }
                if (!isFound)
                {
                    Log.i(TAG, "Folder not found; creating it.");
                    MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(FOLDER_NAME).build();
                    Drive.DriveApi.getRootFolder(mGoogleApiClient)
                            .createFolder(mGoogleApiClient, changeSet)
                            .setResultCallback(new ResultCallback<DriveFolder.DriveFolderResult>() {
                                @Override
                                public void onResult(@NonNull DriveFolder.DriveFolderResult result)
                                {
                                    if (!result.getStatus().isSuccess())
                                    {
                                        Log.e(TAG, "Error while trying to create the folder");
                                    } else {
                                        Log.i(TAG, "Created a folder");
                                        DriveId driveId = result.getDriveFolder().getDriveId();
                                        UploadFile(driveId);
                                    }
                                }
                            });
                }
            }
        }
    });
}

private void UploadFile(final DriveId driveId)
{

    Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>()
    {
        @Override
        public void onResult(@NonNull DriveApi.DriveContentsResult driveContentsResult)
        {
            if (!driveContentsResult.getStatus().isSuccess())
            {
                Log.e(TAG, "U AR A MORON! Error while trying to create new file contents");
                return;
            }

            OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream();
            Toast.makeText(Uploader.this, "Uploading to drive....", Toast.LENGTH_LONG).show();
            final File theFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyMobile_Videos/a.mov");
            try
            {
                FileInputStream fileInputStream = new FileInputStream(theFile);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fileInputStream.read(buffer)) != -1)
                {
                    outputStream.write(buffer, 0, bytesRead);
                }
            } catch (IOException e1)
            {
                Log.i(TAG, "Unable to write file contents.");
            }

            MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(theFile.getName()).setMimeType("video/mov").setStarred(false).build();
            DriveFolder folder = driveId.asDriveFolder();
            folder.createFile(mGoogleApiClient, changeSet, driveContentsResult.getDriveContents()).setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>()
            {
                        @Override
                        public void onResult(@NonNull DriveFolder.DriveFileResult driveFileResult)
                        {
                            if (!driveFileResult.getStatus().isSuccess())
                            {
                                Log.e(TAG, "Error while trying to create the file");
                                return;
                            }
                            Toast.makeText(Uploader.this, "Created a file: " + driveFileResult.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show();

                            String Folder_Id = driveId.getResourceId();
                            System.out.println("The folder id: " +Folder_Id);

                            //This is to get the file id from the listener
                            DriveId File_Uncompleted_Id = driveFileResult.getDriveFile().getDriveId();
                            DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, File_Uncompleted_Id);
                            file.addChangeListener(mGoogleApiClient, changeListener);
                        }

                //A listener to handle file change events.
                final private ChangeListener changeListener = new ChangeListener()
                {
                    @Override
                    public void onChange(ChangeEvent event)
                    {
                        String File_Completed_Id =  event.getDriveId().getResourceId();
                        System.out.println("The uploaded file id: " +File_Completed_Id);
                        System.out.println("File URL: https://drive.google.com/open?id=" +File_Completed_Id);

                    }
                };
            }
                    );
        }

    }
    );
}

}


text:
Q: Finding div width I have three divs. The two smaller ones are inside the same container, the third div.

*

*The first child div is 350x350 px big.

*The third div is 89% of another container div, meaning I dont know the size of it.

*I want to make the second child div span between the edges of the first child div and the container div.

Basically:

How do I figure out the width of my second_child element if I want the second_child element to span precisely between the first_child element and the edge of container?
Edit:
Uploaded a quickly drawn image. The big black square is container, measurements are unknown. The red box is first_child, the blue box is second_child. I want to find the width for second_child so it will stretch from the end of first_child to the right edge of container.

A: You can do using CSS calc():
#second_child {
   width: -moz-calc(100% - 350px);
   width: -webkit-calc(100% - 350px);
   width: calc(100% - 350px);
}

For IE8 and lower you'll have to use jQuery or javascript

A: I think what you need is to use some css like so:
#container {
    width:89%;
    height:350px;
}
#first_child {
    float:left;
    width:350px;
    height:350px;
}
#second_child {
    height:350px;
    margin-left:350px;
}

Here is a working example (with added styles to see the effect)

A: A good answer with pure CSS was given above, so I'll just answer the question of "how do I find the width needed?" in javascript.
// This is assuming there is no padding.
totalWidth = document.getElementById('container').offsetWidth;
firstChildWidth = document.getElementById('first_child').offsetWidth;
document.getElementById('second_child').style.width = (totalWidth - firstChildWidth) + 'px';

A: Using jQuery:
var containerWidth = $('#container').width();
$('#second_child').width(containerWidth - 350);

A: You can do that with pure css positioning, since you know how big the first child is:
#container {
position:relative
}

#first_child {
width:350px;
height:350px
}

#second_child {
height:350px;
position:absolute;
top: 0;
left:350px;
right:0;
}

Note that the container div has position:relative. This is necessary to make position:absolute use the top left corner of the container div instead of the body.