text:
Q: fcbkcomplete, how to obtain all the values after adding or updating the Input I'm interested in using fcbkcomplete, which has:

*

*onselect – fire event on item select.

*onremove – fire event on item remove

What I'd like to happen for those two events is to alert a list of the IDs/values of the items in the input box.
Can you help me understand how to get these values?
Thanks

A: Since the plugin is tied to the actual select element, not the option elements inside, you should be able to write a function that just alerts out all option details of the contained options of the parent select. Maybe something like:
$("#select").fcbkcomplete({
       onselect: function() {
           var optionList;
           $("option",this).each(function() {
               optionList += $(this).attr("id") + " : " + $(this).val() + "\n";
           });
           alert(optionList);
       }
});

A: Checks if an item exists in the DB in this case a user.
$(document).ready(function () {
    $("#users").fcbkcomplete({
        json_url: "yoururl.php",
        cache: false,
        filter_case: false,
        filter_hide: true,
        complete_text:"'.get_lang('StartToType').'",
        firstselected: true,
        onselect:"check_users",   //<----- important
        filter_selected: true,
        newel: true
    });
});

Hewe we check if users exists in the DB
function check_users() {
    //selecting only "selected" users
    $("#users option:selected").each(function() {
        var user_id = $(this).val();
        if (user_id != "" ) {
            $.ajax({
                url: "my_other_url_to_check_users.php",
                data: "user_id="+user_id,
                success: function(return_value) {
                    if (return_value == 0 ) {
                        alert("UserDoesNotExist");
                    }
                },
            });
        }
    });
}


text:
Q: Multiple foreign keys composing another element I am trying to create a database for some box listings. These boxes contain different products in various quantities. How should I implement the table which holds the content of each box?
I'm new to MySql and that is the reason why this may sound so as such a stupid question, but I don't understand how a table will hold different products and their quantities for each box.
Thank you in advance.

A: Because box and product would have a many to many relation, you can solve this by using a associative entity: https://en.wikipedia.org/wiki/Associative_entity.
You have a table 'box', a table 'product' and a table 'box_product'

*

*Box has a one to many relation to box_product.

*Product also has a one to many relation to box_product
In box_product, you would have only 3 columns: 'id', 'box_id' and 'product_id'.
(Could also be 2 columns if you use a composite primary key, and leave out 'id')
Example:
Let's say one box has 3 products: A, B and C. It has one A, 2 B's and 3 C's.
For this example, there would be:

*

*one row in box

*3 rows in product (you do not need to duplicate rows in the product table, just one row per product, no matter how many boxes or quantities of it there are).

*one row in box_product for A, 2 rows in box_product for B, and 3 rows in box_product for C (so 6 rows in the associative entity total).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript weird object I've got this code from a javascript file that looks like some object but Im not sure.
How can I use this data?
DataStore.prime('standings', { stageId: 36 },
[
 [36,13,'Arsenal',1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,,,]
,[36,24,'Aston Villa',2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,,,]
,[36,184,'Burnley',3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,,,]
]);

A: What you see here is an array (not an object), which elements are 3 other arrays, which elements are numbers and Strings.
Here it is in a more conventional form :
var myArray = [
  [36, 13, 'Arsenal', 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, , , ],
  [36, 24, 'Aston Villa', 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, , , ],
  [36, 184, 'Burnley', 3, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, , , ]
];

myArray[0][1]; // 13
myArray[1][2]; // 'Aston Villa'
myArray[2][31]; // undefined

From the script I reckon this is data about some football clubs.

A: DataStore //some class
.prime //probably the function
(
'standings', //argument 1 which is a string calling a string event
{ stageId: 36 }, //argument 2 an object, must be referencing to a stage event

[
 [36,13,'Arsenal',1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,,,]
,[36,24,'Aston Villa',2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,,,]
,[36,184,'Burnley',3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,,,]
] //Argument 3 Multidimensional Array which looks like some stats for a certain team

);

Is this some highscore table for a game?


text:
Q: Vader Sentiment Analysis in R I am using Vader Sentiment Analysis on Tweets for a project of mine with 3000 tweets. Everything is working fine when I run the sentiment for only 1 tweet. That gives me all the scores for that tweet but when I run the loop command for all the tweets, I only get the final results as the overall combined score for Vader. I am interested to get the final results as the first one which is giving all the scores. Any help will be highly appreciated.
Sample data:
dput(data_sample$text)
c("Need DoorDash or Uber method asap cause I be starving",
"I'm such a real ahh niqq cuz I be having myself weak asl",
"This shii made me laugh so fuccin hard bro",
"Kevin Hart and Will Ferrell made a Gem in Get hard fr",
"@_big_emmy @NigerianAmazon Chill", "Ts so bomedy ",
"So is that ass Gotdam",
"This wild", "Idc them late night DoorDash's be goin crazy",
"Video of the week")

Code:
get_vader(data_sample$text[1])

I need this result for all 10 tweets from that loop below:
word_scores                            compound                                 pos
"{0, 0, 0, 0, 0, 0, 0, 0, 0, -1.8}"                            "-0.421"                                 "0"
                                neu                                 neg                           but_count
                            "0.763"                             "0.237"                                 "0"

Not like this:
for (i in 1:length(data_sample$text)){
  Loop_Error <- F
  tryCatch({
    get_vader(data_sample$text[i]) %>%
      as.numeric(unlist(.)) %>%
      .[length(.)-4] ->data_sample$score_vader[i]
  }, error = function(e){
    Loop_Error <<- T})
  if (Loop_Error){
    data_sample$score_vader[i] <- "Error"
  }
}

vader_data

data_sample$score_vader
1                   -0.421
2                   -0.440
3                    0.444
4                   -0.103
5                    0.000
6                    0.000
7                   -0.581
8                    0.000
9                   -0.340
10                   0.000

A: I have this idea to get all the outputs of data_sample given by get_vader(), but you will need to modify your code a bit to use vader_df():
allvals <- NULL
for (i in 1:length(data_sample)){
outs <-  vader_df(data_sample[i])
allvals <- rbind(allvals,outs)
}


text:
Q: R column of ints find nearest value I have a frame
J = data.frame(Entry = c(100, 5, 10, 20, 35))

For each record I want to find the nearest value and end up with
Entry | nearest
 100  |  35
 5    |  10
 20   |  10
 35   |  20

I looked at the data table code Find closest value in a vector with binary search
but because for Entry I am trying to find the closest value it just returns the vector that I enter. How can I do this?

A: J <- data.frame(Entry = c(100, 5, 10, 20, 35),
               X = sapply(J$Entry, function(x){
  temp <- J$Entry[!J$Entry == x]
  temp[which.min(abs(temp - x))]
}))

> J
  Entry  X
1   100 35
2     5 10
3    10  5
4    20 10
5    35 20

Like this?


text:
Q: No suitable driver found for jdbc:postgresql: I have Spring/Hibernate application that is using MySQL database. I deployed it on Heroku and converted my db properties file according Heroku Postgres settings, but after application starts I receive following error:

java.sql.SQLException: No suitable driver found for jdbc:postgresql://okhuoxugkgndyv:42a41d66da81c48b4242a408f6f5ab95a8b6af21eb2150fed2b8c6cf50ef27a7@ec2-54-246-87-132.eu-west-1.compute.amazonaws.com:5432/de0n3c1ovtml0v```

Here is my db.properties file
db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://okhuoxugkgndyv:42a41d66da81c48b4242a408f6f5ab95a8b6af21eb2150fed2b8c6cf50ef27a7@ec2-54-246-87-132.eu-west-1.compute.amazonaws.com:5432/de0n3c1ovtml0v
db.user=okhuoxugkgndyv
db.password=42a41d66da81c48b4242a408f6f5ab95a8b6af21eb2150fed2b8c6cf50ef27a7
db.poolSize=25

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.user}"/>
        <property name="password" value="${db.password}"/>
    </bean>

In pom.xml I also have maven dependency.
<!-- https://mvnrepository.com/artifact/postgresql/postgresql -->
    <dependency>
      <groupId>postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>9.1-901-1.jdbc4</version>
    </dependency>

A: It's not with jdbc drive it's due to properties are not able to find.
As in your datasource configuration very first properties is driver and it's giving an error.
If you bring that line on second , you will get an error with URL.
You need to add db.property file name in you bean.xml file
<bean  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" scope="prototype">

    <property name="location">
        <value>classpath:/bundle/db.properties</value>
    </property>
</bean>

First try with static details as below. If it's work then try to bring those details from property file.
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/dbname" />
        <property name="username" value="postgres" />
        <property name="password" value="" />


text:
Q: Question based on circular permutations
Consider 21 different pearls on a necklace. The number of ways can the pearls be placed in on this necklace such that 3 specific pearls always remain together is?

Using the string method, I got the final answer as $(6)(18!)$, but given answer is $(3)(18!)$.
This brings me to my question. The only way $(3)(18!)$ can be the answer of clockwise and counterclockwise arrangements are taken as same.
How do we make the distinction between the two cases where circular arrangements matter and where they don't matter.


text:
Q: Change the text color of the toolbar overview I cannot find how to change the text color of the overview toolbar on Android.. :

I tried this one :
android:theme="@style/AppTheme"

<style name="AppBlankTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme" parent="AppBlankTheme">
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">true</item>
    <item name="android:textColorPrimary">@android:color/white</item>
    <item name="android:textColorSecondary">@android:color/white</item>
</style>

I want to change the color of the title ("Sharezone") and the close button of the overview toolbar to white.
Thanks.
------------------------- EDIT -------------------------------------------
After a lot of failed solutions, here's my entire code :
style.xml
<style name="AppBlankTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme" parent="AppBlankTheme">
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <item name="android:textColorTertiary">@color/grey_300</item>
</style>

AndroidManifest.xml
<application
    ...
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        ...
        android:theme="@style/AppTheme">
    </activity>
</application>

And here's the toolbar I use in Activity :
<android.support.v7.widget.Toolbar android:id="@+id/toolbar"
    android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary">
    <TextView
        android:id="@+id/toolbar_app_name"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/app_name"
        android:textSize="30sp"
        android:gravity="center_horizontal|center_vertical"
        android:textColor="@color/grey_300"/>
</android.support.v7.widget.Toolbar>

A: This is because of Theme.which you have set in your style
style name="AppBlankTheme" parent="Theme.AppCompat.Light.DarkActionBar"
please use this Theme
style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"
Now your App's dark theme will be removed

A: #. Seems your themes are OK. In AndroidManifest.xml file, apply AppTheme to your desired Activity.
AndroidManifest.xml
    <activity
        android:name=".YourActivity"
        android:theme="@style/AppTheme" />

#. If you are using Toolbar in your layout XML, then you can change its title color programmatically:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar)
toolbar.setTitleTextColor(Color.WHITE);

UPDATE:
As per your updated question, seems you are using custom Toolbar. To change title "Sharezone" color, you have to change the background color of TextView (toolbar_app_name).
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary">

    <TextView
        android:id="@+id/toolbar_app_name"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/app_name"
        android:textSize="30sp"
        android:gravity="center_horizontal|center_vertical"
        android:textColor="#FFFFFF"/>
</android.support.v7.widget.Toolbar>

Hope this will help~

A: You can do that by XML, if your activity is called MainActivity go to the res/layout/activity_main, go to design and press/select the action bar, then to properties on the right and select titleTextColor and change tot he required colour.

Choose colour here:


