text:
Q: Hive: filter a table using another table I am very new to hive and sql and I have a question about how I would go about the following:
I have table A:
Name    id

Amy     1
Bob     4
Josh    9
Sam     6

And I want to filter it using values from another table (table B):
Value  id

.2     4
.7     6

To get a new table that looks like table A but only contains rows with values in the id column that also appeared in the id column of table B:
Name    id

Bob     4
Sam     6

So I'm assuming I would write something that started like...
CREATE TABLE Table C AS
SELECT * FROM Table A
WHERE id....

A: just join it..
hive> CREATE TABLE TableC AS
    > SELECT A.* FROM TableA as A,
    > TableB as B
    > WHERE A.id = B.id;

hive> SELECT * FROM TableC;
OK
Bob 4
Sam 6

or try this,
hive> CREATE TABLE TableD AS
    > SELECT A.* FROM TableA as A join
    > TableB as B
    > on A.id = B.id;

hive> SELECT * FROM TableD;
OK
Bob 4
Sam 6

A: Two tables were created with the below columns
CREATE TABLE TABLE_1
( NAMES VARCHAR2(10) NOT NULL,
ID_1 NUMBER (2) NOT NULL)

CREATE TABLE TABLE_2
( VALUES_1 VARCHAR2(10) NOT NULL,
ID_1 NUMBER (2) NOT NULL)

and inserted values in these tables
Final table should be created as
CREATE TABLE TABLE_3 AS (
SELECT T1.NAMES,T2.ID_1 FROM TABLE_1 T1,TABLE_2 T2
WHERE T1.ID_1(+)= T2.ID_1)

A: The correct syntax for the result I wanted was:
CREATE TABLE tableC AS
SELECT tableA.*
FROM tableA LEFT SEMI JOIN tableB on (tableA.id = tableB.id);

A: Create the result table
CREATE TABLE TABLE3 (Name STRING, id INT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
STORED AS TEXTFILE;

Then insert into the new table using Join
INSERT INTO  TABLE TABLE3 SELECT t1.Name, t1.Id from Table1 t1
JOIN Table2 t2 WHERE t1.id = t2.id;

will give you the desired result.


text:
Q: IcCube - Facts Table not completely matching Dimension I have a facts table and a dimension table from two different sources. They are connected with an offer_id. But in the facts table there are offer_ids not found in the dimension table and vice versa.
Building the cube of course I get some 'no member found for key' error.
Is it possible, to get the cube done with a default offer_id where none is to be found? I didn't find an option to join those two tables withing IcCube (I hoped for a Table View) and a default I only seem to be able to set at a tables creation - but at that point I don't even know, which entries to change...

A: I didn't see the 'Unknown Member' option in the Dimensions...
Thanks anyway.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Conditionally show Alert using onbeforeunload in Angular I want to show alert popup conditionally when I am in Edit mode. I tried using HostListener but it appears even when we are not in edit mode so I want to disable onbeforeunload event conditionally. For now All I know is onbeforeunload will help me provide alert box but it will appear for all the cases. The Code I am using is :
@HostListener('window:beforeunload',['$event'])
  defaultConfirmation(event : any): void {
    console.log(this.initiateEdit)
    if(this.initiateEdit) return true;
    else return false;
  }


text:
Q: Converting Columns into Rows in Pentaho i have a table below that looks like the current one below. How can i put the values for date, count2, amount2 from columns into rows just ONCE?
current:
date   type count amount type2  date count2 amount2
1/1/20  00    5    13.49  ZZZ  1/1/20    0      5.00
1/1/20  12    6    14.69  ZZZ  1/1/20    0      5.00
1/1/20  11    10   20.66  ZZZ  1/1/20    0      5.00

expected
date   type count amount
1/1/20  12    6    14.69
1/1/20  12    6    14.69
1/1/20  11    10   20.66
1/1/20  ZZZ   0    5.00

A: what can you do it just splits data flow into two select steps.
in the first select step use your first three columns.
in the second select step use your remaining other columns. and use filter rows to remove redundancy. then use dummy step and link to both select steps.


text:
Q: How to Exit Watchdog/Python Script from Handler Class Function? I have a script that is watching a folder for a file to be received. If the file is NOT received in X amount of time I want to be alerted, if it is received I want to exit the script. I plan to use Windows scheduled task to start/stop the script (because I don't know how to recycle it in Python). I'm currently stuck on trying to exit out of Watchdog/Python WHEN the file is received (since I only want alert if it isn't).
In the Handler Class I added a call to the quitter function on the if the event.event_type is detected. However, it doesn't exit and continues through till the timeout value is reached.
Here's what I have so far:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import smtplib
import sys

file_rec = False

class Watcher:
    DIRECTORY_TO_WATCH = r"C:\Temp"

    def __init__(self):
        self.observer = Observer()

    def run(self):
        t_end = time.time() + 5 * 3 # Configure timeout value
        global file_rec
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=False)
        self.observer.start()
        try:
            while not file_rec:
                if time.time() > t_end: # If timeout reached file not created -- send email
                    email()

                else:
                    time.sleep(5)
        except:
            self.observer.stop()
            print("Error")

        self.observer.join()

class Handler(FileSystemEventHandler):

    @staticmethod
    def on_any_event(event):
        if event.is_directory:
            return None

        elif event.event_type == 'created':
            # File has been received, can now quit watching
            global file_rec
            file_rec = True
            quitter()

if __name__ == '__main__':

    def email():
        createMsg = "File XXX on Server XXX has not been received, manual intervention required."
        sender = 'NoReply@mydomain.com'
        receiver = 'test.user@mydomain.com'
        message = """From: No Reply <NoReply@mydomain.com>
                            TO: Test User <test.user@mydomain.com>
                            Subject: File Not Received

                            Attention Required: """ + str(createMsg)
        mail = smtplib.SMTP('email.mydomain.com', 25)
        mail.ehlo()
        #mail.starttls()
        mail.sendmail(sender, receiver, message)
        mail.close()
        quitter()

    def quitter():
        sys.exit()

    w = Watcher()
    w.run()

A: I had the same problem. I solved passing the observer to the handler extended constructor
from watchdog.events import FileSystemEventHandler

class MyHandler(FileSystemEventHandler):
    def __init__(self, observer):
        object.__init__(self)
        self.observer = observer

    def process(self, event):
        """
        event.event_type
            'modified' | 'created' | 'moved' | 'deleted'
        event.is_directory
            True | False
        event.src_path
            path/to/observed/file
        """
        # the file will be processed there
        print event.src_path, event.event_type  # print now only for debug
        self.observer.stop()
        print "stopped"

    def on_modified(self, event):
        self.process(event)

    def on_created(self, event):
        self.process(event)


text:
Q: Wifi Extender setup issue irrespective of brand name and modal number I have done WiFi Extender Setup of well-known brands and modal numbers.
Irrespective of brand name and modal number, I faced difficulties while extender setup.
In some cases, users do not have computer and some extender doesn't get easily setup with WPS.
Moreover, in some cases, the main router doesn't have WPS button.
User is unable to manage a computer and ethernet cable.
In such scenarios, irrespective of brand name and modal number, please let me know how to setup wifi extender with android and iPhone?
With Regards
TekQ


text:
Q: Map on array and save item to other array in Vue I have a array of arrays:
[["email", "test@test.com"], ["phone", 123123123], ["address", "street"]]

I want to create array where I will have only first element from every array:
["email", "phone", "address"]

I have something like that:
bigArray.map((field) => {
        this.smallArray.add(field[0]);
      });

but I got error: Error in event handler for "bigArray": "TypeError: _this.smallArray.add is not a function"
How can I solve this issue?

A: this.smallArray = this.bigArray.map(arr => arr[0])

A:

const arr = [["email", "test@test.com"], ["phone", 123123123], ["address", "street"], ["sameple"]]
const result = arr
  .filter(a => !!a[1])
  .map(a => a[0])

console.log(result)

A: I think you are tyring to add filtered element to smallArray. You should use.
this.smallArray.push(field[0]);


text:
Q: Docker Mysql+PHP [Port mismatch issue with terminal & PHP Application] I have written a new docker-compose file for MySQL & PHP connection
From MySQL:

*

*Port exposing 3315:3306
From PHP:

*

*To access a MySQL from PHP server, I have added line docker-compose.yml links as 'mysql' service name

*Port exposing 30005:80
My Folder structure & file [Image-1]

This is command, which I used to run the docker
docker-composer --build up
My running containers list  [Image-2]

This is how I'm accessing in terminal  [Image-3]

The Result of the PHP script is  [Image-4]

My problem to this configuration is, when you noticed the index.php file from the Image-1.
i have used port as 3306 to connect a mysql, but when you refer the Image-3. To connect a mysql in terminal, i have used port as 3315
Issue on this, Why i need to use 3306 as port in PHP application to MySQL server, instead of using mysql(In docker-compose.yml file) exposed port 3315.
In terminal, i can able to access correctly, but when we go for application i have this problem.
Someone can help me to understand the port mismatch in application & terminal for a MySQL connect.
Thanks in advance

A: All your containers are in one isolated network. Mysql service has hostname - mysql and listens to port 3306.
The host machine listens to port 3315 and forwards packets into that network on port 3306.


text:
Q: Does there exist a relationship between elasticity tensor $E_{ijkl}$ and $\int_{\Gamma} F^i z^i d \Gamma$? Does there exist a relationship between elasticity tensor $$E_{ijkl}$$ and $$\int_{\Gamma} F^i z^i d \Gamma$$ where $F^i$ is force and $z^i$ displacement. $\Gamma$ is loaded boundary.
I see these two formulations in shape optimization problem formulations using material distribution method. That makes me think that these two are equal, but I cannot see how.

A: They are two different things.
The elasticity tensor is a property of an elastic material, and it represents a density of stiffness. It relates stresses ($\sigma_{ij}$) with strains ($\epsilon_{ij}$) (using Einstein summation):
$$\sigma_{ij} = E_{ijkl} \epsilon_{kl}\, .$$
Your second expression represents the work done over your body while subjected to a force $F^{i}$, and moves a distance $z^{i}$.
Also, see that one quantity is a fourth order tensor while the other is a scalar.

A: Power stress $\cfrac{dW}{dt}=\sigma_{ij}D_{ij}$, where $\sigma_{ij}$ is the stress tensor and $D_{ij}$ is the velocity gradient, and the velocity gradient is just the strain $ϵ_{ij}$ per time unit. This relation might help you to constrain the problem more.
$$\cfrac{dW}{dt}=\sigma_{ij}D_{ij} = \sigma_{ij}\frac{ϵ_{ij}}{dt}$$
so with W=$\int_\Gamma F^iz^i d\Gamma$
$$\int_\Gamma F^iz^i d\Gamma= \sigma_{ij}{ϵ_{ij}} = (E_{ijij}ϵ_{ij})ϵ_{ij}$$
Which might be simplified further...


text:
Q: Show picture upon cell selection that matches cell string to picture database in excel I will attempt to explain to the best of my abilities what I am looking for as far as a final product. I am trying to make a spreadsheet that has a list of strings in a column.
When the strings are hovered over, the string will be used to match to the name of a picture in a database. The database will return the picture and show it as a rollover image.
I have searched for ways on how to do this, but I keep finding people who change it based on the comments and use a static image for each cell. I have a database of around 23000 pictures and can't do it manually one at a time, and the cells have the potential to be variable depending on the opened sheets.
Hover over is not necessary, however. I would be more than happy to do this upon a cell selection.

A: This is a broad question and covers many parts.  Here is a little something to get you started.
Open the VB Editor by pressing Alt+F11.  Right click on the sheet you want this functionality to exist on and then click View Code.  This code will load a comment with a single image (be sure to change C:\YOUR_IMAGE_FULL_PATH to a valid image) into whichever cell you click into.  When you leave the cell it will delete the comment.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Target.Cells.Count = 1 Then

        Static cellAddress
        Dim sFile As String
        Dim cmt As Comment

        If cellAddress <> "" Then
            Set cmt = Range(cellAddress).Comment
            cmt.Delete
            Set cmt = Nothing
        End If

        sFile = "C:\YOUR_IMAGE_FULL_PATH"

        Set cmt = Target.AddComment
        cmt.Text Text:=""
        With cmt.Shape
            .Fill.UserPicture sFile
        End With

        cellAddress = Target.Address

    End If

End Sub

When you say

The database will return the picture and show it as a rollover image

Does that mean the image itself is stored in the database?  Or is the name of the image returned from the database and we have to search a directory on the HDD for an image with that name?
Without knowing your DBMS or your table schema or anything like that I can't really help much more.


text:
Q: Font sizes in px in modern browsers (is it good, what about 120 dpi?) I used to use the 'font-sizes in ems' approach (mostly for IE users)  and some CSS hacks to have the same font size on systems where screen is set to 120dpi. I know that forcing the same font size in 120 dpi is not good in usability terms, but this is the way I should get it done.
I'm curious is it good to switch to pixels instead of ems, as far as I see all my target browsers (IE7,8; FF 3.6, Chrome 5, Opera 10.6, Safari Win) support full page zoom.
I have the following restrictions:

*

*No IE6 support

*Font size should be the same in 96dpi and 120dpi (I usually have many graphics that requires that text should be in some particular size).

Should I switch?
Thanks in advance!

A: I generally recommend to stick w/ em- or %-based font-sizes to avoid headaches related w/ the pixel based approaches. However, you might want to use px for the base font size and adjust it w/ CSS3 media queries to your needs (particularly querying for the resolution should help you).
The downside of this method is that, as so often, IE 7 and 8 will need yet another hack as IE is the only browser in your list currently not supporting media queries. hth & good luck!


text:
Q: Mongoose: Browser should not open The application that I'm developing right now uses Chromium Embedded
Framework to handle multiple display webapp.
The Mongoose executable is ran by the framework at run time. At the same
time however, Mongoose runs an instance of Google Chrome.
As much as possible, I want to avoid this scenario.
Is there a way to disable Mongoose from opening a browser but continue with
the webserver execution?

A: Add start_browser no line to the mongoose.conf file. Make sure that mongoose.conf file lives in the same directory as mongoose.exe.


text:
Q: Should DTOs represent nested entity strutctures, or should I have my pathing set up to have an endpoint for each nested object? For example, lets say I have an entity that looks like this.
public class PersonEntity {
    public String firstName;
    public String lastName;
    public List<CarEntity> cars;
}

Option 1
GET /people/1
{
    "firstName": "Bob",
    "lastName": "Sagget,
    "cars": [
        (could be just IDs or the full Car DTOs)
    ]
}

Option 2
GET /people/1
{
    "firstName": "Bob",
    "lastName": "Sagget"
}

GET /people/1/cars
[
    {
        "make": "Honda",
        "model": "Accord",
        "year": 1992
    }
]

I feel like option 2 is more RESTful. But I also wonder about instances where you will need the full nested set of objects in every scenario. Should I still design it this way in that case? Also, what if the Car entity has nested objects? I would need a third endpoint to navigate down into the cars child entities.

A: If you put the entire cars dto in people, you will be able to display a person and all the cars this person has on the same page which I think is a more user friendly design.
If you make a separate endpoint for a person's cars then the user would first navigate to the person's page and then the user would have to click again in order to see this person's cars which may even require another page load


text:
Q: Is there a programmatic interface to the Windows wireless network report? That is the report generated with command prompt command:
netsh wlan show wlanreport
which writes a report file out to C:\ProgramData\Microsoft\Windows\WLANReport\WLAN-report-latest.html. References:
https://support.microsoft.com/en-us/help/4000462/windows-10-analyzing-wireless-network-report
https://www.windowscentral.com/microsoft-fixes-single-notification-error-latest-windows-10-slow-ring-build
I would like to get that type of data programmatically (via .NET/C#, win APIs, WMI, or Powershell) and ideally not in the form of an HTML file to then parse. But I'll take what I can get. Worse case might be to shell execute a call to that command to generate the report.
Or is the programmatic alternative to call a bunch of different APIs to get the complete set of info instead of a single call/command like this netsh one?


text:
Q: Can two Silverlight applications share IsolatedStorage on one machine? What identifies an silverlight application and when can two silverlight applications share IsolatedStorage if at all, i.e.:

*

*if I want to have two Silverlight applications share IsolatedStorage space, is this possible? What kind of "application id" do I need to give to do this?

*if I don't want two Silverlight applications to share IsolatedStorage, how do I prevent this? Do I need to do this?

For instance, I've noticed when I develop a Silverlight application, I can press F5, in the application save to Isolated Storage, stop the application, press F5 again, and it reads from the same IsolatedStorage. (I would think that a new compilation would cause it to use new IsolatedStorage.)
However, when I then copy the .xap and .html files to another directory and open the .html file, it does NOT share the IsolatedStorage with the application I was developing. What changed?
What is going on behind the scenes here so I know when IsolatedStorage is shared and when it isn't?

A: The URL to the source XAP file identifies the application.  You would want a new version of an application to be able to read the existing store for a previous version.  Consider a game where all the high scores are stored in the application store.  The user might be a little upset when all those scores disappear after they upgraded it.
Different applications can share a single site based store.  However you only get those two levels of granularity, app level keyed at the XAP Url or site based, which is host and port (I'm not sure whether scheme is also part of that key).

A: If memory serves me right the isolated storage can be used within the scope of the application and scope of the page. So - if I understand my recollection right, I'd probably say - yes.
Edit
From a copy of Pro Silverlight 3.0 in C# that I posess :
(p. 636)
With isloated storage, a niqe storage location is created for every combination of user and application. In other words, the same computer can have multiple isloated storage locations for the same application, assymin each one is for a different user. Similarly the same user can have multiple storage locations one for each Silverlight Application
(p. 637)
... GetUserStoreForFile(). This method provides a storage site that's accessible to all silverlight applications on the same website domain, however these settings are still user specific


text:
Q: MySQL Select Row With Highest Column Value Given the data set for a table person_investments:

id
person
stock
invested

1
Jack
GOOG
1000

2
Jack
META
800

3
Jack
TSLA
1500

4
Jill
GOOG
4000

5
Jill
TSLA
1000

6
Taylor
WMT
1000

7
Taylor
TGT
2500

8
Taylor
HD
1000

I'm trying to figure out how to query and get the stock in which each person is most invested. In this example, I'm looking for this result:

id
person
stock
invested

3
Jack
TSLA
1500

4
Jill
GOOG
4000

7
Taylor
TGT
2500

I've been trying to work with something basic like this:
SELECT id, person, stock, MAX(invested)
FROM person_investments
GROUP BY person;

However, with a real data set, I'm not getting the expected results. What am I getting wrong?

A: Need to pick max in each group of person.
One was can be using rank -
select id, person,stock,invested
from (
 select id, person,stock,invested,
 dense_rank() over (partition by person order by invested desc) rnk
 from stock)s
where s.rnk =1;

Refer fiddle here.
I've also added a scenario where there are more then 1 max.

A: SELECT id, person, stock, MAX(invested) FROM person_investments GROUP BY stock,person;

In groupby field, you have to combine person and stock also.


text:
Q: Zip Kit Integration with Xcode 4.3 I am trying to use zip/unzip functionality in my iOS app for that purpose I found one library from blog link -  https://bitbucket.org/kolpanic/zipkit/wiki/UsingZipKit.
I am using Xcode 4.3 and getting below error
ZKDefs.h, ZKFileArchive.h No such file or directory

I have followed all instructions but still getting this error. Anyone has tried this library for Xcode 4.3 iOS 5? May be I am getting this error due to Header path, but I am unable to solve this.
Thanks in advance...

A: I found the answer. I am using shell command and trying to zip/unzip through it. It worked for me on simulator.
e.g
           system("zip newfile.zip oldfile.rtf");


text:
Q: Swift: Convert Foo to Foo here is my code
class Foo<T> {

}

class Main {
    static func test() {
        var foo: Foo<Any>

        var bar = Foo<String>()
        //Do all my stuff with foo necessitating String

        foo = bar
    }
}

When I try to assign foo = bar I get an error Cannot assign a value of type Foo<String> to a value of type Foo<Any>.
I don't understand why I got this error, since String conforms to Any.
If I do exactly the same thing but using Array, I don't have any error
static func test() {
        var foo: Array<Any>

        var bar = Array<String>()
        //Do all my stuff with foo necessitating String

        foo = bar
    }

Does anyone know what's wrong with my code?
Thanks

A: Arrays and dictionaries are special types that have this kind of behavior built in. This does, however, not apply to custom generic types. The type Foo<Any> is not a supertype (or in this case superclass) of Foo<String> even though Any is a supertype of String. Therefore, you cannot assign variables of these types to each other.
Depending on your particular case the solution outlined in Swift Cast Generics Type might work for you. When Foo wraps a value of type T you can add a generic constructor that converts the value from a differently typed instance of Foo.
class Foo<T> {
    var val: T

    init(val: T) {
        self.val = val
    }

    init<O>(other: Foo<O>) {
        self.val = other.val as! T
    }
}

class Main {
    static func test() {
        var foo: Foo<Any>

        var bar = Foo<String>(val: "abc")
        //Do all my stuff with foo necessitating String

        foo = Foo<Any>(other: bar)
    }
}

A: I have improved on @hennes answer by adding the ability to define how you want to convert from type O to type T
class Foo<T> {
    var val: T

    init(val: T) {
        self.val = val
    }

    init<O>(other:Foo<O>, conversion:(O) -> T) {
        self.val = conversion(other.val)
    }
}

class Main {
    static func test() {
        var foo: Foo<Int>

        var bar = Foo<String>(val: "10")
        //Do all my stuff with foo necessitating String

        foo = Foo<Int>(other: bar, conversion: {(val) in
            return Int(val.toInt()!)
        })
        print(foo.val) //prints 10
        print(foo.val.dynamicType) //prints Swift.Int
    }
}

This gives you the ability to convert between two types that don't support casting to each other. Additionally, it gives a compiler warning when the conversion is illegal, as opposed to crashing due to the forced cast.
No idea why there is a difference in compiler warnings for 1 or >1 line closures but there are.
Bad compiler warning for 1-line closure

Good compiler warning for 2-line closure


text:
Q: Como creo un boton con una imagen en python tkinter amigos mi pregunta es como creo un boton y al boton insertarle una imagen, soy nuevo con python tkinter, si me pueden ayudar muchas gracias.
Intente con esto:
img = PhotoImage(file='actualizar.png')
botonNuevo1 = tkinter.Button(text="test", width=500, height=500, image=img,justify="right")
botonNuevo1.place(x=500, y=100)

y me queda así:

A: Tienes que usar pack() para organizar. Según tu ejemplo, el código sería el siguiente.
import tkinter
from tkinter import PhotoImage
from PIL import Image,ImageTk
root = tkinter.Tk()
root.geometry("960x600")
img = Image.open('actualizar.png')
img = img.resize((1000, 250), Image.ANTIALIAS) # Redimension (Alto, Ancho)
img = ImageTk.PhotoImage(img)
botonNuevo1 = tkinter.Button(root, image=img, text="asdfasdf", compound="top")
botonNuevo1.place(x=500, y=100)
botonNuevo1.pack()

root.mainloop()

Pack() te ayuda a controlar la posición del objeto. También se puede usar grid().
Te dejo un tutorial donde se explica a detalle: Posicionar elementos en Tcl/Tk (tkinter)
Use la librería PIL para redimensionar la imagen.


text:
Q: Decrypting using AES / Crypto++ I'm trying to figure out how to decrypt a block of cipher text using AES. I am using the crypto++ library - or at least TRYING to use that library. But I'm getting absolutely nowhere. I assume that it is only a couple of lines of code to run this decryption algorithm, but I can't figure it out. This is what I have written. Start laughing now:
#include <stdio.h>
#include <cstdlib>
#include <rijndael.h>
#include <sha.h>

using namespace std;

int main()
{

    // Decryption
    CTR_Mode< AES >::Decryption decryptor;
    decryptor.SetKeyWithIV( cbcKey, AES::DEFAULT_KEYLENGTH, cbcCipher );
}

Can anyone give me a brief tutorial on how to "simply" decrypt a 16-byte block of cipher text given a decryption key using crypto++? Their documentation is more cryptic than the cipher text you see above (at least for me), and I'm finding little help by searching.  Thank you very much.

A: The FAQ at the crypto++ library webpage contains pointers to a "tutorial", go read it over there.

A:
Can anyone give me a brief tutorial on how to "simply" decrypt a 16-byte block of cipher text given a decryption key using crypto++?

This from the Crypto++ wiki. It provides a CTR mode example.
AutoSeededRandomPool prng;

SecByteBlock key(AES::DEFAULT_KEYLENGTH);
prng.GenerateBlock( key, key.size() );

byte ctr[ AES::BLOCKSIZE ];
prng.GenerateBlock( ctr, sizeof(ctr) );

string plain = "CTR Mode Test";
string cipher, encoded, recovered;

/*********************************\
\*********************************/

try
{
    cout << "plain text: " << plain << endl;

    CTR_Mode< AES >::Encryption e;
    e.SetKeyWithIV( key, key.size(), ctr );

    // The StreamTransformationFilter adds padding
    //  as required. ECB and CBC Mode must be padded
    //  to the block size of the cipher. CTR does not.
    StringSource ss1( plain, true,
        new StreamTransformationFilter( e,
            new StringSink( cipher )
        ) // StreamTransformationFilter
    ); // StringSource
}
catch( CryptoPP::Exception& e )
{
    cerr << e.what() << endl;
    exit(1);
}

/*********************************\
\*********************************/

// Pretty print cipher text
StringSource ss2( cipher, true,
    new HexEncoder(
        new StringSink( encoded )
    ) // HexEncoder
); // StringSource
cout << "cipher text: " << encoded << endl;

/*********************************\
\*********************************/

try
{
    CTR_Mode< AES >::Decryption d;
    d.SetKeyWithIV( key, key.size(), ctr );

    // The StreamTransformationFilter removes
    //  padding as required.
    StringSource ss3( cipher, true,
        new StreamTransformationFilter( d,
            new StringSink( recovered )
        ) // StreamTransformationFilter
    ); // StringSource

    cout << "recovered text: " << recovered << endl;
}
catch( CryptoPP::Exception& e )
{
    cerr << e.what() << endl;
    exit(1);
}

Here's the result of running the sample program:
$ ./crytpopp-test.exe
key: F534FC7F0565A8CF1629F01DB31AE3CA
counter: A4D16CBC010DACAA2E54FA676B57A345
plain text: CTR Mode Test
cipher text: 12455EDB41020E6D751F207EE6
recovered text: CTR Mode Test

A: Indeed, Crypto++ tutorials a quite hard to follow. In general, in order to use Crypto++ API you need to have at least some basic knowledge about Cryptography, I would suggest this Cryptography course.
Having said that, let me address your question. Since it is a little bit ambiguous, I would assume that you would like to decrypt an AES cipher, using CTR mode. As input, let's say you have a cipher, the IV and the key (all represented in hex in a std::string).
#include <iostream>
#include <string>

#include "crypto++/modes.h" // For CTR_Mode
#include "crypto++/filters.h" //For StringSource
#include "crypto++/aes.h" // For AES
#include "crypto++/hex.h" // For HexDecoder

int main(int argc, char* argv[]) {
    // Our input:
    // Note: the input was previously generated by the same cipher
    std::string iv_string = "37C6D22FADE22B2D924598BEE2455EFC";
    std::string cipher_string = "221DF9130F0E05E7E87C89EE6A";
    std::string key_string = "7D9BB722DA2DC8674E08C3D44AAE976F";

    std::cout << "Cipher text: " << cipher_string << std::endl;
    std::cout << "Key: " << key_string << std::endl;
    std::cout << "IV: " << iv_string << std::endl;

    // 1. Decode iv:
    // At the moment our input is encoded in string format...
    // we need it in raw hex:
    byte iv[CryptoPP::AES::BLOCKSIZE] = {};
    // this decoder would transform our std::string into raw hex:
    CryptoPP::HexDecoder decoder;
    decoder.Put((byte*)iv_string.data(), iv_string.size());
    decoder.MessageEnd();
    decoder.Get(iv, sizeof(iv));

    // 2. Decode cipher:
    // Next, we do a similar trick for cipher, only here we would leave raw hex
    //  in a std::string.data(), since it is convenient for us to pass this
    // std::string to the decryptor mechanism:
    std::string cipher_raw;
    {
        CryptoPP::HexDecoder decoder;
        decoder.Put((byte*)cipher_string.data(), cipher_string.size());
        decoder.MessageEnd();

        long long size = decoder.MaxRetrievable();
        cipher_raw.resize(size);
        decoder.Get((byte*)cipher_raw.data(), cipher_raw.size());
        // If we print this string it's completely rubbish:
        // std::cout << "Raw cipher: " << cipher_raw << std::endl;
    }

    // 3. Decode the key:
    // And finally the same for the key:
    byte key[CryptoPP::AES::DEFAULT_KEYLENGTH];
    {
        CryptoPP::HexDecoder decoder;
        decoder.Put((byte*)key_string.data(), key_string.size());
        decoder.MessageEnd();
        decoder.Get(key, sizeof(key));
    }

    // 4. Decrypt:
    std::string decrypted_text;
    try {
            CryptoPP::CTR_Mode<CryptoPP::AES>::Decryption d;
            d.SetKeyWithIV(key, sizeof(key), iv);

            CryptoPP::StringSource ss(
                cipher_raw,
                true,
                new CryptoPP::StreamTransformationFilter(
                    d,
                    new CryptoPP::StringSink(decrypted_text)
                ) // StreamTransformationFilter
            ); // StringSource

            std::cout << "Decrypted text: " << decrypted_text << std::endl;
    }
    catch( CryptoPP::Exception& e ) {
            std::cerr << e.what() << std::endl;
            exit(1);
    }

    return 0;
}

I compiled it on Ubutunu 14.04, using Crypto++562:
g++ -Wall -std=c++0x -o prog practicalAES.cpp -lcryptopp
If I run the program, I get this output:
Cipher text: 221DF9130F0E05E7E87C89EE6A
Key: 7D9BB722DA2DC8674E08C3D44AAE976F
IV: 37C6D22FADE22B2D924598BEE2455EFC
Decrypted text: CTR Mode Test
It's not really visible here, but both the Key and the IV have the same length - 16 bytes (or 128 bits). This is the block size, so this cipher is AES-128. Since it is the CTR mode, no padding is added, and both the cipher and the plain text have the same number of bytes.
Also note that 60% of the code involves decoding the string into hex, while the decryption itself is only the last step (so if your input data comes as raw hex, no decoding is needed).

A: The tutorial of Crypto++ is focused on the usage of filters and sources and sinks, which are, in my opinion, over complicated. In your case the code is actually very simple:
CTR_Mode< AES >::Decryption decryptor;
decryptor.SetKeyWithIV( cbcKey, AES::DEFAULT_KEYLENGTH, cbcCipher );
decryptor.ProcessData(output, input, size);

// Decrypt another piece of data with the same key
decryptor.Resynchronize(new_iv, new_iv_length);
decryptor.ProcessData(new_output, new_input, size);


text:
Q: Deserialize json string to c# object using newtonsoft I have been working with the project, where i have to make external RESTful service call to get some data.
The problem i'm facing here is, the response i'm getting from the service is different on different scenario. For example.
On one scenario, i'm getting below response
{
   "id":3000056,
   "posted_date":"2016-04-15T07:16:47+00:00",
   "current_status":"initialized",
   "customer":{
        "name" : "George",
        "lastName" : "Mike"
   },
   "application_address":{
        "addressLine1" : "Lin1",
        "addressLine2" : "Lin2",
   }

}

In the other scenario, im getting below response
 {
   "id":3000057,
   "posted_date":"2016-04-15T07:16:47+00:00",
   "current_status":"initialized",
   "customer":[],
   "application_address":[]

}

The problem here is, i have below model, and i'm deserializing it by newtonsoft deserailization.
public class Response
    {

        [JsonProperty("id")]
        public int Id { get; set; }

        [JsonProperty("posted_date")]
        public DateTime PostedDate { get; set; }

        [JsonProperty("current_status")]
        public string CurrentStatus { get; set; }

        [JsonProperty("customer")]
        public Customer Customer { get; set; }

        [JsonProperty("application_address")]
        public ApplicationAddress ApplicationAddress { get; set; }

    }

public Class Customer
{

    public string name { get; set; }
    public string lastName { get; set; }
}

public classs ApplicationAddress
{
public string addreesLine1{ get; set; }
public string addreesLine1{ get; set; }
}

For the first response, it will desrialize. But for the second response, the response is not getting deserialized as the response contains [] for Customer and ApplicationAddrees object. While deserializing, it is treating as a array, but actually it is not.
Note : Below code i'm using for Deserializing.
Response response =                    JsonConvert.DeserializeObject(result);
Is there any configuration we can do before serializing? Is newtonsoft facilitate that feature?
Thanks .

A: If you are sure that there will be no arrays in this properties, than you can consider using JsonConverter like this:
public class FakeArrayToNullConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return false;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return null;
        }
        return  token.ToObject<T>();

    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

And then put additional attribure to your model:
    [JsonProperty("customer")]
    [JsonConverter(typeof(FakeArrayToNullConverter<Customer>))]
    public Customer Customers { get; set; }

    [JsonProperty("application_address")]
    [JsonConverter(typeof(FakeArrayToNullConverter<ApplicationAddress>))]
    public ApplicationAddress ApplicationAddressList { get; set; }

And when in your JSON string  for this properties it will be an array [], you will simply deserialize it with null object.

A: You can't instruct deserialize to handle "[]" as something different as it represents an array (are you sure you never will get customers and addresses in those arrays??)
So you could deserialize to an anonymous type and then map it to your structure.

A: This is just a guess but can you check if this works:
public class ApplicationAddress
{
    private readonly string[] _array = new string[2];
    public string this[int index]
    {
        get { return _array[index]; }
        set { _array[index] = value; }
    }
    public string addreesLine1
    {
        get { return this[0]; }
        set { this[0] = value; }
    }
    public string addreesLine2
    {
        get { return this[1]; }
        set { this[1] = value; }
    }
}


text:
Q: Get all informations of a discrete random variable in tensorflow Imagine that I build a discrete random variable in tensorflow. There is a way to get the P(X = k) and associated probabilities ?  i.e two lists [k_1 .., k_n] and [p_1,.., p_n] with p_i = P(X = k_i) ?

A: How about tfp.distributions.Categorical(logits=np.random.randn(10)).probs_parameter()
And if you wanted it to take on values different from 0..9, you could use tfp.distributions.FiniteDiscrete


text:
Q: Returning a 2D C array of type id in Objective-C I'm using a 2D C array of ids in my iOS app. Is it possible to return this in an objective-C method? As an alternative solution, I tried to return a pointer to a 2D C array of integers, but I cannot modify the 2D-int array.
- (int (*)[8][8])board:(Piece *)piece
{

    int (*layout)[8][8] = malloc(8 * 8 * sizeof(int));

    //Cannot modify layout 2D C array

    return layout;
}

I have some experience in Objective-C, but none in C. Am I likely to continually run into problems using C 2D arrays, such that I should make a 2D-Array Objective-C class? What is the more typical approach an iOS developer would use?

A: - (int **)board:(Piece *)piece
{

    int **layout = malloc(8 * sizeof(int *));
    for(int i=0; i<8; i++)
       layout[i] = malloc(8 * sizeof(int));

    return layout;
}

Don't forget to free the memory in the end. Also, you could also use a one dimensional array and something like this to access it in a similar way:
#define access(array, x, y) array[y * 8 + x]

There is also now drop in multi-dimensional array class in Objective-C, but you could create a NSArray with other NSArray's inside of it, or, google if someone else did this (I remember at least one implementation but can't recall its name)

A: After you declare int (*layout)[8][8] = malloc(8 * 8 * sizeof(int));, You can change the values like (*layout)[x][y]=val;. But I recommend you to declare int (*layout)[8], so you can access elements by simply layout[x][y]=val.
Edit: I don't know about Objective-C, but in C, the function I suggested will look like:
int (*newarray())[8] {
 int (*l)[8]=malloc(64*sizeof(int));
 // You can do stuff like l[2][4]=15 here
 return l;
}


text:
Q: How to add an id attribute to a html tag with a certain class using jQuery? I have a link with a class of special and I want to add an id attribute to it.
Only one element in my document will have this class at any one time (I may remove and add a new one at some point).
How would I add an id attribute to the element to change it from this:

to this:

A: Try this
$('div.special').attr('id','your-id');

A: $(".special").attr("id","special-" + (new Date()).getTime());

A: Adding the attribute is easy:
$('.special').attr('id', 'your-id-value');

The more potentially problematic part will be ensuring that the id's you are adding are unique.

A: Don't have the reputation to add a comment, but i believe it's benefitial enough for others searching for answer to state, that
attr();

Doesn't simply add the attribute but rather sets it. Important when there already is some set ID on the element.

A: You can add id with:
$('.special').attr('id', 'id-value');

Do you want change id?
$('.special').removeAttr('id').attr('id', 'id-value');


text:
Q: How to Ignore directory index file in Symbolic links? I made symbolic link : ln -s / link to the root ..
The directory contains an index file (index.php , index.html) etc..,
I can`t have a listing of the content , i get the index directly ..
I want to know how to get a listing of the content even if an index file is present.

A: Index file used by Apache is driven by the DirectoryIndex directive. If you alter this directive in your VirtualHost or Directory with a file name that does not exists, you will prevent apache from finding this file.
So for example let's say you want this behavior for the directory /foo
<Directory /foo>
   # we need this option activated the get automatic listing
   Option +Indexes
   DirectoryIndex not_a_directory_index.does_not_exists.file
</Directory>


text:
Q: Custom classes not changing in Spritekit .sks files I've been working with SpriteKit a bit and can't figure out this issue I'm having with custom classes in .sks files. Below is the sceneDidLoad method you'd find in a newly created SpriteKit project:
- (void)viewDidLoad {
[super viewDidLoad];

// Load 'GameScene.sks' as a GKScene. This provides gameplay related content
// including entities and graphs.
GKScene *scene = [GKScene sceneWithFileNamed:@"GameScene"];

// Get the SKScene from the loaded GKScene
GameScene *sceneNode = (GameScene *)scene.rootNode;

// Copy gameplay related content over to the scene
sceneNode.entities = [scene.entities mutableCopy];
sceneNode.graphs = [scene.graphs mutableCopy];

// Set the scale mode to scale to fit the window
sceneNode.scaleMode = SKSceneScaleModeAspectFill;

SKView *skView = (SKView *)self.view;

// Present the scene
[skView presentScene:sceneNode];

skView.showsFPS = YES;
skView.showsNodeCount = YES;
}

Nothing too crazy - it just loads an .sks file called GameScene, finds its root node (which is a GameScene type due to the custom class in the .sks being set to that), and pushes it to the screen.
The issue I'm having is that when I change this .sks file and the pertaining classes, the root node never adopts the custom class. The .sks file is being found by the sceneWithFileNamed method, as an invalid name will cause the method to return nil, while it currently returns a scene (but with a normal SKScene root node rather than my custom class). This causes my project to crash when I try to assign the scene entities to the sceneNode, which is not a built-in property of SKScene.
Here's my modified version, which only includes two edits:
- (void)viewDidLoad {
[super viewDidLoad];

// Load 'MenuScene.sks' as a GKScene. This provides gameplay related content
// including entities and graphs.
GKScene *scene = [GKScene sceneWithFileNamed:@"MenuScene"];

// Get the SKScene from the loaded GKScene
MenuScene *sceneNode = (MenuScene *)scene.rootNode;

// Copy gameplay related content over to the scene
sceneNode.entities = [scene.entities mutableCopy];
sceneNode.graphs = [scene.graphs mutableCopy];

// Set the scale mode to scale to fit the window
sceneNode.scaleMode = SKSceneScaleModeAspectFill;

SKView *skView = (SKView *)self.view;

// Present the scene
[skView presentScene:sceneNode];

skView.showsFPS = YES;
skView.showsNodeCount = YES;
}

Here's the MenuScene.h file:
#import <SpriteKit/SpriteKit.h>
#import <GameplayKit/GameplayKit.h>

@interface MenuScene : SKScene

@property (nonatomic) NSMutableArray<GKEntity *> *entities;
@property (nonatomic) NSMutableDictionary<NSString*, GKGraph *> *graphs;

@end

Maybe even more interestingly, I can change the custom class of the GameScene .sks, but the code runs as though nothing changed.
Am I missing something, or are custom classes broken?
Update: I've tried putting the module name in the field below the custom class in the .sks inspector, but it hasn't worked out. Here's a link to the post that described that solution: https://forums.developer.apple.com/thread/25620


text:
Q: Paypal Settlement Reports not working Settlement Reports returns that it fetched n rows, but nothing populates on Magento Side.
Was running Magento 1.9 and updated to 1.9.1.0 to the same effect.

A: Magento's documentation on Paypal Settlement Reports is almost nonexistent.
Not sure how many people use this report as there is nothing on the web on this.
http://www.magentocommerce.com/knowledge-base/entry/how-to-set-up-and-run-paypal-settlement-reports doesn't mention anything about all the versions available of the Paypal Reports.
Paypal Settlement Report is now on version 8.0, but on the Payapal SFTP report subscriptions you cannot easily change the versions. My paypal was set up for version 1.0 and I managed to change to version 7 without talking to the customer support by unsubscribing the report and resubscribing. When you re-subscribe, the newer version started being pushed.
Since the reports are pushed once a day, you need to wait for the new version to be available on SFTP.
Magento was still failing after the update to version 7
I'm not sure about other versions, but version 7 has an error in the STL reports where
Transaction Debit or Credit header has 2 spaces between Transaction and Debit, and Magento fails the import.
To fix it, you need to change
 /app/code/core/Mage/Paypal/Model/Report/Settlement.php and add the extra space for that header.
all good now.
Pedro


text:
Q: Full Screen Video Recording in Front Camera using camera2 api I have been stuck in this issue for days.
I followed this Android's official camera-sample in Kotlin:
android's camera-sample
I raised an issue on github issue on 11 Feb 2020 but haven't received any feedback.
My problem is:
I used the sample as it is and only changed val cameraId = manager.cameraIdList[0] to val cameraId = manager.cameraIdList[1] for front camera.
NOTE: It does not happen in rear camera.
The front camera does not work and shows black bar on
devices tested:

*

*Emulator: Pixel C API 29

*Device: Galaxy Tab S2

*Mode: Portrait

I wanted a full screen view, so when I don't set the aspect ratio of AutoTextureView in the commented line below, the video takes full screen but is now stretched.
if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
  //I only have portrait mode
} else {
  //textureView.setAspectRatio(previewSize.height, previewSize.width)
}

Is there a way to set full screen mode without any stretching or in a correct aspect ratio?
I have been through following solutions in slack and none worked for me:
Camera 2 : Unable to record video in full screen?
Camera2 API Make Preview Fill Entire View
Android Camera2 API stretching the preview

A: After working for days. Camera2 full screen preview and image capture helped me solve the problem.
Setting onMeasure in AutoFitTextureView as:
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    val width = View.MeasureSpec.getSize(widthMeasureSpec)
    val height = View.MeasureSpec.getSize(heightMeasureSpec)
    if (ratioWidth == 0 || ratioHeight == 0) {
        setMeasuredDimension(width, height)
    } else {
        if (width > ((height * ratioWidth) / ratioHeight)) {
            setMeasuredDimension(width, (width * ratioHeight) / ratioWidth)
        } else {
            setMeasuredDimension((height * ratioWidth) / ratioHeight, height)
        }
    }
}

Above code makes the screen full size but had problem of preview not
  being at the centre

So I translated as follows in configureTransform(viewWidth: Int, viewHeight: Int)
   // adjust the x and y to centre the preview
   val screenWidth = resources.displayMetrics.widthPixels
   val xShift = (viewWidth - screenWidth)/2

   val screenHeight = resources.displayMetrics.heightPixels
   val yShift = (viewHeight - screenHeight)/2
   matrix.setTranslate(-xShift.toFloat(), -yShift.toFloat())

   textureView.setTransform(matrix)


text:
Q: Elegant SVG shadow outline for visibility (without using filter) I need to find a way to outline my transparent rectangle that has black stroke with some sort of shadow to make it visible on any color background
Here is my attempt to do that without filters (can't use them as it's causing too many reflows) using two rectangles - but it doesn't looks as close as nice as div with shadow.
https://codepen.io/anon/pen/omMmRj

<svg id='mySvg' width="100mm" height="100mm">
   <rect id="mainRect" x="25mm" y="25mm" height="50mm" width="50mm" fill="none"></rect>
   <rect id="secondaryRect" x="25.5mm" y="25.5mm"  height="49mm" width="49mm" fill="none"></rect>
</svg>

body {
  background: white;
}
#hello{
  height: 200px;
  width: 200px;
  border: 1px solid white;
  margin-top:50px;
  margin-left:50px;
  box-shadow: 1px 1px 5px 0px rgba(0,0,0,0.55);
}

And here is sample output I expect to be on that rectangle using div + shadow -> it highliths white border with black color so it's visible on any background. Need to find a way to do same on svg rect without filter.
https://codepen.io/anon/pen/KJBEKG

A: One solution to your problem would be making the two rectangles the sane size and using stroke-dashoffset for one of the two rectangles:

#mySvg{
  border:1px solid black;
  background:orange;
}
#mainRect{
  stroke : white;
  stroke-width: .5mm;
  stroke-dasharray : 3.5mm;
}
#secondaryRect{
  stroke : black;
  stroke-width: .5mm;
  stroke-dasharray : 3.5mm;
  stroke-dashoffset : 3.5mm;
}
<svg id='mySvg' width="100mm" height="100mm">
  <rect id="mainRect" x="25mm" y="25mm" height="50mm" width="50mm" fill="none"></rect>
    <rect id="secondaryRect" x="25mm" y="25mm"  height="50mm" width="50mm" fill="none"></rect>
</svg>

An other solution would be using filters. Please observe that in this case I've added fill="orange" to your rectangle.

#mySvg{
  border:1px solid black;
  background:orange;
}
#mainRect{
  stroke : white;
  stroke-width: .5mm;

}
<svg id='mySvg' width="100mm" height="100mm">
  <filter id="outline">
<feMorphology in="SourceAlpha" operator="dilate" radius="1"/>
<feComposite in="SourceGraphic"/>
</filter>
  <rect id="mainRect" x="25mm" y="25mm" height="50mm" width="50mm" fill="orange" filter="url(#outline)"></rect>
</svg>

A: Answering my own question - nice and good solution is to use secondary rectangle (that has to be put first as SVG layers last items on front), make it bit bigger than other rectangle so it outlines it nicely.

body {
  background: green;
}
#hello{
  height: 200px;
  width: 200px;
  border: 1px solid white;
  margin-top:50px;
  margin-left:50px;
  box-shadow: 1px 1px 5px 0px rgba(0,0,0,0.55);
}
#mainRect{
    fill: none;
    stroke: white;
    stroke-width: 0.5mm;
    stroke-dasharray: 3mm;
}
#secondaryRect{
    stroke: #424242;
    stroke-width: 1mm;
    stroke-dasharray: 3mm;
}
<svg id='mySvg' width="100mm" height="100mm">
   <rect id="secondaryRect" x="25mm" y="25mm"  height="50mm" width="50mm" fill="none"></rect>
   <rect id="mainRect" x="25mm" y="25mm" height="50mm" width="50mm" fill="none"></rect>
</svg>


text:
Q: File saving issue Windows phone 8.1 I am facing the following issue while performing the save operation on a windows 8.1 phone
a. Let us assume there is a a file named test1.doc is downloaded to a default location in the sdcard. SDCARD - Testfolder
b. We try to edit/open the file using the office 365 present in the phone and try to save it. It does not save it in the same location i.e. TestFolder.
c. It prompts the user to save in the file in the default folder present in phone for eg in the above case since it is a .doc it saves in Documents folder.
Based on the file extension, it will try to save them in the respective default location i.e. mp3 will be saved under music, .jpg or png will be in picture, .mp4 under videos and .doc,.xls,.txt, ppt under documents.
Pl. refer to the below link
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn639127.aspx
d. And during save it also modifies the file name by appending (1) to the file. User is also given the option to modify the file name before saving.
Where on the tab and desktop it is allowing us to do the save on the same location.
I would like to know if it is a know limitation on the windows phone or any thing needs to be done to make the file save in the same location. Any input on this will be of great help.

A: That is the platform norm (I am not calling it as "limitation"). Every app has access to its own IsolatedStorage and media libraries depending on the access requested in manifest.


text:
Q: Adding a network folder to Clementine library I have 2 machines running Ubuntu.  One of them contains a music library on its windows partition.
I can connect to that computer's music library via 'connect to server' and save that location as a bookmark, but I can't figure out a way to add that folder/bookmark to my Clementine library.
Any ideas?

A: Just found this post before but found easier solution for Ubuntu 12.10.
So to share for anyone else looking...
Ubuntu stores network shares as a folder in /run/user/<user-name>/gvfs/<share-name>
In Clementine just add that share folder.
Saves a lot of time.
In 12.04 I think it is /home/<user-name>/.gvfs/<share-name> but not sure if Clementine will see hidden folders worth a shot though.

A: This can be done by sharing the source Music folder with Samba, and have the remote machine automount the share to the local Music folder.
On the Machine that has the music files:

*

*Setup Samba server.

*Define a share at ~/Music (or wherever your music files are located).
On the Remote Machine:

*

*Install smbfs

*Edit /etc/fstab to mount the share to ~/Music (or anywhere else you want). Instructions

*Add the folder that the share is mounted to to Clementine Library.

A similar solution can be done with ssh/sshfs, if you need a more security.

A: Update here.  Hope that someone finds this usefull.
On Linux Mint Mate Desktop Ulyana 20.00  using gio:
gio mount smb://server-name/share-name
will mount share in:
/run/user/value/gvfs/'smb-share:server=server name,share=share name'

I tested this as well on my latitude e6420 running Ubuntu focal with Mate desktop, the same results.


text:
Q: Sticky Zoom for geoJson Dynamically loading geoJson for Chloropleth map. When I zoom in and pan all is well but if I choose another Cell Carrier which rerenders the Chloropleth it always jumps back out to the original default Zoom/Center.
How can I implement a 'sticky zoom' to preserve the session bounds?
I've been playing with storing it in an hidden field but if always seems to be overwritten by the change in geoJson features.

var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v10',
    center: [-100, 38],
    zoom: 3
});

if (document.getElementById('hfldBounds').value != 'null') {
    map.fitBounds(document.getElementById('hfldBounds').value);
};

map.on('zoom', function (e) {
   document.getElementById('hfldBounds').value  = map.getBounds();
});

Ideally the user selects a carrier that renders the map. They zoom in and pan and then they want to see what another carrier owns in the same bounds so they change carrier, get the new geoJson data but maintain the previous map extents.

A: I finally worked this out myself so I'll post the solution here:
<script>
        var map = new mapboxgl.Map({
            container: 'map',
            style: 'mapbox://styles/mapbox/light-v10',
            center: [-100, 38],
            zoom: 3
        });

        map.on('zoom', function (e) {
            sessionStorage.setItem('bounds', map.getBounds());
        });

        map.on('drag', function (e) {
            sessionStorage.setItem('bounds', map.getBounds());
        });

        if (sessionStorage.getItem('bounds') != null) {
                let bounds = sessionStorage.getItem('bounds');
                var araBounds = bounds.toString().split(',');
                var swX = parseFloat(araBounds[0].replace('LngLatBounds(LngLat(',''));
                var swY = parseFloat(araBounds[1].replace(')',''));
                var neX = parseFloat(araBounds[2].replace('LngLat(',''));
                var neY = parseFloat(araBounds[3].replace('))', ''));

                var ne = new mapboxgl.LngLat(neX, neY);
                var sw = new mapboxgl.LngLat(swX, swY);

                var box = new mapboxgl.LngLatBounds(sw, ne);
                map.fitBounds(box);
            };
</script>

*

*load map

*save bounds to session variable on move or pan

*check for bounds and construct a new bounds object

*use bounds object with map.fitBounds() to zoom back to your previous extents.


text:
Q: SQLServer Select Query Performance issue I have a performance issue with a select query. The query can take more than 4 minutes which is too long.
This query is launched on .Net Client Process but not on Microsoft SQLServer Management Studio. So It can make sometimes 5 seconds and can make sometimes 4 minutes, 1 minutes, 30seconds.
So I have 3 questions:

*

*Why this select query is too long? Because it can make less than 5 seconds with sqlserver cache free. I test this query with instructions DBCC FREEPROCCACHE and  DBCC DROPCLEANBUFFERS

*Why a sqlserver system   SQLTransaction named sort_init to rebuild indexes makes about 30seconds? How can I proceed to reduce this time?

*Why on the execution plan, I have Clustered Index Scan, and not Clustered Index Seek (scan all page maybe takes  long time) . Each Clustered Index scanned is the Primary Key of each table.
NB: I have another lot of queries using these tables which have Clustered Index Seek on join clause.
What I'm doing wrong? How could I get the query to run faster? How can I optimize the index?

I use SQL Profiler to trace the issue, so I have these principal Events:

A) SQL Profiler:

*

*SP:StmtCompleted:

TextData:
`SELECT [DespatchNote].[Id], [DespatchNote].[RealType], [DespatchNote].[DbOwner], [DespatchNote].[Archived], [CreatedOn], [CreatedById], [UpdatedOn], [UpdatedById], [KeyingFinished], [IsValidated], [ValidatedOn], [ValidatedById], [Notes], [DefaultDisplayLanguageId], [ReferencedTransactionId], [TransactionNumber], [IsCanceled], [CanceledOn], [CanceledById], [TransactionType], [IsPending], [IsGenerated], [PrintCount], [LastPrintDate], [AttachedFile], [IsPointOfSalesTransaction], [IsAffiliatedTransaction], [IsDone], [DoneById], [DoneOn], [IsSent], [SentOn] FROM [DespatchNote] INNER JOIN [Flow] ON [DespatchNote].[Id] = [Flow].[Id] INNER JOIN [Transaction] ON [DespatchNote].[Id] = [Transaction].[Id] INNER JOIN [ProductsMovements] ON [DespatchNote].[Id] = [ProductsMovements].[Id] WHERE (([DespatchNote].[RealType] = @param42485) AND (([ProductsMovements].[IsDone] = @param42486) AND ([DespatchNote].[Archived] IS NULL)))`

*

*Duration (ms)
: 201277

*SQLTransaction :
ObjectName :    sort_init
Duration (ms):  29982
EventSubClass: 1-Commit

B)Query with SHOWPLAN_ALL On

SELECT [DespatchNote].[Id], [DespatchNote].[RealType], [DespatchNote].[DbOwner], [DespatchNote].[Archived],   [CreatedOn], [CreatedById], [UpdatedOn], [UpdatedById], [KeyingFinished], [IsValidated], [ValidatedOn],    [ValidatedById], [Notes], [DefaultDisplayLanguageId], [ReferencedTransactionId], [TransactionNumber],    [IsCanceled], [CanceledOn], [CanceledById], [TransactionType], [IsPending], [IsGenerated],    [PrintCount], [LastPrintDate], [AttachedFile], [IsPointOfSalesTransaction], [IsAffiliatedTransaction],    [IsDone], [DoneById], [DoneOn], [IsSent], [SentOn]    FROM [DespatchNote]     INNER JOIN [Flow] ON [DespatchNote].[Id] = [Flow].[Id]     INNER JOIN [Transaction] ON [DespatchNote].[Id] = [Transaction].[Id]     INNER JOIN [ProductsMovements] ON [DespatchNote].[Id] = [ProductsMovements].[Id]     WHERE (([DespatchNote].[RealType] = (select top 1 DespatchNote.RealType from DespatchNote))     AND (([ProductsMovements].[IsDone] = 1)      AND ([DespatchNote].[Archived] IS NULL)))
  |--Merge Join(Inner Join, MERGE:([x3distributor].[dbo].[Flow].[Id])=([x3distributor].[dbo].[ProductsMovements].[Id]), RESIDUAL:([x3distributor].[dbo].[Flow].[Id]=[x3distributor].[dbo].[ProductsMovements].[Id]))
       |--Clustered Index Scan(OBJECT:([x3distributor].[dbo].[Flow].[PK_Flow]), ORDERED FORWARD)
       |--Merge Join(Inner Join, MERGE:([x3distributor].[dbo].[ProductsMovements].[Id])=([x3distributor].[dbo].[Transaction].[Id]), RESIDUAL:([x3distributor].[dbo].[Transaction].[Id]=[x3distributor].[dbo].[ProductsMovements].[Id]))
            |--Nested Loops(Inner Join, WHERE:([x3distributor].[dbo].[DespatchNote].[RealType]=[x3distributor].[dbo].[DespatchNote].[RealType]))
            |    |--Top(TOP EXPRESSION:((1)))
            |    |    |--Index Scan(OBJECT:([x3distributor].[dbo].[DespatchNote].[IX3_DespatchNote_RealType]))
            |    |--Merge Join(Inner Join, MERGE:([x3distributor].[dbo].[DespatchNote].[Id])=([x3distributor].[dbo].[ProductsMovements].[Id]), RESIDUAL:([x3distributor].[dbo].[DespatchNote].[Id]=[x3distributor].[dbo].[ProductsMovements].[Id]))
            |         |--Clustered Index Scan(OBJECT:([x3distributor].[dbo].[DespatchNote].[PK_DespatchNote]),  WHERE:([x3distributor].[dbo].[DespatchNote].[Archived] IS NULL) ORDERED FORWARD)
            |         |--Clustered Index Scan(OBJECT:([x3distributor].[dbo].[ProductsMovements].[PK_ProductsMovements]),  WHERE:([x3distributor].[dbo].[ProductsMovements].[IsDone]=(1)) ORDERED FORWARD)
            |--Clustered Index Scan(OBJECT:([x3distributor].[dbo].[Transaction].[PK_Transaction]), ORDERED FORWARD)

C) For each table I launch DBCC SHOWCONTIG([MyTable]), so:

DBCC SHOWCONTIG analyse la table 'Transaction'...
Table : 'Transaction' (770101784) ; index ID : 1, base de données ID : 5
Analyse du niveau TABLE effectuée.
- Pages analysées................................: 3690
- Extensions analysées..............................: 466
- Commutateurs d'extension..............................: 526
- Moyenne des pages par extension........................: 7.9
- Densité d'analyse [meilleure valeur:valeur réelle].......: 87.67% [462:527]
- Fragmentation d'analyse logique..................: 1.95%
- Fragmentation d'analyse d'extension...................: 5.79%
- Moyenne d'octets libres par page.....................: 631.1
- Densité de page moyenne (complète).....................: 92.20%
DBCC SHOWCONTIG analyse la table 'DespatchNote'...
Table : 'DespatchNote' (1138103095) ; index ID : 1, base de données ID : 5
Analyse du niveau TABLE effectuée.
- Pages analysées................................: 409
- Extensions analysées..............................: 52
- Commutateurs d'extension..............................: 51
- Moyenne des pages par extension........................: 7.9
- Densité d'analyse [meilleure valeur:valeur réelle].......: 100.00% [52:52]
- Fragmentation d'analyse logique..................: 0.00%
- Fragmentation d'analyse d'extension...................: 5.77%
- Moyenne d'octets libres par page.....................: 806.2
- Densité de page moyenne (complète).....................: 90.04%
DBCC SHOWCONTIG analyse la table 'ProductsMovements'...
Table : 'ProductsMovements' (1074102867) ; index ID : 1, base de données ID : 5
Analyse du niveau TABLE effectuée.
- Pages analysées................................: 1112
- Extensions analysées..............................: 139
- Commutateurs d'extension..............................: 138
- Moyenne des pages par extension........................: 8.0
- Densité d'analyse [meilleure valeur:valeur réelle].......: 100.00% [139:139]
- Fragmentation d'analyse logique..................: 0.00%
- Fragmentation d'analyse d'extension...................: 5.76%
- Moyenne d'octets libres par page.....................: 725.6
- Densité de page moyenne (complète).....................: 91.03%
DBCC SHOWCONTIG analyse la table 'Flow'...
Table : 'Flow' (1890105774) ; index ID : 1, base de données ID : 5
Analyse du niveau TABLE effectuée.
- Pages analysées................................: 2662
- Extensions analysées..............................: 337
- Commutateurs d'extension..............................: 343
- Moyenne des pages par extension........................: 7.9
- Densité d'analyse [meilleure valeur:valeur réelle].......: 96.80% [333:344]
- Fragmentation d'analyse logique..................: 0.45%
- Fragmentation d'analyse d'extension...................: 5.93%
- Moyenne d'octets libres par page.....................: 579.2
- Densité de page moyenne (complète).....................: 92.84%

D)Details for each table:

For all Table in my DataBase, each Index (Clustered and non clustered) have total Fragmentation less than 10 %.
DESPATCHNOTE: (36360 LINES ON THIS TABLE) (7 COLUMNS)
   Indexes : PK_DespatchNote(Cluster)
IX3_DespatchNote_RealType(non unique , non Cluster)
FK_DespatchNote_Archived(non unique , non Cluster)
   Script to create the Table :
CREATE TABLE [dbo].[DespatchNote](
    [Id] [uniqueidentifier] NOT NULL,
    [Archived] [datetime] NULL,
    [RealType] [uniqueidentifier] NOT NULL,
    [DbOwner] [uniqueidentifier] NOT NULL,
    [RecordVersion] [timestamp] NOT NULL,
    [IsSent] [bit] NULL,
    [SentOn] [datetime] NULL,
 CONSTRAINT [PK_DespatchNote] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

TRANSACTION: (136120 LINES ON THIS TABLE) (20 COLUMNS)
   Indexes :   PK_Transaction(Cluster)
IX3_Transaction_RealType(non unique , non Cluster)
FK_Transaction_ReferencedTransactionId(non unique , non Cluster)
FK_Transaction_DefaultDisplayLanguageId(non unique , non Cluster)
FK_Transaction_CanceledById(non unique , non Cluster)
FK_Transaction_Archived(non unique , non Cluster)
   Script to create the Table :
CREATE TABLE [dbo].[Transaction](
    [Id] [uniqueidentifier] NOT NULL,
    [Archived] [datetime] NULL,
    [RealType] [uniqueidentifier] NOT NULL,
    [DbOwner] [uniqueidentifier] NOT NULL,
    [RecordVersion] [timestamp] NOT NULL,
    [Notes] [ntext] NULL,
    [DefaultDisplayLanguageId] [uniqueidentifier] NULL,
    [ReferencedTransactionId] [uniqueidentifier] NULL,
    [TransactionNumber] [nvarchar](40) NULL,
    [IsCanceled] [bit] NULL,
    [CanceledOn] [datetime] NULL,
    [CanceledById] [uniqueidentifier] NULL,
    [TransactionType] [int] NOT NULL,
    [IsPending] [bit] NOT NULL,
    [IsGenerated] [bit] NOT NULL,
    [PrintCount] [int] NOT NULL,
    [LastPrintDate] [datetime] NULL,
    [AttachedFile] [image] NULL,
    [IsPointOfSalesTransaction] [bit] NOT NULL,
    [IsAffiliatedTransaction] [bit] NOT NULL,
 CONSTRAINT [PK_Transaction] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

ALTER TABLE [dbo].[Transaction] ADD  CONSTRAINT [DF_Transaction_TransactionType]  DEFAULT (0) FOR [TransactionType]
GO

ALTER TABLE [dbo].[Transaction] ADD  CONSTRAINT [DF_Transaction_IsPending]  DEFAULT (0) FOR [IsPending]
GO

ALTER TABLE [dbo].[Transaction] ADD  DEFAULT ((0)) FOR [IsGenerated]
GO

ALTER TABLE [dbo].[Transaction] ADD  CONSTRAINT [DF_Transaction_PrintCount]  DEFAULT ((0)) FOR [PrintCount]
GO

ALTER TABLE [dbo].[Transaction] ADD  CONSTRAINT [DF_Transaction_IsPointOfSalesTransaction]  DEFAULT ((0)) FOR [IsPointOfSalesTransaction]
GO

ALTER TABLE [dbo].[Transaction] ADD  CONSTRAINT [DF_Transaction_IsAffiliatedTransaction]  DEFAULT ((0)) FOR [IsAffiliatedTransaction]

FLOW: (136120 LINES ON THIS TABLE) (13 COLUMNS)
   Indexes :   PK_Flow(Cluster)
IX3_Flow_RealType (non unique , non Cluster)
FK_Flow_ValidatedById(non unique , non Cluster)
FK_Flow_UpdatedById(non unique , non Cluster)
FK_Flow_CreatedById(non unique , non Cluster)
FK_Flow_Archived(non unique , non Cluster)
   Script to create the Table :
CREATE TABLE [dbo].[Flow](
    [Id] [uniqueidentifier] NOT NULL,
    [Archived] [datetime] NULL,
    [RealType] [uniqueidentifier] NOT NULL,
    [DbOwner] [uniqueidentifier] NOT NULL,
    [RecordVersion] [timestamp] NOT NULL,
    [CreatedOn] [datetime] NULL,
    [CreatedById] [uniqueidentifier] NULL,
    [UpdatedOn] [datetime] NULL,
    [UpdatedById] [uniqueidentifier] NULL,
    [KeyingFinished] [bit] NULL,
    [IsValidated] [bit] NULL,
    [ValidatedOn] [datetime] NULL,
    [ValidatedById] [uniqueidentifier] NULL,
 CONSTRAINT [PK_Flow] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

PRODUCTSMOVEMENTS : (83631 LINES ON THIS TABLE) (8 COLUMNS)
   Indexes :   PK_ProductsMovements(Cluster)
IX3_ProductsMovements_RealType(non unique , non Cluster)
FK_ProductsMovements_DoneById(non unique , non Cluster)
FK_ProductsMovements_Archived(non unique , non Cluster)
   Script to create the Table :
CREATE TABLE [dbo].[ProductsMovements](
    [Id] [uniqueidentifier] NOT NULL,
    [Archived] [datetime] NULL,
    [RealType] [uniqueidentifier] NOT NULL,
    [DbOwner] [uniqueidentifier] NOT NULL,
    [RecordVersion] [timestamp] NOT NULL,
    [IsDone] [bit] NULL,
    [DoneById] [uniqueidentifier] NULL,
    [DoneOn] [datetime] NULL,
 CONSTRAINT [PK_ProductsMovements] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

If you want more information please advise me
Best regards
Thanks.

A: Your query is basically:
SELECT . . .
FROM [DespatchNote] INNER JOIN
     [Flow]
     ON [DespatchNote].[Id] = [Flow].[Id] INNER JOIN
     [Transaction]
     ON [DespatchNote].[Id] = [Transaction].[Id] INNER JOIN
     [ProductsMovements]
     ON [DespatchNote].[Id] = [ProductsMovements].[Id]
WHERE [DespatchNote].[RealType] = @param42485 AND
      [ProductsMovements].[IsDone] = @param42486 AND
      [DespatchNote].[Archived] IS NULL

First, all your tables have id declared as the primary key.  Alas, the lowest hanging fruit is eaten.
i
Next, the question is about additional indexes.  My guess is that an index on DespatchNote(RealType, Archived, id) would help the query.  This should reduce the volume of data going into the joins, and might encourage the database engine to use the indexes for the joins.


text:
Q: 'Build raylib using make' - I built it using the wrong setting, do I just delete folder and try again?
via: https://github.com/raysan5/raylib/wiki/Working-on-Windows
I installed mingw to build raylib. The instructions as noted above said to use the 1st command. I used the second one by accident. So I deleted the entire raylib folder and extracted out a second one and then used the proper command to compile. My question is: was that the proper way to uninstall my mistake? Or did it create something somewhere else I needed to delete? Comparing the /src of the unbuilt and built versions the difference was a few .o files....does the mingw command just compile code 'for the folder in question'? so everything i did with that mistaken command woulda been held in the /src folder? And if everyone is contained to the raylib folder...then I can freely change the directory that raylib folder inhabits? i.e. I can move it from downloads to c


text:
Q: Rails+MongoDB: Find ObjectId bigger than given value I am trying to find next (newest) document in MongoDB:
Article.find({'_id' => { "$gt" => Moped::BSON::ObjectId(id_from_database)}})

But every time I run this query, I get
Problem:
  Document(s) not found for class Article with id(s) {"_id"=>{"$gt"=>"given value"}}.

I have installed these gems:
gem 'mongoid'
gem 'bson'
gem 'bson_ext'

But still cannot find the issue... I will be grateful for each help!
Thank you

A: The following will return the next object
Article.where({:_id => {:$gt => id_from_database}}).sort({:_id=>1}).first

A: I think you want to call where instead of find which is used for getting a record by a specific id.
Article.where({'_id' => { "$gt" => Moped::BSON::ObjectId(id_from_database)}}).sort(_id: 1).first


text:
Q: currency convertion with two currencies I'm currently playing around with a currency converter and I need help on how to enable users to choose whatever currencyTo they want, just as the currencyFrom.
Currently, the conversion is only from USD (which is set to 1) and then converted into a chosen currency. How can I allow users to choose another currency than USD and it still calculates the correct rate?

/* Connecting HTML currency form with the functionality from JavaScript
We create a function to convert currencies using API and the value entered by the user.

*/
var calculate = function calculate() {

    var amount = parseFloat(document.getElementById("amount").value); // Sets the varaible amount to be connected with whatever value the user types in the amount field in HTML
    var select1 = document.getElementById("currencyTo"); // Sets the variable select1 to be connected with currencyTo in HTML
    var result = document.getElementById("result"); // Sets the variable result to be connected with result in HTML

/* The calculation for the selected rates
The calculation times the amount the user types with the currency and rate related to the currency
And defines this number equals result
*/
    var number = amount * select1.options[select1.selectedIndex].dataset.rate;
     result.value = number;
}

// The calculate function is initiated as soon as the user types a number in the amount field or change the currency, and displays the result immediately in the result field
// This element allows the user to see the immediate result without pressing a calculate button

  document.getElementById("amount").addEventListener("keyup", calculate);
  document.getElementById("currencyTo").addEventListener("change", calculate);

 /* This defines currencies and rates connected witht the specific currency
The key is the abbreviation of the currency name and the value is the rate connected to each currency*/

function callbackFunc(response){
    var currencies = response;
    var currencies_keys = Object.keys(currencies.quotes);
    var currencies_values = Object.values(currencies.quotes);

//This ensures that the user can not change the default currency in the currencyFrom field
    var currencyFrom = document.getElementById("currencyFrom");
    currencyFrom.setAttribute("disabled", "disabled");

// When define that the currencies and its values shoud go to the currencyTo field
    var currencyTo = document.getElementById("currencyTo");
    var currencySelection = "";

// Here we use a universal function to retrieve the activeUser key from LocalStorage as a string and transforms the values into JavaScript objects using JSON.parse
    var activeUser = JSON.parse(localStorage.getItem('activeUser'))

// This creates a list of all the currencies
    var currenciesList = [];

    for(i=0; i < currencies_keys.length; i++){
        if(i == 0){
            var currency = currencies_keys[i].substring(0,3); // With this substring we split the currencyFrom and currencyTo into their own strings

        }

// With this substring we split the currencyFrom and currencyTo into their own strings and define variables
// And defines that the varibale rate should inherit the values of the currenices_values, which is currencies and quotes
        var currency = currencies_keys[i].substring(3,6);
        var rate = currencies_values[i];

// Create a variable called currency object that consists of the variables currency and rate
// Push the object into the currency list
// We tell our currency converter that whatever the currency the user picks it should inherit the values of the variable currency and rate
        var currencyObject = new Currency(currency, rate);
        currenciesList.push(currencyObject);

        currencySelection += "<option value='" + currency + "' data-rate='" + rate + "'>" + currency + "</option>";
    }
//  Adding the list of currency objects to local storage and transforming the list to a string and displaying predefined currency from activeUser in currencyTo in HTML
    localStorage.setItem("currencies", JSON.stringify(currenciesList));

    currencyTo.innerHTML = currencySelection;

    currencyTo.value = activeUser.currency.name;
 }

// set endpoint and your access key
endpoint = 'live'
access_key = '7ff7413fd18c1b9652f371629bd4bb4f';

// Here we get the most recent exchange rates via the "live" endpoint:
$.ajax({
    url: 'http://apilayer.net/api/' + endpoint + '?access_key=' + access_key,
    dataType: 'jsonp',
    success: function(json) {
        callbackFunc(json);
    }
});

//Logout function - redirects to LogIn html when button is clicked
var logout = document.getElementById('logout');
logout.onclick = function() {
    document.location.href = 'login1.html';
}
<!DOCTYPE html>

    <title>Main page</title>
    <link rel="stylesheet" href="mainpage.css">
    <link rel="stylesheet" href="commentbox.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins">

Currency Converter

Currency converter

<form>

<input type="text" placeholder="Insert numbers" id="amount" value=""  style="height:40px;font-size:12pt;width:350px;">

<select id="currencyFrom"style="height:50px;font-size:14pt;width:150px">
    <option value='AED' title='United Arab Emirates Dirham'>AED</option>
   <option value='AFN' title='Afghan Afghani'>AFN</option>
   <option value='ALL' title='Albanian Lek'>ALL</option>
   <option value='AMD' title='Armenian Dram'>AMD</option>
   <option value='ANG' title='Netherlands Antillean Guilder'>ANG</option>
   <option value='AOA' title='Angolan Kwanza'>AOA</option>
   <option value='ARS' title='Argentine Peso'>ARS</option>
   <option value='AUD' title='Australian Dollar'>AUD</option>
   <option value='AWG' title='Aruban Florin'>AWG</option>
   <option value='AZN' title='Azerbaijani Manat'>AZN</option>
   <option value='BAM' title='Bosnia-Herzegovina Convertible Mark'>BAM</option>
   <option value='BBD' title='Barbadian Dollar'>BBD</option>
   <option value='BDT' title='Bangladeshi Taka'>BDT</option>
   <option value='BGN' title='Bulgarian Lev'>BGN</option>
   <option value='BHD' title='Bahraini Dinar'>BHD</option>
   <option value='BIF' title='Burundian Franc'>BIF</option>
   <option value='BMD' title='Bermudan Dollar'>BMD</option>
   <option value='BND' title='Brunei Dollar'>BND</option>
   <option value='BOB' title='Bolivian Boliviano'>BOB</option>
   <option value='BRL' title='Brazilian Real'>BRL</option>
   <option value='BSD' title='Bahamian Dollar'>BSD</option>
   <option value='BTC' title='Bitcoin'>BTC</option>
   <option value='BTN' title='Bhutanese Ngultrum'>BTN</option>
   <option value='BWP' title='Botswanan Pula'>BWP</option>
   <option value='BYN' title='Belarusian Ruble'>BYN</option>
   <option value='BYR' title='Belarusian Ruble'>BYR</option>
   <option value='BZD' title='Belize Dollar'>BZD</option>
   <option value='CAD' title='Canadian Dollar'>CAD</option>
   <option value='CDF' title='Congolese Franc'>CDF</option>
   <option value='CHF' title='Swiss Franc'>CHF</option>
   <option value='CLF' title='Chilean Unit of Account (UF)'>CLF</option>
   <option value='CLP' title='Chilean Peso'>CLP</option>
   <option value='CNY' title='Chinese Yuan'>CNY</option>
   <option value='COP' title='Colombian Peso'>COP</option>
   <option value='CRC' title='Costa Rican Colón'>CRC</option>
   <option value='CUC' title='Cuba Convertible Peso'>CRC</option>
   <option value='CUP' title='Cuban Peso'>CUP</option>
   <option value='CVE' title='Cape Verdean Escudo'>CVE</option>
   <option value='CZK' title='Czech Republic Koruna'>CZK</option>
   <option value='DJF' title='Djiboutian Franc'>DJF</option>
   <option value='DKK' title='Danish Krone'>DKK</option>
   <option value='DOP' title='Dominican Peso'>DOP</option>
   <option value='DZD' title='Algerian Dinar'>DZD</option>
   <option value='EEK' title='Estonian Kroon'>EEK</option>
   <option value='EGP' title='Egyptian Pound'>EGP</option>
   <option value='ERN' title='Eritrean Nakfa'>ERN</option>
   <option value='ETB' title='Ethiopian Birr'>ETB</option>
   <option value='EUR' title='Euro'>EUR</option>
   <option value='FJD' title='Fijian Dollar'>FJD</option>
   <option value='FKP' title='Falkland Islands Pound'>FKP</option>
   <option value='GBP' title='British Pound Sterling'>GBP</option>
   <option value='GEL' title='Georgian Lari'>GEL</option>
   <option value='GGP' title='Guernsey Pound'>GGP</option>
   <option value='GHS' title='Ghanaian Cedi'>GHS</option>
   <option value='GIP' title='Gibraltar Pound'>GIP</option>
   <option value='GMD' title='Gambian Dalasi'>GMD</option>
   <option value='GNF' title='Guinean Franc'>GNF</option>
   <option value='GTQ' title='Guatemalan Quetzal'>GTQ</option>
   <option value='GYD' title='Guyanaese Dollar'>GYD</option>
   <option value='HKD' title='Hong Kong Dollar'>HKD</option>
   <option value='HNL' title='Honduran Lempira'>HNL</option>
   <option value='HRK' title='Croatian Kuna'>HRK</option>
   <option value='HTG' title='Haitian Gourde'>HTG</option>
   <option value='HUF' title='Hungarian Forint'>HUF</option>
   <option value='IDR' title='Indonesian Rupiah'>IDR</option>
   <option value='ILS' title='Israeli New Sheqel'>ILS</option>
   <option value='IMP' title='Manx pound'>IMP</option>
   <option value='INR' title='Indian Rupee'>INR</option>
   <option value='IQD' title='Iraqi Dinar'>IQD</option>
   <option value='IRR' title='Iranian Rial'>IRR</option>
   <option value='ISK' title='Icelandic Króna'>ISK</option>
   <option value='JEP' title='Jersey Pound'>JEP</option>
   <option value='JMD' title='Jamaican Dollar'>JMD</option>
   <option value='JOD' title='Jordanian Dinar'>JOD</option>
   <option value='JPY' title='Japanese Yen'>JPY</option>
   <option value='KES' title='Kenyan Shilling'>KES</option>
   <option value='KGS' title='Kyrgystani Som'>KGS</option>
   <option value='KHR' title='Cambodian Riel'>KHR</option>
   <option value='KMF' title='Comorian Franc'>KMF</option>
   <option value='KPW' title='North Korean Won'>KPW</option>
   <option value='KRW' title='South Korean Won'>KRW</option>
   <option value='KWD' title='Kuwaiti Dinar'>KWD</option>
   <option value='KYD' title='Cayman Islands Dollar'>KYD</option>
   <option value='KZT' title='Kazakhstani Tenge'>KZT</option>
   <option value='LAK' title='Laotian Kip'>LAK</option>
   <option value='LBP' title='Lebanese Pound'>LBP</option>
   <option value='LKR' title='Sri Lankan Rupee'>LKR</option>
   <option value='LRD' title='Liberian Dollar'>LRD</option>
   <option value='LSL' title='Lesotho Loti'>LSL</option>
   <option value='LTL' title='Lithuanian Litas'>LTL</option>
   <option value='LVL' title='Latvian Lats'>LVL</option>
   <option value='LYD' title='Libyan Dinar'>LYD</option>
   <option value='MAD' title='Moroccan Dirham'>MAD</option>
   <option value='MDL' title='Moldovan Leu'>MDL</option>
   <option value='MGA' title='Malagasy Ariary'>MGA</option>
   <option value='MKD' title='Macedonian Denar'>MKD</option>
   <option value='MMK' title='Myanma Kyat'>MMK</option>
   <option value='MNT' title='Mongolian Tugrik'>MNT</option>
   <option value='MOP' title='Macanese Pataca'>MOP</option>
   <option value='MRO' title='Mauritanian Ouguiya'>MRO</option>
   <option value='MUR' title='Mauritian Rupee'>MUR</option>
   <option value='MVR' title='Maldivian Rufiyaa'>MVR</option>
   <option value='MWK' title='Malawian Kwacha'>MWK</option>
   <option value='MXN' title='Mexican Peso'>MXN</option>
   <option value='MYR' title='Malaysian Ringgit'>MYR</option>
   <option value='MZN' title='Mozambican Metical'>MZN</option>
   <option value='NAD' title='Namibian Dollar'>NAD</option>
   <option value='NGN' title='Nigerian Naira'>NGN</option>
   <option value='NIO' title='Nicaraguan Córdoba'>NIO</option>
   <option value='NOK' title='Norwegian Krone'>NOK</option>
   <option value='NPR' title='Nepalese Rupee'>NPR</option>
   <option value='NZD' title='New Zealand Dollar'>NZD</option>
   <option value='OMR' title='Omani Rial'>OMR</option>
   <option value='PAB' title='Panamanian Balboa'>PAB</option>
   <option value='PEN' title='Peruvian Nuevo Sol'>PEN</option>
   <option value='PGK' title='Papua New Guinean Kina'>PGK</option>
   <option value='PHP' title='Philippine Peso'>PHP</option>
   <option value='PKR' title='Pakistani Rupee'>PKR</option>
   <option value='PLN' title='Polish Zloty'>PLN</option>
   <option value='PYG' title='Paraguayan Guarani'>PYG</option>
   <option value='QAR' title='Qatari Rial'>QAR</option>
   <option value='RON' title='Romanian Leu'>RON</option>
   <option value='RSD' title='Serbian Dinar'>RSD</option>
   <option value='RUB' title='Russian Ruble'>RUB</option>
   <option value='RWF' title='Rwandan Franc'>RWF</option>
   <option value='SAR' title='Saudi Riyal'>SAR</option>
   <option value='SBD' title='Solomon Islands Dollar'>SBD</option>
   <option value='SCR' title='Seychellois Rupee'>SCR</option>
   <option value='SDG' title='Sudanese Pound'>SDG</option>
   <option value='SEK' title='Swedish Krona'>SEK</option>
   <option value='SGD' title='Singapore Dollar'>SGD</option>
   <option value='SHP' title='Saint Helena Pound'>SHP</option>
   <option value='SLL' title='Sierra Leonean Leone'>SLL</option>
   <option value='SOS' title='Somali Shilling'>SOS</option>
   <option value='SRD' title='Surinamese Dollar'>SRD</option>
   <option value='STD' title='São Tomé and Príncipe Dobra'>STD</option>
   <option value='SVC' title='Salvadoran Colón'>SVC</option>
   <option value='SYP' title='Syrian Pound'>SYP</option>
   <option value='SZL' title='Swazi Lilangeni'>SZL</option>
   <option value='THB' title='Thai Baht'>THB</option>
   <option value='TJS' title='Tajikistani Somoni'>TJS</option>
   <option value='TMT' title='Turkmenistani Manat'>TMT</option>
   <option value='TND' title='Tunisian Dinar'>TND</option>
   <option value='TOP' title='Tongan Pa?anga'>TOP</option>
   <option value='TRY' title='Turkish Lira'>TRY</option>
   <option value='TTD' title='Trinidad and Tobago Dollar'>TTD</option>
   <option value='TWD' title='New Taiwan Dollar'>TWD</option>
   <option value='TZS' title='Tanzanian Shilling'>TZS</option>
   <option value='UAH' title='Ukrainian Hryvnia'>UAH</option>
   <option value='UGX' title='Ugandan Shilling'>UGX</option>
   <option value='USD' title='United States Dollar'>USD</option>
   <option value='UYU' title='Uruguayan Peso'>UYU</option>
   <option value='UZS' title='Uzbekistan Som'>UZS</option>
   <option value='VEF' title='Venezuelan Bolívar'>VEF</option>
   <option value='VND' title='Vietnamese Dong'>VND</option>
   <option value='VUV' title='Vanuatu Vatu'>VUV</option>
   <option value='WST' title='Samoan Tala'>WST</option>
   <option value='XAF' title='CFA Franc BEAC'>XAF</option>
   <option value='XAG' title='Silver (troy ounce)'>XAG</option>
   <option value='XAU' title='Gold (troy ounce)'>XAU</option>
   <option value='XCD' title='East Caribbean Dollar'>XCD</option>
   <option value='XDR' title='Special Drawing Rights'>XDR</option>
   <option value='XOF' title='CFA Franc BCEAO'>XOF</option>
   <option value='XPF' title='CFP Franc'>XPF</option>
   <option value='YER' title='Yemeni Rial'>YER</option>
   <option value='ZAR' title='South African Rand'>ZAR</option>
   <option value='ZMK' title='Zambian Kwacha (pre-2013)'>ZMK</option>
   <option value='ZMW' title='Zambian Kwacha'>ZWL</option>
   <option value='ZWL' title='Zimbabwean Dollar'>ZWL</option>
</select>

<select id="currencyTo" style="height:50px;font-size:14pt;width:150px">
</select>

<input type="text" id="result" value="" style="height:40px;font-size:12pt;width:350px; background-color:lightsteelblue">

</form>

  <input
  type="button"
  value="Logout"
  name="logout"
  id="logout" />

    B
    I
    U

    Loading...

        <input type="submit" value="Comment" />

A: It's easy: If you want to calculate the rate for a currency pair (let's say XXX/YYY) but you have only USD/XXX and USD/YYY, simply invert the first (1/x) to make it XXX/USD and then multiply by the second.
For example you want GBP/EUR:

*

*You have USD/GBP = 0.771188

*You have USD/EUR = 0.848514

*Invert USD/GBP = GBP/USD = 1/0.771188 = 1.2967

*➡ GBP/EUR = GBP/USD * USD/EUR (note: USD cancels out) = 1.2967 * 0.848514 = 1.100269

If you want EUR/GBP, it's the other way round, invert USD/EUR and multiply by USD/GBP. Always make sure your "intermediate" rate (USD in that case) ends up in the middle, so it is eliminated.
With this simple trick, you can use any currency API like SWOP foreign exchange rate API to calculate rates for any base currency even in their free plan.
Disclaimer: I'm one of the programmers of SWOP ;)
A different note: Usually you should avoid including your access_key in posts - people could steal it and use up your quota.
Best regards

A: If you know USD to any currency, you can use that information to convert any currency to any other by converting to and from USD, e.g. € -> $ -> £


text:
Q: UICollectionView with Custom Layout Going Blank I have built a tv guide style application for someone that utilizes a UICollectionView with a custom UICollectionViewLayout. The custom layout uses four different custom UICollectionViewCells. I have run into a very interesting problem that has stumped me and my team. My post is quite long, but it is done that way to hopefully give you the full context. If you have the time to read and toss me your ideas. I would greatly appreciate it. As always, thanks to the SO community for all your help.
tl;dr - UICollectionView with custom layout (subclass of UICollectionViewLayout) randomly loses all data in the view. Goes completely blank. .reloadData() is called on viewDidAppear and does not fix. Stumped as to the cause.
Section 0, Item 0 is one type of cell and is kept in the top left at all times. As you scroll, the cell is moved with you and kept in the top left corner.
Section 0, Item 1-n are the second type of cell and are kept at the top at all times.
Section 1-n, Item 0-n are the "stations", another type of cell, and are kept along the left border at all times.
All other cells are the "shows" and the fourth type of cell and are mapped to a specific x,y coordinate based on time and station.
This collectionView is very performant and has allowed us to give a great user experience for the most part. However, when completely loaded up with 10 days worth of data. It uses a decent amount of memory. ~100-150MB depending on the lineup, number of stations, and length of shows. Shorter shows means more cells mapped out to the collection view.
When the app is running with a large chunk of the guide data, sometimes, the collectionView will hiccup and my floating headers will stop moving. Then ALL of my cells will disappear. We have affectionately started calling this the White Screen of Death as the entire collection is rendered empty. At this time, the scroll bars are still visible and you can see yourself scrolling around, but no cells are loaded.
We've created the problem a few times with a device connected to Xcode's debugger and have some data. The data for populating all the cells is still available from debugger. cellForItemAtIndexPath can be called from the debugger and returns a UICollectionViewCell. numberOfSections and numberOfItemsInSections still functions and shows correct numbers when printing from debugger. cellForItemAtIndexPath function is never called after collection goes empty. Breakpoint in this method will never be hit. Layout is still accessible and variables can be accessed with no problems.
Now for the things that seem abnormal, but we don't know what to do with.
collectionView.contentSize and collectionView.collectionViewLayout.contentSize are different. On a non-broke device, they are the same when looking through the debugger.
collectionView.visibleCells returns an empty array. This would technically be correct as our collection is in white screen of death mode... but we have sections and items in the sections, so not sure about that.
The problem is intermittent, but we can reproduce usually a few times an hour if we are trying hard enough. We think it's memory related, because it never happens on the simulator. Only on physical devices.
Since this is an unreleased app for a client, I've blacked out their navigational controls.

Has anyone seen a similar problem? Does anyone have any ideas for what to try next?
Last note, THANK YOU FOR READING THIS FAR! :)

A: Seeing as someone just upvoted this question, I thought I would come back and post the resolution we landed on.
Our collectionView was calling into a singleton that was managing a large amount of data for the application. The singleton was being populated in the background as the users scrolled to keep data in the view. These background updates to the singleton were all being managed via background threads running in low priority. We built the threads to update the data stores first, then update the accessor methods to know about the new data. This was our attempt at thread safety, as the accessors wouldn't know there was any other data than what already existed until after the data was done being modified. However, this did not work. More details below.
After testing extensively with multiple devices, we realized our problem showed up in a very high volume on certain days, we took this data and started analyzing the collectionView cells for the given dates, we came to find out that the days when the problem showed up regularly, there were cells that were being generated that had very large sizes, for example, a single cell in a row might span the width of 4-5 iPhones. After some searching, we found this was a common problem people had and most just downsized their cells. Our cells however are linked to times and lengths.
More research was put forth and we eventually took a swing at removing all threading. This meant that when our user hit the end of the collection, we would push a modal view that showed an activity indicator and blocked user input while the singleton was updated. This IMMEDIATELY resolved our problem.
The notes from our research:

*

*Extremely large cells, width or height, cause problems for collectionViews and extra caution should be taken.

*These large cells can make problems occur in a much higher frequency than normal, however, they did not appear to be the cause of our issue.

*Thread safety was our issue, at some point the collectionView was losing it's connection to the data source and it could not recover. We tried several remedies to relink the data source, none worked. The fix was to remove all threading.

Hope this helps!


text:
Q: How to apply the resulting removed outliers on the dataset using boxplot Good day,
I am using boxplot to remove the outliers from my dataset:
outliers <- boxplot(dataset, outline=FALSE);

Now as outliers variable has all information, how do I apply the removal on dataset? Does boxplot do that inplace?
Thank you,

A: The values that boxplot considers to be outliers are stored in outliers$out. So, assuming that your dataset contains values in a column named value, you could remove them like this:
dataset[!dataset$value %in% outliers$out, ]

or if dataset had only the one column:
dataset[!dataset$value %in% outliers$out, , drop = FALSE]

A: Can use this -
x[!x %in% boxplot.stats(x)$out]


text:
Q: Computer name not appearing on network I can connect to other computers on my home network (ubuntu + OSX machines) using the IP address, but I can't connect using the netbios name.
On the mac the name appears in Finder but if I try to connect (go>connect to server> smb://user@mythtv.local) it doesn't work, while smb://username@192.168.0.3 does. Same with ssh, ping and afp between the macs.
This is a intermittent problem. It has worked in the past.

A: Are you sure the device is using Netbios resolution? On the Mac, .local names are reserved for Bonjour resolution. Do you have an option to change the MythTV network name to something other than .local? Are both devices set to use the same Workgroup name (check the WINS tab in your Mac's Network Pane fort this setting)?

A: Are some of your machines connected wirelessly? If so, then you might have a bug where multicast isn't working reliably on some machines, breaking multicast protocols like Bonjour, and broadcast protocols like NetBIOS name service.
Make sure your multicast rate isn't set too high on your 802.11 Access Point. It has to be at a "lowest common denominator" rate; a rate low enough that all clients can receive it reliably no matter how far they are from the AP.
Also, try this test: temporarily turn off wireless security and see if the problem goes away. If it does, that's a good sign that either or AP or one or more of your clients isn't doing 802.11 multicast encryption correctly. Sometimes you can resolve this by switching from a more complex wireless security mode to a simpler one. For instance, WPA2 "Mixed Mode", where both AES-CCMP and TKIP encryption are enabled, is more complex because the multicast cipher type can be different from the unicast cipher type. Switching to pure WPA2 (AES-CCMP only) is simpler because it uses the same cipher everywhere, and as a bonus, it's more secure.