text:
Q: How can I add programmability to my application I'm writing an applicaton that is, at its core, a rules engine. The users want to be able to define custom rules. Some of these will be fairly simple algebraic expressions, many will involve some if-then branching logic, and some will be even more complex. What are my options for doing this?
My users are pretty smart, proficient at T-SQL and Excel commands, and generally familiar with programming constructs but they are not "programmers" per se.
I've thought about using VBA/VSTA; interoperating with Excel somehow; integrating some sort of scripting language (Ruby? Perl? Tcl?); or rolling my own.
In the best of all possible worlds, I will give them an editor with color coding and IntelliSense-like interactive help, an immediate execution mode for testing and experimenting, and a step-thru debugger. They also need to be able to save, retrieve, edit, and execute their rules. Blazing speed is not essential.
My environment is Windows/.Net 3.5/C#
Any ideas?

A: I'm not a windows person so my answers won't exactly suit your situation. I'd recommend embedding a full blown scripting language interpreter into your application. Expose some primitives (ie. the parts of your rule engine you want public) and then provide a full blown interpreter. I know that TCL, Python and Guile are designed to be embedded in this fashion. I'd personally recommend Python since Scheme (guile) is a little esoteric and TCL seems to be losing ground generally.

A: Any implementation like that is full of risks.  I'd start with the smallest possible set of customizations and then incrementally build up your capabilities from there.
Don't try to program all sorts of extensibilities into it at once, unless you already have lots of skill doing that.  Pick one simple ability at a time - running standard SQL queries and returningg recordsets or whatever.

A: It won't be quite all that you're asking for, but I depending on your needs, I would investigate Boo. It's relatively painless to build a DSL in Boo that is relatively readable to the business folks, which has great benefits even if they aren't the ones coding the rules directly.
Oren Eini's Building Domain Specific Languages in Boo is pretty good, and just came out in final form. A rules engine is one of the example implementations of a DSL that he examines. Boo is a fully-built statically typed Python-like language for .Net, with a small but strong community, and makes altering the language to suit specific needs easier than almost every other alternative, thanks to an extensible compiler pipeline and a very nice semantically-smart macro system.
The nice thing about Boo is that most DSLs are just built on a common base class that provides the "language" you need, but isn't much different than the code you'd be writing to hard-coded rules. You can make the language look exactly like you want, but won't have to worry about hand-parsing or writing control flow commands or all the stuff that you'd expect a language to have.
There are some downsides: It's not quite like Python or Ruby, the documentation is mostly in Boo's source code, and the community is, yes, small. But if you can "teach by example" you can get pretty far. The main caveat that applies to your wishlist is in code completion; code completion has limited support with some VS plugins and with SharpDevelop, but what is there pretty much evaporates as you build out the DSL.

A: Since .NET is your platform, embedding ironpython might work for you.  In fact, the author of one of the ironpython books used ironpython in a product that seems to (on the surface) have a lot of similarities with what you're doing.  I think it was called Resolver One.
Edit
It is called Resolver One
Here's a link to his book.

A: Don't invent your own scripting language! It is bad to learn a new language for a single system. I'd try to use Python which is relatively easy to learn and to understand.

A: Windows has built in Windows Script Host engine with two interpreters for VBScript and JScript. You can easily use them. Just check out MSDN for appropriate COM interfaces.

A: Lua could be a good solution. What I'm really wondering is how complex could be to integrate your rules engine with a scripting language that allows users to write their own rules.
A good approach can be to embed everything (the rule engine too) inside the scripting interpreter, otherwise you would end up writing a lot of code to bridge what an user writes into the script with the related rules used in your program.
However designing such programmability requires much attention to what your language should be able to do, starting from a little core of utilities and then extending it; or you can really plan a lot before starting the whole implementation but for my experience (I wrote like 3-4 interpreters so far) the better way is to fit it while developing it, of course with the feedback of the users: it will be necessary, because you can suppose how good they are, but I wouldn't count on it.

A: For an honest-to-God rules engine, you could look into using Clips. Clips is an OpenSource expert system that you can embed into your own applications.
If you want true scripting, there are tons of tools out there to add in scripting to applications with languages like Lua, TCL, REXX, etc.
No matter what you do, you should check out the licensing closely. Embedding someone else's code into yours often has repercussions on how you can license the resulting program.

A: Talking from experience, because our main software has a scripting feature.
We use the Actipro SyntaxEditor as our scripting designer. Our original requirement was to "The user shall be able to write a formula for a field. That formula will be used to validate the content of the field."
From that, we used Dynamic Linq. The user was able to write a formula while still being able to add mathematical functions and custom functions. We didn't need more at the time, but are now seeing limitation of using the Dynamic Linq.
If we are to make a new version of our scripting engine, we would now be looking forward to using the new DLR-enabled language: IronPython and IronRuby

A: We currently use Mozilla's SpiderMonkey to do this exact thing in our web application. It is a javascript engine so you can create your own functions and objects that corresponds to actual business logic in your application. Javascript::SpiderMonkey is a perl module that interfaces but I believe there are more languages that work with it.

A: If the structure and rules are clearly understood, then I would mimic the Query interface that is contained in Lucene (java and .net). Basically, your rules become query types and you can and/or them together much in the same way that Lucene does it.
Lastly, you can then create an interface that allows your users to do this work. The critical piece will be the query types and the associated metadata that can serve as items upon which to be acted.
For example, say your rules engine was an ecommerce engine and you allow your users to define rules that will reward customers with a discount if they add a particular product to their basket.
They would pick a type of ProductQuery which matches on product number and then a successful completion of the productquery would result in a discountreward that is automatically applied.
Hope this helps.

A: As others have stated, LUA is a fairly quick and easy way to embed a scripting language inside your application. Our company's product has a macro feature, and I was briefly entertaining the idea of embedding full scripting support as part of it. But ultimately we decided trainign would be a nightmare.
Regardless, this is a pretty good introduction to embedded LUA in c# if you choose that route:
http://blog.apterainc.com/software/embedding-lua-and-c/

A: Instead of an embeded scipting language, think of programing a graphical language or tool, if you can identify all the possible rules and map them to the appropiete code, You could offer to the end-user a simple & easy way to add behaviors & action to their workflow in a visual manner.
Offering a UI-based rule engine is more simple to learn & more convenient for non programmeurs. And you can always add an embeded scripting language, to customize the preexisting actions, latter.
Also, it's the common tool used in ETL for exemple, in order to create Business rules


text:
Q: Installation of PuTTY on Mac-Mojave I downloaded PuTTY as given in this https://www.puttygen.com/download-putty .
And I got a Unix executable file and as soon as I click on it I am getting an error:
(process:5149): Gtk-WARNING **: 21:09:33.715: Locale not supported by C library.
    Using the fallback 'C' locale.

(PuTTY:5149): Gtk-WARNING **: 21:09:33.734: cannot open display:
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

My locale are set as follows:
LANG=
LC_COLLATE="C"
LC_CTYPE="C"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL="C"

Can someone please help me how can I resolve this error? and move forward to my PuTTY configuration window.

A: The messages about the "locale" settings shouldn't matter. It ought to work without it using the "fallback" locale.
But:
Putty for Mac requires X11 which is no longer part of OSX on the newer MacOS versions.
The "Can't open display" error message refers most likely to that problem.
You will need to install the XQuartz system which is the (open source) successor to the X11.app.


text:
Q: Turning off random PHP gif logo How does one go about turning off my PHP site from displaying the php logo gif when accessing: sitename.com/?=PHPE9568F36-D428-11d2-A769-00AA001ACF42
After some reading and hunting I came across this:

PHP CODER GUY WITH BREADSTICKS (Thies
  C. Arntzen): PHP Version 4.0.0 - 4.2.3
BROWN DOG IN GRASS (Stig's dog,
  Nadia): PHP Version 4.3.0 - 4.3.10
BLACK SCOTTISH TERRIER (Zeev's dog,
  Scotch): PHP Versions 4.3.11 - 4.4.6;
  and 5.0.4 - 5.1.2
BUNNY (Sterling's rabbit, Carmella):
  PHP Version 5.0.0 - 5.0.3
COLORED PHP LOGO: PHP Version 5.1.3 -
  5.2.13
ELEPHANT PHP LOGO: PHP Version 5.3.0 -
  current

Turns out the images change for every version.
Anyway, is there a way to turn this off in the PHP .ini ?

A: Turns out it was a relatively simple fix.
In the php.ini there is an option called expose_php which must be set to off!


text:
Q: If term in file 1 is in line of file 2, write the whole line in file 2 to file 3 I have a two text files, one containing a list of identifiers, the other containing a list of even more identifiers, plus some other bits of info I want.  What I want to do is compare the identifiers in files 1 and 2, and if they match, write the line in file 2 to a new file, file 3.
Here's what I have (it's a bit weird, as I got into lists and I never got that far in programming):
def identify(MOPED_Prot, Swiss_Prot, MOPED_to_Swiss):
  Swiss = open(Swiss_Prot, 'r')
  M = open(M_Prot, 'r')
  output = open(M_to_Swiss, 'wt')
  Swissids = []
  ids = []
  for line in M.readlines():
    ids.append(line[:5])
  for line in Swiss.readlines():
    Swissids.append(line)
  while set(ids)& set(Swissids):
      output.write(#line?  Not sure what goes here + "\n")

I did get the code to write one of the lines from "Swiss" into the new file for every intersection with code similar to this, but it only repeated a single line.  Honestly, the end is what has me confused.
Edit:  As requested, here's what the files look like
File 1:
B4E035
P23946
O00376
D6RGF3
B2RDK6
Q12999
Q8TDD2
B2RDC9
C9JL66
Q9NZQ9

File 2:
P31946  1433B_HUMAN YWHAB
P62258  1433E_HUMAN YWHAE
Q04917  1433F_HUMAN YWHAH YWHA1
P61981  1433G_HUMAN YWHAG
P31947  1433S_HUMAN SFN HME1

File 3 should output the line in file two, if any of the identifiers in the first column match (they are all 6 characters in length)

A: I write something here thata could help you...I put into a folder three files
file_a.txt (contaning in each line  1, 2, 3, 4, 5)
file_b.txt (contaning in each line  4, 5, 6, 7, 8)
final_file.txt
and this i my script:
# -*- coding: utf-8 -*-

from collections import Counter

file_a = open('file_a.txt', 'r')
file_b = open('file_b.txt', 'r')
final_file = open('final_file.txt', 'w')

ids = []

for line in file_a.readlines():
  ids.append(line)

print ids
c = Counter(ids)

for line in file_b.readlines():
  print line;
  print 'count' + str(c[line])
  if c[line] > 0:
    final_file.write(line);

file_b.close();
final_file.close();
file_a.close();

A: Supposing that file1 contains one identifier per line, maybe you can use something like this:
with open (file1, 'r') as f: ids = [line.strip () for line in f]
with open (file2, 'r') as f:
    with open (file3, 'w') as g:
        for line in f:
            if any (id in line for id in ids): g.write (line)

Nota bene: I do not have python2.7 installed (and until now I read that you needed python2.7). Maybe you need to do some adaption to port this code to py2.
EDIT: Taking into consideration your sample data, you can try this:
with open (file1, 'r') as f: ids = [line.strip () for line in f]
with open (file2, 'r') as f:
    with open (file3, 'w') as g:
        for line in f:
            if any (line.startswith (id) for id in ids): g.write (line)


text:
Q: How to delete Tkinter widgets from a window? I have a list of tkinter widgets that I want to change dynamically.
How to delete the widgets from the window?

A: You simply use the destroy() method to delete the specified widgets like this:
lbl = tk.Label(....)

btn = tk.Button(....., command=lambda: lbl.destroy())

Using this you can completely destroy the specific widgets.

A: One way you can do it, is to get the slaves list from the frame that needs to be cleared and destroy or "hide" them according to your needs. To get a clear frame you can do it like this:
from tkinter import *

root = Tk()

def clear():
    list = root.grid_slaves()
    for l in list:
        l.destroy()

Label(root,text='Hello World!').grid(row=0)
Button(root,text='Clear',command=clear).grid(row=1)

root.mainloop()

You should call grid_slaves(), pack_slaves() or slaves() depending on the method you used to add the widget to the frame.

A: You can call pack_forget to remove a widget (if you use pack to add it to the window).
Example:
from tkinter import *

root = Tk()

b = Button(root, text="Delete me", command=lambda: b.pack_forget())
b.pack()

root.mainloop()

If you use pack_forget, you can later show the widget again calling pack again. If you want to permanently delete it, call destroy on the widget (then you won't be able to re-add it).
If you use the grid method, you can use grid_forget or grid_remove to hide the widget.

A: You say that you have a list of widgets to change dynamically. Do you want to reuse and reconfigure existing widgets, or create all new widgets and delete the old ones? It affects the answer.
If you want to reuse the existing widgets, just reconfigure them. Or, if you just want to hide some of them temporarily, use the corresponding "forget" method to hide them. If you mapped them with pack() calls, you would hide with pack_forget() (or just forget()) calls. Accordingly, grid_forget() to hide gridded widgets, and place_forget() for placed widgets.
If you do not intend to reuse the widgets, you can destroy them with a straight destroy() call, like widget.destroy(), to free up resources.

A:
clear_btm=Button(master,text="Clear") #this button will delete the widgets
clear_btm["command"] = lambda one = button1, two = text1, three = entry1: clear(one,two,three) #pass the widgets
clear_btm.pack()

def clear(*widgets):
    for widget in widgets:
        widget.destroy() #finally we are deleting the widgets.

A: I found that when the widget is part of a function and the grid_remove is part of another function it does not remove the label. In this example...
def somefunction(self):
    Label(self, text=" ").grid(row = 0, column = 0)
    self.text_ent = Entry(self)
    self.text_ent.grid(row = 1, column = 0)
def someotherfunction(self):
    somefunction.text_ent.grid_remove()

...there is no valid way of removing the Label.
The only solution I could find is to give the label a name and make it global:
def somefunction(self):
    global label
    label = Label(self, text=" ")
    label.grid(row = 0, column = 0)
    self.text_ent = Entry(self)
    self.text_ent.grid(row = 1, column = 0)
def someotherfunction(self):
    global label
    somefunction.text_ent.grid_remove()
    label.grid_remove()

When I ran into this problem there was a class involved, one function being in the class and one not, so I'm not sure the global label lines are really needed in the above.

A: Today I learn some simple and good click event handling using tkinter gui library in python3, which I would like to share inside this thread.
from tkinter import *

cnt = 0

def MsgClick(event):
    children = root.winfo_children()
    for child in children:
        # print("type of widget is : " + str(type(child)))
        if str(type(child)) == "<class 'tkinter.Message'>":
            # print("Here Message widget will destroy")
            child.destroy()
            return

def MsgMotion(event):
  print("Mouse position: (%s %s)" % (event.x, event.y))
  return

def ButtonClick(event):
    global cnt, msg
    cnt += 1
    msg = Message(root, text="you just clicked the button..." + str(cnt) + "...time...")
    msg.config(bg='lightgreen', font=('times', 24, 'italic'))
    msg.bind("<Button-1>", MsgClick)
    msg.bind("<Motion>", MsgMotion)
    msg.pack()
    #print(type(msg)) tkinter.Message

def ButtonDoubleClick(event):
    import sys; sys.exit()

root = Tk()

root.title("My First GUI App in Python")
root.minsize(width=300, height=300)
root.maxsize(width=400, height=350)
button = Button(
    root, text="Click Me!", width=40, height=3
)
button.pack()
button.bind("<Button-1>", ButtonClick)
button.bind("<Double-1>", ButtonDoubleClick)

root.mainloop()

Hope it will help someone...

A: You can use forget method on the widget
from tkinter import *

root = Tk()

b = Button(root, text="Delete me", command=b.forget)
b.pack()

b['command'] = b.forget

root.mainloop()


text:
Q: Using an intent to forward users to twitter app with pre-determiend search keyword I want to be able to switch between my app and twitters app to show a search for a pre-determined hashtag.
I have an on click listener & sending the user to the twitter app... loading the tweets and allowing the discussion of that hashtag. There is the logic but how can I do this? What I get now is just my feed and a drop down list of previous searches.
Here is the listener & intent code:
final Button button = (Button) view.findViewById(R.id.C_Twitter_Button);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

        try {
            Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("twitter://search?f=realtime&q=%23KeyWord"));
            startActivity(intent);

        }catch (Exception e) {
            startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("https://twitter.com/search?f=realtime&q=%23KeyWord")));
        }
    }
});

Can anyone offer me a solution?
Thanks

A: The search query was wrong :(
The solution is to use the following url to search the twitter app:
twitter://search?query=%23hashtag
Cheers


text:
Q: Print DevTool's Network Traffic output to webpage I'm currently trying to stream a DHCP video over HTML with a docker container, so far, everything has been working fine. I was only wondering if there is a way I could print the video segment that is currently being requested inside my webpage so that I can demo what's exactly happening.
(segment can be seen in chrome's devtools )

Maybe with a javascript function.


text:
Q: When I'm using phantomJS in node, the error appeared I'm using phantomJS in node and wrote the following code, but the error appeared on the console.
The following code simply tries to access the google top page and take a screen shot of its page.
How should I resolve this error?
(node version: v6.10.3)
(1) code(test.js)
var phantom = require("phantom");
var promise = phantom.create().then(function(ph) {
    return ph.createPage().then(function(page) {
        page.property('onConsoleMessage', function(msg) {
            console.log(msg);
        });
        page.property('onLoadStarted', function() {
            loadInProgress = true;
            console.log('Load Started...');
        });
        page.property('onLoadFinished', function() {
            loadInProgress = false;
            console.log('Load End');
        });

        var loadInProgress = false;
        var stepIndex = 0;
        var steps = [
            function() {
                page.open('https://www.google.co.jp/').then(function (status) {
                    // something process
                }).catch(function(error){
                    console.log(error); // <======= Here, the error appeared
                });
            },
            function() {
                console.log("step end");
            }
        ];

        interval = setInterval(function(){
            if(!loadInProgress && typeof steps[stepIndex] == 'function') {
                steps[stepIndex]();
                stepIndex++;
            } else if (steps[stepIndex] != 'function') {
                ph.exit();
                clearInterval(interval);
            }
        }, 10);
    });
});

(2) error
$ node test.js
step end
warn: exit() was called before waiting for commands to finish. Make sure you are not calling exit() too soon.
info: Load Started...
Error: Phantom process stopped with exit code 0
    at Phantom._rejectAllCommands (<myfilepath>/phantomjs/node_modules/phantom/lib/phantom.js:361:41)
    at ChildProcess.Phantom.process.on.code (<myfilepath>/phantomjs/node_modules/phantom/lib/phantom.js:164:18)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)

A: You exit the script too early, exactly as the error says.
Remove ph.exit(); from the interval function:
    interval = setInterval(function(){
        if(!loadInProgress && typeof steps[stepIndex] == 'function') {
            steps[stepIndex]();
            stepIndex++;
        } else if (steps[stepIndex] != 'function') {
            // ph.exit(); // <-- remove exit() from here
            clearInterval(interval);
        }
    }, 10);

Move it instead into page.open callback for it to be called after the page is opened:
page.open('https://www.google.co.jp/').then(function (status) {
    ph.exit();
})


text:
Q: How to get the absolute file path of a Google drive file as a url? Is there any way to get the file path of a file in Google drive? Generally, google drive file url can be a sharing url. But what if we wanted to access the absolute file path? Something like:
drive.google.com/file/myvideo.mp4
And then I wanted to show the video file in a webpage using a video tag.
Google drive is taking too long to process a video file that I uploaded, so I cannot embed it on my website, so I thought maybe accessing the file path will do the trick :)
So how to get something like above url?
Thanks for helping.
Edit:
Found it! Now I can get the absolute file path of any file in my drive. Follow the steps:
1- Open:
https://drive.google.com/us?id=yourfileid
Where yourfileid is file id
2- load and copy the URL at the page
3- that's it, it's the absolute file path URL

A: to get the absolute path of a video on the google drive just send a request to the link
https://drive.google.com/u/1/get_video_info?docid="+IdVideo

the return will be a byte-by-byte file that contains all the information in the video including the absolute link it is worth remembering that the data is encoded in url right away to access it just decode another important point and that the link you obtained is only valid for the device that made the request why the link it is linked to the ip and also to the agent that sent the request for example if you sent the request with postman and try to open the link in chrome there will be an access denied error and vice versa.
Below is an example of the response provided by the request:
status=ok&hl=pt_BR&allow_embed=0&ps=docs&partnerid=30&autoplay=0&docid=1HCK3eleZSNQfpuZaI_oyIBQ9I_DroTq8&abd=0&public=true&el=embed&title=Jogos+Vorazes+Em+Chamas+-+ToTTi9.mp4&BASE_URL=https%3A%2F%2Fdrive.google.com%2Fu%2F0%2F&iurl=https%3A%2F%2Fdrive.google.com%2Fu%2F0%2Fvt%3Fauthuser%3D0%26id%3D1HCK3eleZSNQfpuZaI_oyIBQ9I_DroTq8%26s%3DAMedNnoAAAAAYHNJTEUxV9Q3qpFIyzfWQ9jSgXyoRJ7h&cc3_module=https%3A%2F%2Fs.ytimg.com%2Fyt%2Fswfbin%2Fsubtitles3_module.swf&ttsurl=https%3A%2F%2Fdrive.google.com%2Fu%2F0%2Ftimedtext%3Fauthuser%3D0%26id%3D1HCK3eleZSNQfpuZaI_oyIBQ9I_DroTq8%26vid%3D78edbfcf1fc76400&reportabuseurl=https%3A%2F%2Fdrive.google.com%2Fu%2F0%2Fabuse%3Fauthuser%3D0%26id%3D1HCK3eleZSNQfpuZaI_oyIBQ9I_DroTq8&token=1&plid=V0QWdNzM2hSOAQ&fmt_stream_map=18%7Chttps%3A%2F%2Fr2---sn-bg0eznlz.c.drive.google.com%2Fvideoplayback%3Fexpire%3D1618175340%26ei%3DLC1zYNjFDcOM8gStnI64Bg%26ip%3D45.184.131.85%26cp%3DQVRGWkJfVFNSQVhPOlp3SExoWl9oYTNKYk56Sm1iU3dGd25LakR1Y1BUM01JNmVUYW5SRDNWZjM%26id%3D78edbfcf1fc76400%26itag%3D18%26source%3Dwebdrive%26requiressl%3Dyes%26mh%3DXL%26mm%3D32%26mn%3Dsn-bg0eznlz%26ms%3Dsu%26mv%3Du%26mvi%3D2%26pl%3D24%26ttl%3Dtransient%26susc%3Ddr%26driveid%3D1HCK3eleZSNQfpuZaI_oyIBQ9I_DroTq8%26app%3Dexplorer%26mime%3Dvideo%2Fmp4%26vprv%3D1%26prv%3D1%26dur%3D8775.029%26lmt%3D1612203534601168%26mt%3D1618160459%26sparams%3Dexpire%252Cei%252Cip%252Ccp%252Cid%252Citag%252Csource%252Crequiressl%252Cttl%252Csusc%252Cdriveid%252Capp%252Cmime%252Cvprv%252Cprv%252Cdur%252Clmt%26sig%3DAOq0QJ8wRQIhAPjdubHafwixI9u_3cHc4Qt0sF8092zP3ZNSxPvqHY7nAiApe4jGKLmb4jVA4vqAGa5M-Sv2vPiwCCMFDIjzPvpq-Q%3D%3D%26lsparams%3Dmh%252Cmm%252Cmn%252Cms%252Cmv%252Cmvi%252Cpl%26lsig%3DAG3C_xAwRgIhAL9KrFxY09TeS3LW7B6wVmuM6pJTlVNC7B3uqVYHYXiuAiEAv43kEsHHcDK805VYorcU_CSm9_END9gpT_KX7QSZ9PA%3D%2C22%7Chttps%3A%2F%2Fr2---sn-bg0eznlz.c.drive.google.com%2Fvideoplayback%3Fexpire%3D1618175340%26ei%3DLC1zYNjFDcOM8gStnI64Bg%26ip%3D45.184.131.85%26cp%3DQVRGWkJfVFNSQVhPOlp3SExoWl9oYTNKYk56Sm1iU3dGd25LakR1Y1BUM01JNmVUYW5SRDNWZjM%26id%3D78edbfcf1fc76400%26itag%3D22%26source%3Dwebdrive%26requiressl%3Dyes%26mh%3DXL%26mm%3D32%26mn%3Dsn-bg0eznlz%26ms%3Dsu%26mv%3Du%26mvi%3D2%26pl%3D24%26ttl%3Dtransient%26susc%3Ddr%26driveid%3D1HCK3eleZSNQfpuZaI_oyIBQ9I_DroTq8%26app%3Dexplorer%26mime%3Dvideo%2Fmp4%26vprv%3D1%26prv%3D1%26dur%3D8775.029%26lmt%3D1612196404551931%26mt%3D1618160459%26sparams%3Dexpire%252Cei%252Cip%252Ccp%252Cid%252Citag%252Csource%252Crequiressl%252Cttl%252Csusc%252Cdriveid%252Capp%252Cmime%252Cvprv%252Cprv%252Cdur%252Clmt%26sig%3DAOq0QJ8wRAIgJFTtuzFA6Y8D-esOQBFfwIc0N2Sncbo32ERciZ9TaecCIGCvb44U8ejqtdUzc84GmFKT_17DpYj2iWXBROl3n5E2%26lsparams%3Dmh%252Cmm%252Cmn%252Cms%252Cmv%252Cmvi%252Cpl%26lsig%3DAG3C_xAwRQIgVeWACgdswVRbGA7KGlPCE1rbEkmbG-J7Qu_frbBTd3ECIQCvqYFUuOZ9quV33O5FsS5duvgynpNG_5IEZDm48i7Uhw%3D%3D%2C37%7Chttps%3A%2F%2Fr2---sn-bg0eznlz.c.drive.google.com%2Fvideoplayback%3Fexpire%3D1618175340%26ei%3DLC1zYNjFDcOM8gStnI64Bg%26ip%3D45.184.131.85%26cp%3DQVRGWkJfVFNSQVhPOlp3SExoWl9oYTNKYk56Sm1iU3dGd25LakR1Y1BUM01JNmVUYW5SRDNWZjM%26id%3D78edbfcf1fc76400%26itag%3D37%26source%3Dwebdrive%26requiressl%3Dyes%26mh%3DXL%26mm%3D32%26mn%3Dsn-bg0eznlz%26ms%3Dsu%26mv%3Du%26mvi%3D2%26pl%3D24%26ttl%3Dtransient%26susc%3Ddr%26driveid%3D1HCK3eleZSNQfpuZaI_oyIBQ9I_DroTq8%26app%3Dexplorer%26mime%3Dvideo%2Fmp4%26vprv%3D1%26prv%3D1%26dur%3D8775.029%26lmt%3D1612265735773933%26mt%3D1618160459%26sparams%3Dexpire%252Cei%252Cip%252Ccp%252Cid%252Citag%252Csource%252Crequiressl%252Cttl%252Csusc%252Cdriveid%252Capp%252Cmime%252Cvprv%252Cprv%252Cdur%252Clmt%26sig%3DAOq0QJ8wRAIgVK9gEt4VVCfclg29yeicdxkjSLBH5GLBaGc2zZ3rFs8CIEAZ-8QHSI3r2a2JI27km7J_6lf1yAF_knmUCfboxC5G%26lsparams%3Dmh%252Cmm%252Cmn%252Cms%252Cmv%252Cmvi%252Cpl%26lsig%3DAG3C_xAwRQIhAIMFtRVlbf2oImOUp7CqF_MlH5073S-RvuJ2s3rHqwHPAiBIjnF5UtBKJ73vipMsiqERIQ0kIVFeAq_jFP93gEhnVA%3D%3D&url_encoded_fmt_stream_map=itag%3D18%26url%3Dhttps%253A%252F%252Fr2---sn-bg0eznlz.c.drive.google.com%252Fvideoplayback%253Fexpire%253D1618175340%2526ei%253DLC1zYNjFDcOM8gStnI64Bg%2526ip%253D45.184.131.85%2526cp%253DQVRGWkJfVFNSQVhPOlp3SExoWl9oYTNKYk56Sm1iU3dGd25LakR1Y1BUM01JNmVUYW5SRDNWZjM%2526id%253D78edbfcf1fc76400%2526itag%253D18%2526source%253Dwebdrive%2526requiressl%253Dyes%2526mh%253DXL%2526mm%253D32%2526mn%253Dsn-bg0eznlz%2526ms%253Dsu%2526mv%253Du%2526mvi%253D2%2526pl%253D24%2526ttl%253Dtransient%2526susc%253Ddr%2526driveid%253D1HCK3eleZSNQfpuZaI_oyIBQ9I_DroTq8%2526app%253Dexplorer%2526mime%253Dvideo%252Fmp4%2526vprv%253D1%2526prv%253D1%2526dur%253D8775.029%2526lmt%253D1612203534601168%2526mt%253D1618160459%2526sparams%253Dexpire%252Cei%252Cip%252Ccp%252Cid%252Citag%252Csource%252Crequiressl%252Cttl%252Csusc%252Cdriveid%252Capp%252Cmime%252Cvprv%252Cprv%252Cdur%252Clmt%2526sig%253DAOq0QJ8wRQIhAPjdubHafwixI9u_3cHc4Qt0sF8092zP3ZNSxPvqHY7nAiApe4jGKLmb4jVA4vqAGa5M-Sv2vPiwCCMFDIjzPvpq-Q%253D%253D%2526lsparams%253Dmh%252Cmm%252Cmn%252Cms%252Cmv%252Cmvi%252Cpl%2526lsig%253DAG3C_xAwRgIhAL9KrFxY09TeS3LW7B6wVmuM6pJTlVNC7B3uqVYHYXiuAiEAv43kEsHHcDK805VYorcU_CSm9_END9gpT_KX7QSZ9PA%253D%26type%3Dvideo%252Fmp4%253B%2Bcodecs%253D%2522avc1.42001E%252C%2Bmp4a.40.2%2522%26quality%3Dmedium%2Citag%3D22%26url%3Dhttps%253A%252F%252Fr2---sn-bg0eznlz.c.drive.google.com%252Fvideoplayback%253Fexpire%253D1618175340%2526ei%253DLC1zYNjFDcOM8gStnI64Bg%2526ip%253D45.184.131.85%2526cp%253DQVRGWkJfVFNSQVhPOlp3SExoWl9oYTNKYk56Sm1iU3dGd25LakR1Y1BUM01JNmVUYW5SRDNWZjM%2526id%253D78edbfcf1fc76400%2526itag%253D22%2526source%253Dwebdrive%2526requiressl%253Dyes%2526mh%253DXL%2526mm%253D32%2526mn%253Dsn-bg0eznlz%2526ms%253Dsu%2526mv%253Du%2526mvi%253D2%2526pl%253D24%2526ttl%253Dtransient%2526susc%253Ddr%2526driveid%253D1HCK3eleZSNQfpuZaI_oyIBQ9I_DroTq8%2526app%253Dexplorer%2526mime%253Dvideo%252Fmp4%2526vprv%253D1%2526prv%253D1%2526dur%253D8775.029%2526lmt%253D1612196404551931%2526mt%253D1618160459%2526sparams%253Dexpire%252Cei%252Cip%252Ccp%252Cid%252Citag%252Csource%252Crequiressl%252Cttl%252Csusc%252Cdriveid%252Capp%252Cmime%252Cvprv%252Cprv%252Cdur%252Clmt%2526sig%253DAOq0QJ8wRAIgJFTtuzFA6Y8D-esOQBFfwIc0N2Sncbo32ERciZ9TaecCIGCvb44U8ejqtdUzc84GmFKT_17DpYj2iWXBROl3n5E2%2526lsparams%253Dmh%252Cmm%252Cmn%252Cms%252Cmv%252Cmvi%252Cpl%2526lsig%253DAG3C_xAwRQIgVeWACgdswVRbGA7KGlPCE1rbEkmbG-J7Qu_frbBTd3ECIQCvqYFUuOZ9quV33O5FsS5duvgynpNG_5IEZDm48i7Uhw%253D%253D%26type%3Dvideo%252Fmp4%253B%2Bcodecs%253D%2522avc1.42001E%252C%2Bmp4a.40.2%2522%26quality%3Dhd720%2Citag%3D37%26url%3Dhttps%253A%252F%252Fr2---sn-bg0eznlz.c.drive.google.com%252Fvideoplayback%253Fexpire%253D1618175340%2526ei%253DLC1zYNjFDcOM8gStnI64Bg%2526ip%253D45.184.131.85%2526cp%253DQVRGWkJfVFNSQVhPOlp3SExoWl9oYTNKYk56Sm1iU3dGd25LakR1Y1BUM01JNmVUYW5SRDNWZjM%2526id%253D78edbfcf1fc76400%2526itag%253D37%2526source%253Dwebdrive%2526requiressl%253Dyes%2526mh%253DXL%2526mm%253D32%2526mn%253Dsn-bg0eznlz%2526ms%253Dsu%2526mv%253Du%2526mvi%253D2%2526pl%253D24%2526ttl%253Dtransient%2526susc%253Ddr%2526driveid%253D1HCK3eleZSNQfpuZaI_oyIBQ9I_DroTq8%2526app%253Dexplorer%2526mime%253Dvideo%252Fmp4%2526vprv%253D1%2526prv%253D1%2526dur%253D8775.029%2526lmt%253D1612265735773933%2526mt%253D1618160459%2526sparams%253Dexpire%252Cei%252Cip%252Ccp%252Cid%252Citag%252Csource%252Crequiressl%252Cttl%252Csusc%252Cdriveid%252Capp%252Cmime%252Cvprv%252Cprv%252Cdur%252Clmt%2526sig%253DAOq0QJ8wRAIgVK9gEt4VVCfclg29yeicdxkjSLBH5GLBaGc2zZ3rFs8CIEAZ-8QHSI3r2a2JI27km7J_6lf1yAF_knmUCfboxC5G%2526lsparams%253Dmh%252Cmm%252Cmn%252Cms%252Cmv%252Cmvi%252Cpl%2526lsig%253DAG3C_xAwRQIhAIMFtRVlbf2oImOUp7CqF_MlH5073S-RvuJ2s3rHqwHPAiBIjnF5UtBKJ73vipMsiqERIQ0kIVFeAq_jFP93gEhnVA%253D%253D%26type%3Dvideo%252Fmp4%253B%2Bcodecs%253D%2522avc1.42001E%252C%2Bmp4a.40.2%2522%26quality%3Dhd1080&timestamp=1618160940245&length_seconds=8774&fmt_list=37%2F1920x1080%2F9%2F0%2F115%2C22%2F1280x720%2F9%2F0%2F115%2C18%2F640x360%2F9%2F0%2F115

if you are using java script below this is a code snippet get the video link with 720 quality if available or whatever is available:
 async function obter_link_video(IdVideo){
      var All_Sizes_Video = {};
      var Returned = await fetch('https://drive.google.com/u/1/get_video_info?docid='+IdVideo);
      Returned = await Returned.text();
      Returned = await Returned.split("&");
      Returned.map((Value) => {
          var Result = Value.split("=");
          All_Sizes_Video[Result[0]] = Result[1];
      });
     if(All_Sizes_Video.status == "ok"){
     var size_array = [];
     var fmt_list = await decodeURIComponent(All_Sizes_Video.fmt_list);
     var fmt_list = fmt_list.split(",");
     var lenght_fmt_list = fmt_list.length-1;
     fmt_list.map((value, index) => {
         var result = value.split("/")[0];
         size_array.push(result);
         size_array.sort((a, b) => a - b);
         var length_size_array = size_array.lenght-1;
         if(index == lenght_fmt_list){
              size_array = lenght_fmt_list == 0 ?  size_array[0] : size_array[1];
         }
     });
     var map_all_links = await decodeURIComponent(All_Sizes_Video.fmt_stream_map);
     map_all_links = map_all_links.split(",");
     map_all_links.map((value) => {
         var select_size_video_by_link = value.split("|")[0] == size_array ? setlink_do_video(value.split("|")[1]) : "wrong";
         setesta_usando_link_absoluto(true);
         console.log(value.split('|')[1]);
    });
    }
  }

and finally the last addendum is that each ip can make a maximum of 2000 requests per day to get information about the video if this value is exceeded you will get an error.


text:
Q: The order() function in R is not giving me the right results I had a dataset I was working with and I wanted to use order to sort values in a df column. But I did not get the right results. I checked format, and it was all numeric.
Then I loaded the mtcars data set built into R and also did not get the right results, i would like to know why that is:


text:
Q: How to get git master back in line with head I am trying to sync a git repo online via bitbucket. I have got in a bit of a tangle with it all, transferring the bitbucket repo to a team, changing the remotes of the repo etc... and now when I try to upload to bitbucket, it says " ! [rejected]        master -> master (non-fast-forward)". I have done git pull, and everything is mergoed ok as far as I can see. I am hoping that if I get my master tag back in line with my HEAD it will all work out again.
This is how it looks in my git client - but I am happy using the command line (which I actually use more often).

A: Being on master, fast forward to the commit that has the HEAD label on it, for example using git merge <commit>. Then push it, git push bucket master.
As it seems that you are currently on a detached HEAD (I guess that's what the HEAD label means), select the HEAD commit in your GUI and write down the hash of that commit. Then you can merge to that one.


text:
Q: Argument of type 'Timestamp' is not iterable? in my code I've generated a range of dates using pd.date_range in an effort to compare it to a column of dates read in from excel using pandas. The generated range of dates is refered to as "all_dates".
all_dates=pd.date_range(start='1998-12-31', end='2020-06-23')

for i, date in enumerate(period):   # where 'Period' is the column of excel dates
        if date==all_dates[i]:        # loop until date from excel doesn't match date from generated dates
            continue
        else:
            missing_dates_stock.append(i)  # keep list of locations where dates are missing
            stock_data.insert(i,"NaN")     # insert 'NaN' where missing date is found

This results in TypeError: argument of type 'Timestamp' is not iterable. How can I make the data types match such that I can iterate and compare them? Apologies as I am not very fluent in Python.

A: I think you are trying to create a NaN row if the date does not exist in the excel file.
Here's a way to do it. You can use the df.merge option.
I am creating df1 to simulate the excel file. It has two columns sale_dt and sale_amt. If the sale_dt does not exist, then we want to create a separate row with NaN in the columns. To ensure we simulate it, I am creating a date range from 1998-12-31 through 2020-06-23 skipping 4 days in between. So we have a dataframe with 4 missing date between each two rows. The solution should create 4 dummy rows with the correct date in ascending order.
import pandas as pd
import random

#create the sales dataframe with missing dates

df1 = pd.DataFrame({'sale_dt':pd.date_range(start='1998-12-31', end='2020-06-23', freq='5D'),
                    'sale_amt':random.sample(range(1, 2000), 1570)
                })

print (df1)

#now create a dataframe with all the dates between '1998-12-31' and '2020-06-23'

df2 = pd.DataFrame({'date':pd.date_range(start='1998-12-31', end='2020-06-23', freq='D')})

print (df2)

#now merge both dataframes with outer join so you get all the rows.
#i am also sorting the data in ascending order so you can see the dates
#also dropping the original sale_dt column and renaming the date column as sale_dt
#then resetting index

df1 = (df1.merge(df2,left_on='sale_dt',right_on='date',how='outer')
          .drop(columns=['sale_dt'])
          .rename(columns={'date':'sale_dt'})
          .sort_values(by='sale_dt')
          .reset_index(drop=True))

print (df1.head(20))

The original dataframe was:
        sale_dt  sale_amt
0    1998-12-31      1988
1    1999-01-05      1746
2    1999-01-10      1395
3    1999-01-15       538
4    1999-01-20      1186
...         ...       ...
1565 2020-06-03       560
1566 2020-06-08       615
1567 2020-06-13       858
1568 2020-06-18       298
1569 2020-06-23      1427

The output of this will be (first 20 rows):
    sale_amt    sale_dt
0     1988.0 1998-12-31
1        NaN 1999-01-01
2        NaN 1999-01-02
3        NaN 1999-01-03
4        NaN 1999-01-04
5     1746.0 1999-01-05
6        NaN 1999-01-06
7        NaN 1999-01-07
8        NaN 1999-01-08
9        NaN 1999-01-09
10    1395.0 1999-01-10
11       NaN 1999-01-11
12       NaN 1999-01-12
13       NaN 1999-01-13
14       NaN 1999-01-14
15     538.0 1999-01-15
16       NaN 1999-01-16
17       NaN 1999-01-17
18       NaN 1999-01-18
19       NaN 1999-01-19


text:
Q: Se pueden agregar datos al Map<>Hashmap estando en otra activity diferente? (Android Studio/Firebase database) He tratado de que la parte de "Image" vaya dentro de cada "User", sin embargo no he tenido exito.

Este es el codigo que usé

//Esto era solo para subir la imagen

            final StorageReference Imagename = mstorage.child("image" + ImageData.getLastPathSegment());

            Imagename.putFile(ImageData).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Imagename.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {

Desde aquí es el código para subir el archivo al Database
                  @Override
                            public void onSuccess(Uri uri) {
                            DatabaseReference imagestore = FirebaseDatabase.getInstance().getReference().child("Image");
                            HashMap<String, String> hashMap = new HashMap<>();
                            hashMap.put("imageurl", String.valueOf(uri));

                            imagestore.setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    Toast.makeText(Pantallaprincipal.this,"Exito", Toast.LENGTH_SHORT).show();
                                }
                            });

                        }
                    });

                }
            });

Todo funciona a la perfección, sin embargo quisiera que la imagen esté dentro de cada usuario para usarla como foto de perfil.

A: Para lograr lo que necesitas, tenes que modificar la referencia.
Si el usuario fue creado por un login con Firebase, deberias usar FirebaseAuth.getInstance().getCurrentUser().getUid(); para obtener esa ID alfanumerica que se encuentra en User, esa es la id del usuario logueado en ese momento.
 DatabaseReference imagestore = FirebaseDatabase.getInstance().getReference().child("User").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Image");

Si no logueaste al usuario , deberias escribir en el segundo child de la referencia el Uid del usuario donde queres guardar la imagen.
Si no queres guardar un nodo Image con imageUrl adentro del usuario, solo guardala adentro del usuario como un atributo mas que seria imageUrl
DatabaseReference imagestore = FirebaseDatabase.getInstance().getReference().child("User").child(FirebaseAuth.getInstance().getCurrentUser().getUid());


text:
Q: Overlayfs: restore removed or changed file from "lower" OpenWrt uses overlayfs
# mount | grep overlay
/dev/ubi0_2 on /overlay type ubifs (rw,noatime)
overlayfs:/overlay on / type overlay (rw,noatime,lowerdir=/,upperdir=/overlay/upper,workdir=/overlay/work)

Somehow real lowerdir is /rom
# mount | grep rom
mtd:ubi_rootfs on /rom type squashfs (ro,relatime)

How to restore file to make it the as in /rom? Remove records from overlays: whiteouts and opaque dirs.
Workaround
cp /rom/path/to/file /overlay/upper/path/to/file

A: Remove file from /overlay/upper, and then remount rootfs.
rm /overlay/upper/my/file
mount -o remount /


text:
Q: Dynamically populate the form based on the value previously selected by getting data from mongodb in express So I am trying to build a online appointment hospital booking website using express and mongodb.
Based on the date selected by the user, the time slots that are available should be displayed from the database dynamically without redirecting.
I tried to get data nad using ajax request but I am not able to display data.
To be honest I don't like this method. If anybody could suggest a better method I would be very happy to adpot it.
booking_appointment.js
let date_selected = document.getElementById("date-selected")
document.getElementById("myCalendar").addEventListener("click", function(e) {
  e.preventDefault();
  axios.post('/time_slots', {text: date_selected.value}).then(function (response) {
    console.log("Success");
  }).catch(function() {
    console.log("Please try again later.");
  })
})

app.js
app.get("/booking",function(req,res){
  res.render("book");
});

app.post("/booking",function(req,res){
//req.body.text will give the selected date value.Based on this value time slots should be displayed from DB.
  console.log(req.body.text);
});

app.post("/time_slots",function(req,res){
  let date=req.body.text;
  items=Slots.find_by(date: date).then((slots,err)=>{
    res.render("book",{slots:slots});
  }).catch(err=>   req.flash('error',"Something went wrong!Try again!"))
});

app.post("/booking",function(req,res){
  console.log("hurray");
  res.render("home");
});

book.ejs
<form action="/booking" method="post" >
<Assume there is a calendar here from which we will get date id='myCalendar'>

<%= (typeof slots != "undefined" ? slots : "okay i need to figure it out") %>

</form>

Can u please tell me how to populate time slots dynamically, thanks in advance.

A: app.js
app.post("/time_slots",function(req,res){
  let date=req.body.text;
  items=User.find().then((slots,err)=>{
    let data=JSON.stringify(slots);
   return res.json({slots: data})
  }).catch(err=>   req.flash('error',"Something went wrong!Try again!"))
});

booking_appointment.js

let Pname = document.getElementById("Pname")
document.getElementById("myCalendar").addEventListener("click", function(e) {
   //wwe dont the default action to performed after submitting the form. we want to send an asnychoronous request to server
  e.preventDefault();
  alert(e);

  axios.post('/time_slots', {text: Pname.value}).then(function (response) {
    // Create the HTML for a new item
    var $section = $('

');
  (JSON.parse(response.data.slots)).forEach(function(slot) {
    $section.append(`<h1>${slot.name}</h1>`);
  });
  $('#myCalendar').html($section);
    }).catch(function(e) {
    console.log(e);
    console.log("Please try again later.");
  })
})

book.ejs
<form action="/booking" method="post" >
<Assume there is a calendar here from which we will get date id='myCalendar'>
</form>


text: Q: Algoritmo de Planificación Round Robin Buenas a todos, tratare de ser lo mas breve posible, busco ayuda para codificar el algoritmo de planificación de procesos "Round Robin (RR)", no se como empezar o que debo de utilizar para este tipo de programa. Busco que el programa haga esto: el usuario debe introducir el tiempo de ejecución de cada proceso y el programa calculara el promedio de los tiempos de ejecución de todos los procesos que el usuario introdujo, lo cual vendría siendo el Quantum, y después comenzar con lo que el algoritmo indica. Espero y alguien pueda ayudarme. De antemano gracias.


text:
Q: adding CSS to rails form helper I would like to add a css class to a rails form helper. The css class is intended to be used in a div around the input tag, though. That's why no style is applied to the slider, I guess.
Original syntax inside form:

          <input type="range" data-init="auto" id="slider3" min="0" max="100" value="<%= @subproject_value1 %>" step="1">
          <output for="slider3">0</output>

markup
Rails form helper inside form tag:
<%= range_field(:subproject, :ans1, in: 1..100, :class => "range range--light") %>

form helper
EDIT:
added images

A: If you need that div around the input, then you can simply mark it up in your template and have the actual form helper within it:

    <%= range_field(:subproject, :ans1, in: 1..100, id: 'slider3'%>
    <output for="slider3">0</output>

A: I just had to add :'data-init' => 'auto' to the range_field tag


text:
Q: Continuous Rainbow color cycling effect in js Just started learning JS and want to know how to create an effect in which VIBGYOR color keeps on cycling continuously using JS.
Here is my attempt https://jsfiddle.net/2t1kbm8u/.
const scheme = document.querySelector("div");
const rainbow = [
  "#9400D3",
  "#4B0082",
  "#0000FF",
  "#00FF00",
  "#FFFF00",
  "#FF7F00",
  "#FF0000",
];

setInterval(() => {
  for(let colors = 0; colors < rainbow.length; colors++) {
    scheme.style.color = `${rainbow[colors]}`;
    scheme.style.borderColor = `${rainbow[colors]}`;
    console.log(rainbow[colors]);
  }
}, 1000);

Though all colors are being consoled but only the first and last colors are visible

A:    const scheme = document.querySelector("div");
  const rainbow = [
    "#9400D3",
    "#4B0082",
    "#0000FF",
    "#00FF00",
    "#FFFF00",
    "#FF7F00",
    "#FF0000",
  ];
  var currentColor = 0;
  setInterval(() => {
    scheme.style.color = `${rainbow[currentColor]}`;
    scheme.style.borderColor = `${rainbow[currentColor]}`;
    currentColor++;
    if (currentColor == rainbow.length-1) {
    currentColor = 0;
    }
  }, 1000);


text:
Q: ¿Como hago para usar un evento dentro de una "clase" javascript, desde el mouseup de un contenedor?         function MakeDrawable(containerID){
            this.container = (document.getElementById(containerID) || document.body);
            this.onCreateElement = null;//Evento externo
            this.container.onmouseup = function(e){
                e.preventDefault();
                var hash = {Nombre:"Hola", Apellido: "Mundo"};
                //Quiero llamar a mi evento externo
                this.onCreateElement(hash);
            }
        }
        //Implementacion

        var drawableContainer = new MakeDrawable("qa");
        drawableContainer.onCreateElement = function(hash){
            alert(JSON.stringify(hash));
        };

¡De antemano muchas gracias por su tiempo!
La pregunta del titulo se que es medio confusa, pero el código explica bien mi duda.
Mi idea con esto es, realizar la implementación y usar el evento bindeandole una función creada por mi, que ésta reciba un argumento.
La cosa es que no me está funcionando, no se como accesar desde el mouseup del contenedor al evento onCreateElement que tengo en mi clase MakeDrawable, manteniendo el hilo de ejecucion de cada new que haga sobre la clase.
Muchas gracias!
Edit: Ignorar los punto y coma o llaves ya que el código lo recorté para tener el caso especifico. Me interesa la parte del llamado.

A: No es posible hacerlo de la manera que quieres.
Por ejemplo en el método de onmouseup, cuando quieres enviar el hash a onCreateElement el this en ese momento no es el de la clase y por eso te salta un error. El ambito de this en este método cambia.
Mira lo que yo hice con tu código.
function MakeDrawable(containerID){
        let self = this;
        this.container = (document.getElementById(containerID) || document.body);
        this.onCreateElement = function(hash) {
            alert(JSON.stringify(hash))
        };//Evento externo
        this.container.onmouseup = function(e){
            e.preventDefault();
            var hash = {Nombre:"Hola", Apellido: "Mundo"};
            //Quiero llamar a mi evento externo
            self.onCreateElement(hash);
        }
    }
    //Implementacion

    var drawableContainer = new MakeDrawable("qa");

Capture el this de la clase en la variable self para poder refenciar this en el método onmouseup.
Espero haberte ayudado.

A: Buenas noches respondiendo mi propia pregunta, dejo un código de ejemplo donde instancio clases Javascript y puedo hacer un call a los eventos asignados desde afuera.
Saludos y espero que les sirva!
<!DOCTYPE html>

        Test


text:
Q: How do I make the background image cover the div, and not the body? I am trying to make the background image be positioned to the bottom left of a div and cover the entire div, without distorting it's ratio.
Whenever I use
background:url("img.jpg") no-repeat left bottom fixed;

it goes to the left of the body and the bottom of the body, not the div. How do I get it to use the div as the frame of reference and not the body?
Fiddle below
http://jsfiddle.net/UFpYd/3/

A: How about this:
background: url('img.jpg') no-repeat scroll center top/cover transparent;

EDIT:-
After watching your JSFiddle you may try this:
background: url('img.jpg') no-repeat left bottom;

JSFIDDLE

A: Not sure if you are looking for this:
background: url('img.jpg') no-repeat left bottom;

or this:
background: url('img.jpg') no-repeat left bottom fixed;

Clarification: Your fiddle you posted uses center top for background image positioning. It should work as you expect if you use left bottom (whether fixed or not will depend on how you want your image positioned).


text:
Q: Export Dictionary with Both Simple Values and Nested Dictionaries to CSV I'm accessing a third-party API that returns a dictionary that contains both simple values and nested (embedded?) dictionaries. I need to convert this to a CSV file, but I need help extracting and exporting specific values from the nested dictionaries.
Here's a simplified example of what I'm getting back:
accounts = {
    'Id': '0131232',
    'AccountName': 'CompanyX',
    'Active': False,
    'LastModifiedBy': {'type': 'User', 'Id': '', 'Name': 'Joe Smith'}
},
{
    'Id': '987654',
    'AccountName': 'CompanyY',
    'Active': True,
    'LastModifiedBy': {'type': 'User', 'Id': '', 'Name': 'Mary Johnson'}
}

I'm trying to export this to a CSV file with the following code:
with open('output.csv', 'w') as f:
    dwriter = csv.DictWriter(f, accounts[0].keys())
    dwriter.writeheader()
    dwriter.writerows(accounts)

f.close()

What I want in the CSV file is the following:
Id,AccountName,Active,LastModifiedBy
0131232,CompanyX,False,Joe Smith
987654,CompanyY,True,Mary Johnson

What I'm getting with my code above is the following:
Id,AccountName,Active,LastModifiedBy
0131232,CompanyX,False,"{'type': 'User', 'Id': '', 'Name': 'Joe Smith'}"
987654,CompanyY,True,"{'type': 'User', 'Id': '', 'Name': 'Mary Johnson'}"

Obviously I need to extract the key-value pair I want from the nested dictionary and assign that value to the higher-level dictionary. My question is how do I do that while still handling the simple values as is?
It seems like this could be done with dictionary comprehension, but I'm not sure I can do a conditional with that.
Alternatively I could go through each record, check each value to see if it's a dictionary, and write out the values I want to a new dictionary, but that feels a little too heavy.
Full disclosure: I'm new to Python, so apologies if I'm missing something obvious.
Thanks!
- Chris

A: If you don't need accounts for anything else you can do:
for account in accounts:
    account['LastModifiedBy'] = account['LastModifiedBy']['Name']

otherwise, .copy() it and do the same.


text:
Q: Javascript every() display different value when doing a return and console.log() I'm trying to solve a simple algorithm where you evaluate that every number in an array is greater than the next one, so I first taught in the Every() method, but when I do a return is always false, but when I console.log() it display true!
How is this possible?
const arr = [3, 2, 1];

const returnRes = arr.every((value, index, arr) => value > arr[index + 1]);

const consoleLogRes = arr.every((value, index, arr) => console.log(value > arr[index + 1]));

console.log(returnRes);

Evidence

A: At the third iteration. The value  arr[index + 1] will be undefine. why? it because the value of  arr[index + 1] will be arr(2+1) which is arr[3] and arr[3] does not exist because index start from zero not 1. what you can do is to add a check at the last iteration to prevent the undefine from happening. check the code below
const arr = [3, 2, 1];

const response = arr.every((value, index, arr) => {

  if (index + 1 === arr.length) {
    return true;
  }
  return value > arr[index + 1];
});

console.log(response);

A: The issue is when your value is 1 and index is 2, that is, when the every function processes the last element of your array, arr[index + 1] returns undefined and 1 > undefined evaluates to false.
To properly fix it, you should return true when index is pointing to the last element:

const arr = [3, 2, 1];

const returnRes = arr.every((value, index, arr) =>
  index === arr.length - 1 || value > arr[index + 1]);

console.log(returnRes);


text:
Q: What does the selector syntax mean in $( "" ).text( message ) What does the selector
 syntax mean in this code?  I've seen selectors like div or #someId but I'm confused what the
 means
    function log( message ) {
        $( "
" ).text( message ).prependTo( "#log" );
        $( "#log" ).scrollTop( 0 );
    }

A: It means "create a jQuery-wrapped div element on the fly".
See http://api.jquery.com/jQuery/
From the above:

jQuery( html [, ownerDocument] )
Description: Creates DOM elements on the fly from the provided string
  of raw HTML.

Later...

When the parameter has a single tag, such as $('') or
  $(''), jQuery creates the element using the native JavaScript
  createElement() function.

So basically, it's like doing:
$(document.createElement("div")).text("blahblah");

A: It will create a new
 element and prepend it to the #log element.

A: It creates a new div tag and prepends it to log.

A: It means that the jquery function will not actually query for DIV elements but will create an jquery wrapped element of type

 on which you can work on and append to the DOM eventually.
In your case, the code will create jquery object representing a DIV element, set its innerText to what the message variable contains and prepend it to the element with ID "log".

A: $('
') will not select a div from your html, but create a new one. Also it can be written like $('

'), first one is just a shorthand for second.

A:
 indicates that the div is a self closing div. It's basically shorthand for $('

').
Any browser that supports XHTML supports the self-closing syntax on all elements.


text:
Q: Animation in matplotlib with scatter and using set_offsets: How to update color of scatter point I am trying to create an animation that plots GPS data from a run. I have code that plots the points and creates the animation. In order to have the old point deleted and the new plotted with each frame I am using scat.set_offsets(x[i],y[i]) to plot the points. The trouble I am running into is that I want the color of the point to reflect the speed at that position. The code below works but I cannot figure out the color updating. I have tried using scat.alpha() but it switches the color once and never updates again. I want to use, jet, for example, and have 0 mph be blue and the fastest time to be red.
The running log has the first two columns as lon/lat and the third is velocity. Some data:
 Longitude   Latitude   GPS Speed(km/h)

-88.19895578    43.19975045 0

-88.19894667    43.19976286 0

-88.19893236    43.19977277 0

-88.19872605    43.19969481 9.9

-88.19871956    43.19967161 10.799999

-88.19872339    43.19962663 11.7

-88.19873801    43.19959561 11.7

-88.19879232    43.19958254 9.9

-88.19876674    43.1995382  9.9

-88.19876797    43.19948614 7.2

The code is below. Thanks for the help!
"""
Matplotlib Animation of Accelerometer Vectors

author: Ryan Croke
website: http://TheHolyMath.com
"""

import numpy as np
import networkx as nx
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib  import cm
import csv
import json
import smopy
import re

### DATA ###
# Read shape file
g = nx.read_shp("tl_2014_us_state/tl_2014_us_state.shp")

# plot points of acceleration and deceleration
f = open('runninglog.csv')
cr = csv.reader(f)

# Make arrays for processing
latitude = []
longitude = []
velocity = []

# Velocity is in m/s - convert to miles/hour
# 1m/s = 2.236 mph
for row in cr:
    # Need to test for headers - pass anything with letters
    if any(c.isalpha() for c in row[0]) == True:
        pass
    else:
        longitude.append(float(row[0]))

    if any(c.isalpha() for c in row[1]) == True:
        pass
    else:
        latitude.append(float(row[1]))

    if any(c.isalpha() for c in row[2]) == True:
        pass
    else:
        velocity.append(round(float(row[2])*2.236,2))

# Numer of plots
P = int(len(latitude))

# In the USA longitude is decreasing from west to east, latitude is increasing from south to north
# lower left will be max(lon) and min(lat)
pos1 = (float(min(latitude)),float(max(longitude)))
pos2 = (float(max(latitude)),float(min(longitude)))

### Animation ###
# First set up the figure, the axis, and the plot element we want to animate
map = smopy.Map(pos1, pos2, z=15)
# Smoopy allows you to create a matplotlib image using a t0_pixels command
x = []
y = []

# Create array's for lat/lon in pixel image
for i in xrange(len(latitude)):
    x1, y1 = map.to_pixels(latitude[i],longitude[i])
    x.append(x1)
    y.append(y1)

# animation of a scatter plot using x, y from above
#------------------------------------------------------------------------------

fig = plt.figure()
ax = map.show_mpl(figsize=(8, 6))
scat = ax.scatter([],[],s=60)

# initialization function: plot the background of each frame
def init():
    scat.set_offsets([])
    #scat.set_facecolor([])
    return scat,

# animation function.  This is called sequentially
def animate(i):
    scat.set_offsets([x[i], y[i]])
    #scat.set_edgecolors('red')
    #scat.set_facecolor()

    return scat,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=P, interval=40, repeat=False, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('Around_the_block_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()


text:
Q: How to access newly added Contact in Sync Adapter onPerformSync method? When I add a contact to my phone book, the sync Adapter onPerformSync() method gets triggered. But I am not able to figure out how to retrieve the newly added Contact details within that method. Please help me with some guidance and code snippets. Appreciate your help.

A: The contacts of your account are stored in the RawContacts table. The data (e.g. phone numbers, email addresses) is stored in the Data table (with RAW_CONTACT_ID pointing to the row _ID of that contact in the RawContacts table).
To detect new contacts, your sync adapter needs to maintain the SOURCE_ID field in the RawContacts table.
The documentation says about SOURCE_ID (in the columns of fields on top):

String that uniquely identifies this row to its source account. Typically it is set at the time the raw contact is inserted and never changed afterwards. The one notable exception is a new raw contact: it will have an account name and type (and possibly a data set), but no source id. This indicates to the sync adapter that a new contact needs to be created server-side and its ID stored in the corresponding SOURCE_ID field on the phone.

So your sync adapter should look for contacts that belong to your account type and have an empty SOURCE_ID. After the contact has been synced it must set the SOURCE_ID to a (non-empty) value that identifies the new contact.
When you sync a new contact from the server you need to set the SOURCE_ID when inserting the new contact on Android. Failure to do so, will result in duplicates (since the contact would be synced back to the server as a new contact on the next sync).


text:
Q: XML to CSV: Print lines for each child node and sometimes child node is missing I need the XML below converted to csv. This was tricky for two reasons: 1) There are multiple Support_Order_Detail child elements and a separate line is needed for each child 2) There are no Support_Order_Detail child elements in the second record. I used preceding-sibling matching on Support_Order_Detail and used the not[] function to handle the record without Support_Order_Detail node. I've included the XSLT that I've struggled with and it does work. I get the correct output. However, I know there is a better way and I do get an error in my debugger:
Ambiguous rule match for /Report_Data/Report_Entry[2]
Matches both "Report_Data/Report_Entry[not(Support_Order_Detail)]"
and "Report_Data/Report_Entry"
I'm hoping to learn if anyone can suggest where I would not have duplicate code, i.e. two templates. I'd like to get rid of the one using the not[] function.
Doe,Jane,Child Support,Mandatory,12345
Doe,Jane,Child Support,Mandatory,12345
Dole,Bob,Student Loan,Federal,56789

.
    <Report_Data>
      <Report_Entry>
          <Worker>
              <Last_Name>Doe</Last_Name>
              <First_Name>Jane</First_Name>
          </Worker>
          <Lien_Type>Support Order</Lien_Type>
          <Lien_Sub_Type>Mandatory</Lien_Sub_Type>
          <Support_Order_Detail>
              <Support_Type Descriptor="Current Child Support">
                  <ID type="Support_Type">CS</ID>
              </Support_Type>
          </Support_Order_Detail>
          <Support_Order_Detail>
              <Support_Type Descriptor="Past Due Child Support">
                  <ID type="Support_Type">PDCS</ID>
              </Support_Type>
          </Support_Order_Detail>
          <Case_ID>12345</Case_ID>
      </Report_Entry>
      <Report_Entry>
          <Worker>
              <Last_Name>Dole</Last_Name>
              <First_Name>Bob</First_Name>
          </Worker>
          <Lien_Type>Student Loan</Lien_Type>
          <Lien_Sub_Type>Federal</Lien_Sub_Type>
          <Case_ID>56789</wd:Case_ID>
      </Report_Entry>
    </Report_Data>

XSLT:
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:xs="http://www.w3.org/2001/XMLSchema"
     exclude-result-prefixes="xs"
     xmlns:xtt="urn:com.workday/xtt"
     version="2.0">

    <xsl:template match="/">
        <File xtt:separator="
">
            <xtt:class xtt:name="dateformat" xtt:dateFormat="dd/MM/yyyy"/>
            <xsl:apply-templates/>
        </File>
    </xsl:template>

    <xsl:template match="Report_Data/Report_Entry">
        <xsl:apply-templates select="Support_Order_Detail"/>
    </xsl:template>

    <xsl:template match="Support_Order_Detail" >
        <Record xtt:separator=",">
            <LastName xtt:maxLength="14"><xsl:value-of select="preceding-sibling::Worker/Last_Name[1]"/></LastName>
            <FirstName xtt:maxLength="17"><xsl:value-of select="preceding-sibling::Worker/First_Name[1]"/></FirstName>
            <LienType>
            <xsl:choose>
                <xsl:when test="preceding-sibling::Lien_Type[1] = 'Support Order' and Support_Type/@Descriptor = 'Current Child Support'">
                    <xsl:text>Child Support</xsl:text>
                </xsl:when>
                <xsl:when test="preceding-sibling::Lien_Type[1] = 'Support Order' and Support_Type/@Descriptor = 'Past Due Child Support'">
                    <xsl:text>Child Support</xsl:text>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="Support_Type/@Descriptor"/>
                </xsl:otherwise>
            </xsl:choose>
            </LienType>
            <LienSubType><xsl:value-of select="preceding-sibling::Lien_Sub_Type[1]"/></LienSubType>
            <CaseID xtt:maxLength="20"><xsl:value-of select="following-sibling::Case_ID"/></CaseID>
        </Record>
    </xsl:template>

    <xsl:template match="Report_Data/Report_Entry[not(Support_Order_Detail)]" >
        <Record xtt:separator=",">
            <LastName xtt:maxLength="14"><xsl:value-of select="Worker/Last_Name"/></LastName>
            <FirstName xtt:maxLength="17"><xsl:value-of select="Worker/First_Name"/></FirstName>
            <LienType><xsl:value-of select="Lien_Type"/></LienType>
            <LienSubType><xsl:value-of select="Lien_Sub_Type"/></LienSubType>
            <CaseID xtt:maxLength="20"><xsl:value-of select="Case_ID"/></CaseID>
        </Record>
    </xsl:template>

</xsl:stylesheet>

Expected XML results:
    <Record xtt:separator=",">
        <LastName xtt:maxLength="14">Doe</LastName>
        <FirstName xtt:maxLength="17">Jane</FirstName>
        <LienType>Child Support</LienType>
        <LienSubType>Mandatory</LienSubType>
        <CaseID xtt:maxLength="20">12345</CaseID>
    </Record>
    <Record xtt:separator=",">
        <LastName xtt:maxLength="14">Doe</LastName>
        <FirstName xtt:maxLength="17">Jane</FirstName>
        <LienType>Child Support</LienType>
        <LienSubType>Mandatory</LienSubType>
        <CaseID xtt:maxLength="20">12345</CaseID>
    </Record>
    <Record xtt:separator=",">
        <LastName xtt:maxLength="14">Dole</LastName>
        <FirstName xtt:maxLength="17">Bob</FirstName>
        <LienType>Student Loan</LienType>
        <LienSubType>Federal</LienSubType>
        <CaseID xtt:maxLength="20">56789</CaseID>
    </Record>

A: So I don't know about whatever extension or tool you're using, but doing this in pure XSLT is pretty straightforward; match all the Report_Entry elements, and if they have any Support_Order_Detail elements loop through all of them except the last() one (because we've already generated a line for that):
(I've slightly modified this to use a variable instead of the duplicative selects)
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="text" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />

    <xsl:template match="//Report_Entry">
        <xsl:variable name="row">
            <xsl:value-of select="Worker/Last_Name" />,<xsl:value-of select="Worker/First_Name" />,<xsl:value-of select="Lien_Type"/><xsl:value-of select="Lien_Sub_Type"/>,<xsl:value-of select="Case_ID"/>
            <xsl:text>
</xsl:text>
        </xsl:variable>

        <xsl:value-of select="$row" />

        <xsl:for-each select="Support_Order_Detail[position() != last()]">
            <xsl:value-of select="$row" />
        </xsl:for-each>
    </xsl:template>

    <xsl:template match="text()"/>

</xsl:transform>

http://xsltransform.net/bFN1y9B/1

A:
I do get an error in my debugger:
Ambiguous rule match for /Report_Data/Report_Entry[2] Matches both
  "Report_Data/Report_Entry[not(Support_Order_Detail)]" and
  "Report_Data/Report_Entry"

The error can be eliminated if you change:
<xsl:template match="Report_Data/Report_Entry">

to:
<xsl:template match="Report_Entry">

Similarly, you can replace:
<xsl:template match="Report_Data/Report_Entry[not(Support_Order_Detail)]" >

with:
<xsl:template match="Report_Entry[not(Support_Order_Detail)]" >

A match pattern is not a select expression: it does not need to include a path, unless the pattern is ambiguous without it (e.g. if you have Report_Entry at different places or levels and need to treat them differently.

As for "better" code to achieve the same result, this is largely a matter of personal preference. IMHO, if you have two types of Report_Entry and each one needs to be handled differently, having separate template to handle them is the best approach, unless the difference is minimal (not your case).
I would look into simplifying the xsl:choose block, though.


text:
Q: log4j : How to avoid prefix value in log file? I am using log4j in our application to log our customer activities into the log files,
in log file I am getting prefix value as "INFO - ", How can I avoid this prefix value in
my log file?
My log4jconf.xml is
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
    <param name="Threshold" value="INFO"/>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d
         %-5p  [%c{1}] %m %n"/>
    </layout>
</appender>
<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
    <param name="Threshold" value="INFO"/>
    <param name="File" value="sample.log"/>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d
            %-5p  [%c{1}] %m %n"/>
    </layout>
</appender>
<logger name="CPI810_RCM_LOGGER" additivity="false">
    <level value="INFO"/>
    <appender-ref ref="consoleAppender"/>
</logger>
  </log4j:configuration>

Sample Entry like as following
   INFO - loginId|correlationId|status|firstName|middleName|lastName|resourceRole|access
   INFO - loginId|correlationId|status|firstName|middleName|lastName|resourceRole|access
   INFO - loginId|correlationId|status|firstName|middleName|lastName|resourceRole|access

Code :
cat = Category.getInstance(catname);
    PatternLayout layout = null;
    FileAppender appender =  null;
    try {
        cat = Category.getInstance(catname);
        layout = new PatternLayout("%m %n");

        appender = new FileAppender(layout,fileAppender,true);
        cat.addAppender(appender);

    } catch (Exception e) {
        // TODO: handle exception
    }

A: This is due to the "ConversionPattern" parameter of the appender's layout: the %-5p token instructs log4j to rpint the logging level (INFO in your case) on a minimum of 5 characters, padded with spaces. Thus, if you remove the %-5p from the conversion pattern, you won't see the INFO in your log entries.
This being said, I don't see where the - (dash) comes from. Are you sure that the log entries you showed are really the ones you have in your log file? For instance the [%c{1}] part of the pattern should cause log4j to print the class name between square braces, but I don't see that here.


text:
Q: How to convert Unix timestamp( 1541107867006) to required date time format in SAP HANA Scripted Calculation View After a good research and failing to get the required solution, I am posting the question here.
Problem: Unable to convert timestamp '1541107867006' to required date time format in SAP Scripted Calculation View.
Tried the below code and SAP functions but they work for other formats and not this specifically.
SELECT TO_TIMESTAMP (ADD_SECONDS( '1970-01-01 00:00:00', '1541107867006')) TIMESTAMP,
       TO_DATE (ADD_SECONDS( '1970-01-01 00:00:00', '1541107867006')) DATE,
       TO_TIME (ADD_SECONDS( '1970-01-01 00:00:00', '1541107867006')) TIME
from DUMMY

Can you please help with this? Really appreciate your response!
Thanks
Supriya

A: This worked for me.
TO_CHAR(ADD_SECONDS(TO_TIMESTAMP('1970-01-01 00:00:00'), cast('1541107867006' as bigint)/1000),'mm/dd/yyyy')

A: The constant '1541107867006' is not in seconds, but in milliseconds.
Try
SELECT ADD_SECONDS(TO_TIMESTAMP('1970-01-01 00:00:00'),
    cast('1541107867006' as bigint)/1000) as "Timestamp"
from DUMMY;

or, because some casts are implicit:
SELECT ADD_SECONDS('1970-01-01 00:00:00',
    cast('1541107867006' as bigint)/1000) as "Timestamp"
from DUMMY;

It's easier when the (numeric) Unix timestamp is given as a BIGINT right away:
SELECT ADD_SECONDS('1970-01-01 00:00:00', 1541107867006 / 1000) as "TimeStamp"
from DUMMY;


text:
Q: Does Opera Mini proxy filter CSS-hidden elements? I have to provide a responsive website targeting Opera Mini devices. I have to make the page's size as small as possible. As Opera Mini uses a proxy to compress page's size, I was wondering if Opera Mini does load hidden elements (like pictures) on the client device if the elements are specified as follows:
<img style="display:none" source="..."/>

A: Opera Turbo does compress images to decrease overall page size. But it does not remove any markup from the code. Furthermore, the compression mechanism can be disabled in the settings (at least in Opera Mobile).


text:
Q: No puedo quitar duplicados en BigQuery Necesito que la consulta de BigQuery me traiga los registros de la ultima vez que se proceso sin que me traiga todas las veces que se proceso.
Probe con 'Select Max() From Table' pero me sigue trayendo todos los registros anteriores.
¿Alguien que me pueda ayudar?


text:
Q: Rows in Column don't space its children Flutter I have a widget that has a Column with 2 expanded children, flexes are 2 and 1.
second children is another column with 3 Row children each with two text.
The mainAxisAlignment: MainAxisAlignment.spaceBetween in each Row should push the two children texts to the margins but they are staying centered with no space in the middle.
Can you see why there is no space between them?
This is the Widget:

class DisplayCell extends StatelessWidget {
  final AutoSizeGroup autoSizeGroup;
  final String imageUrl;
  final String name;
  final String price;
  final String vendor;
  final Function onTap;

  const DisplayCell(
      {Key key,
      this.autoSizeGroup,
      this.imageUrl,
      this.name,
      this.price,
      this.vendor,
      this.onTap})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.transparent,
      padding: EdgeInsets.all(5),
      child: Container(
        padding: EdgeInsets.all(10),
        decoration: BoxDecoration(
          color: Colors.black.withAlpha(120),
          borderRadius: BorderRadius.circular(5),
          border: Border.all(color: Colors.redAccent, width: 1),
        ),
        child: Column(
//          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Expanded(
              flex: 2,
              child: Image(
                image: NetworkImage(imageUrl),
              ),
            ),
            Expanded(
              flex: 1,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    mainAxisSize: MainAxisSize.max,
                    children: <Widget>[
                      AutoSizeText(
                        AppLocalizations.instance.text('Name:'),
                        style: TextStyle(color: Colors.white, fontSize: 12),
                        minFontSize: 8,
                        maxLines: 1,
                        group: autoSizeGroup,
                      ),
//                      SizedBox(
//                        width: 10,
//                      ),
                      AutoSizeText(
                        name,
                        style: TextStyle(color: Colors.white, fontSize: 12),
                        minFontSize: 8,
                        maxLines: 1,
                        group: autoSizeGroup,
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    mainAxisSize: MainAxisSize.max,
                    children: <Widget>[
                      AutoSizeText(
                        AppLocalizations.instance.text('Price:'),
                        style: TextStyle(color: Colors.white, fontSize: 12),
                        minFontSize: 8,
                        maxLines: 1,
                        group: autoSizeGroup,
                      ),
//                      SizedBox(
//                        width: 10,
//                      ),
                      AutoSizeText(
                        price,
                        style: TextStyle(color: Colors.white, fontSize: 12),
                        minFontSize: 8,
                        maxLines: 1,
                        group: autoSizeGroup,
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    mainAxisSize: MainAxisSize.max,
                    children: <Widget>[
                      AutoSizeText(
                        AppLocalizations.instance.text('Vendor:'),
                        style: TextStyle(color: Colors.white, fontSize: 12),
                        minFontSize: 8,
                        maxLines: 1,
                        group: autoSizeGroup,
                      ),
//                      SizedBox(
//                        width: 10,
//                      ),
                      AutoSizeText(
                        vendor,
                        style: TextStyle(color: Colors.white, fontSize: 12),
                        minFontSize: 8,
                        maxLines: 1,
                        group: autoSizeGroup,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}


text:
Q: Smack 4.2 and CCS (XMPP to FCM/GCM) - response incorrectly parsed by Smack - drops JSON payload Version 4.2 of the Smack library seems to drop the message body, as sent by FCM.
When I set the debugger on, I can see the following incoming message:
<message><data:gcm xmlns:data="google:mobile:data">{"message_type":"nack","from":"xxx","message_id":"aaaa1","error":"BAD_REGISTRATION","error_description":""}</data:gcm></message>

However, when Smack 4.2 parses this message, it drops the JSON body inside the message and gives me the following in my packet listener:
<message><gcm xmlns="google:mobile:data"></gcm></message>

Here's my test class:
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.DefaultPacketExtension;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import javax.net.ssl.SSLSocketFactory;

public class CcsClient {

    private static final String HOST = "fcm-xmpp.googleapis.com";
    private static final int PORT = 5235;
    private final XMPPConnection conn;

    public CcsClient(String senderId, String serverKey) {
        SASLAuthentication.supportSASLMechanism("PLAIN", 0);

        ConnectionConfiguration conf = new ConnectionConfiguration(HOST, PORT);
        conf.setSASLAuthenticationEnabled(true);
        conf.setSocketFactory(SSLSocketFactory.getDefault());
        conf.setServiceName(HOST);
        conf.setSendPresence(false);
        conf.setCompressionEnabled(false);
        conf.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        conf.setDebuggerEnabled(true);

        this.conn = new XMPPConnection(conf);

        conn.addConnectionListener(new AbstractConnectionListener() {
            @Override
            public void connectionClosed() {
                super.connectionClosed();
            }

            @Override
            public void connectionClosedOnError(Exception e) {
                super.connectionClosedOnError(e);
            }

            @Override
            public void reconnectingIn(int seconds) {
                super.reconnectingIn(seconds);
            }

            @Override
            public void reconnectionFailed(Exception e) {
                super.reconnectionFailed(e);
            }

            @Override
            public void reconnectionSuccessful() {
                super.reconnectionSuccessful();
            }
        });

        try {
            conn.connect();
            conn.login(senderId + "@gcm.googleapis.com", serverKey);
            System.out.println("connected!");
        } catch (XMPPException e) {
            e.printStackTrace();
        }
    }

    private static final class GcmPacketExtension extends DefaultPacketExtension {

        private final String json;

        public GcmPacketExtension(String json) {
            super("gcm", "google:mobile:data");
            this.json = json;
        }

        public String getJson() {
            return json;
        }

        @Override
        public String toXML() {
            return "<gcm xmlns=\"google:mobile:data\">" + StringUtils.escapeForXML(json) + "</gcm>";
        }

        public Message toPacket() {
            Message message = new Message();
            message.addExtension(this);
            return message;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final CcsClient c = new CcsClient("xxx", "xxx");
        c.conn.addPacketListener(new PacketListener() {

            @Override
            public void processPacket(Packet packet) {
                System.out.println("incoming!" + packet.toString());
            }
        }, new PacketFilter() {
            @Override
            public boolean accept(Packet packet) {
                return true;
            }
        });

        for (int i = 0; i < 1; i++) {
            c.conn.sendPacket(new GcmPacketExtension("{\"to\":\"xxx\", \"message_id\":\"aaaa"+i+"\", \"delivery_receipt_requested\":true}").toPacket());
        }
        Thread.sleep(1000000);
    }
}

What am I doing wrong?

A: So I finally got it working. An example client is here: https://gist.github.com/judepereira/fd8dc0a5321179b699f5c5e54812770c


text:
Q: How do I access/create topics on firebase pubsub emulator? I've added/setup the firebase pubsub emulator that is running on my localhost on port 8085. Up till this point I had need to use the pubsub in Googel cloud, where I would use their console to create topics and could also review messages published to those topics.
Now that it's running locally, there doesn't seem to be a UI to manage topics/messages and I can't seem to find documentation that explains how to create a topic on the local pubsub, how to review existing topics and how to review messages?
In addition, if I am writing a cloud function that references the pubsub library, will it automatically use my local emulator version if it's running or do I need to specify the host/port in my node.js function someplace? Any examples of this out there?
I believe their is an http API I Can use to create topics,but again, I can't find any documentation on this or find references to see what topics exist and what messages have been sent to the topics.
Any help is appreciated.

A: In order to connect your app to the local emulator you must set some environment variables like explained here
About the UI of the emulator you can access it on http://localhost:4000 like this documentation page mentions, although I am not sure if there are management tools to manage topics or messages in there.