text:
Q: Can't reach the /21 VLSM IP address given to me by my ISP from the internet I'm having trouble reaching my home IP address from the internet. The ISP gave me an address with a variable length subnet mask. 97.97.200.XXX/21 to get exact without giving it all away.  My question is how can I reach it with SSH or anything useful for backing up files? Ping and traceroute give me results for the class A address as they seem to have no options for specifying subnet masks. Is there some other protocol that would allow me to reach this IP from the internet?

A: First, CIDR is a more relevant term here, and to be clear, it's not a "CIDR IP address". CIDR is merely a notation method. Additionally, don't mention classful addressing if you want to be taken seriously. :)
Second, the protocol used to communicate from one IP to another is, you guessed it, IP. If you are unable to do this, there's either a routing issue or firewall issue, or both.
Since this is a home internet circuit, it's likely that inbound connections are being restricted by your ISP or you don't have your router configured to properly handle inbound requests.


text:
Q: jquery doesn't work, can't find the right answer here My html code with the jquery link
<!DOCTYPE html>

        <meta charset="UTF-8">

        <meta name="keywords" content="bas webdesign, beverwijk, heemskerk, uitgeest, ijmuiden, velsen, noord holland, noord-holland, nederland, responsive webdesign, website bouwen, goedkoop, kwaliteit, betrouwbaar, html 5, css 3, javascript, huisstijl, huisstijlen">
        <meta name="viewport" content="width=device-width user-scalable=no">

            <meta property="og:site_name" content="www.bas-webdesign.nl"/>
            <meta property="og:title" content="Investeer in je bedrijf, investeer in een goede website!"/>
            <meta property="og:description" content="Bas webdesign maakt websites op maat voor elk budget. Jij bepaalt, Bas maakt. Advies is bij Bas een service. En service is gratis, zoals het hoort! Neem gerust contact op en kom eens op de koffie voor een vrijblijvend gesprek."/>
            <meta property="og:image" content="afb/sociaal/socialeMediaThumbnail.jpg">
            <meta property="og:url" content="http://bas-webdesign.nl/">
            <meta property="og:type" content="Webdesign"/>

            <link rel="shortcut icon" href="afb/logo/favicon.png" type="image/x-icon">
            <link rel="icon" href="afb/logo/favicon.png" type="image/x-icon">

            <link href='http://fonts.googleapis.com/css?family=Josefin+Sans:400,700' rel='stylesheet' type='text/css'>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

            <link rel="stylesheet" href="css/reset.css">
            <link rel="stylesheet" href="css/style.css">

        <title>Bas Webdesign</title>

                            websites

And here I want to start my hover function.
$( document ).ready(function() {

// globale variabelen

// globale variabelen

// functies

    // hover

        function hoverAan(onzichtbaar, zichtbaar){

            onzichtbaar.style.display = "none";
            zichtbaar.style.display = "inline";

        }

    // hover

// functies

});

The thing is... Without the jquery link and .ready() (so plain js) it does work. Is it the position of the jquery link? or is there something else I do wrong? because I want to write a lot of jquery instead of js. So I wanted to make sure it does the job from the very beginning.. and now it does not.

A: You want to keep all your JavaScript functions outside of your $(document).ready(function () {});. This way, your functions will be loaded in-line with your HTML, instead of your functions being loaded after your HTML is loaded.

redpajama_set_name: RedPajamaStackExchange


text:
Q: EventsByTag support in EventStore Am using EventStore as the ReadJournal and akka-persistence API , to build a persistent view.
The issue am facing is that i do not see the tags in the EventStore GUI after the event is persisted. Therefore, am not sure if the correct tagged event is getting persisted in the eventstore or not.
Going by http://pkaczor.blogspot.in/2015/12/akka-ddd-integrating-eventstore.html and a small test, i see that i am not able to read events persisted by tags in the eventstore through currentEventsByTag akka persistence API.
My write event adapter is mentioned below.
public class ViewEventAdapter implements WriteEventAdapter {
  @Override
  public String manifest(Object event) {
    return "";
  }

  @Override
  public Object toJournal(Object event) {
    if (event instanceof DomainEvent) {
      DomainEvent domainEvent = (DomainEvent) event;
      return tagged(domainEvent , "ViewRelated");
    }
    return event;
  }

  private Tagged tagged(Object event, String tag) {
    Set<String> tags = new HashSet<String>();
    tags.add(tag);
    return new Tagged(event, tags);
  }
}

Following is the configuration.
akka.persistence {
    journal {
        plugin = "eventstore.persistence.journal"
        event-adapters {
            tagger = "com.wt.domain.write.events.ViewEventAdapter"
        }

        event-adapter-bindings {
            "com.wt.domain.write.events.DomainEvent" = tagger
        }
    }
}

And finally the relevant piece of code where i am persisting the eventByTag.
private void handle(DomainEvent event) {
       ViewEventAdapter viewAdapter = new ViewEventAdapter();
        persist(viewAdapter.toJournal(event), evt -> {
          domainObject.update(evt);
          sender().tell("Done"), self());
        });
      }
  }

Any help in this matter is much appreciated.
There is another question on the similar lines here: Why doesn't the Akka Persisence Query Read Journal retrieve my events?


text:
Q: OpenIDConnect Session Management passing session_state from RP to OP I am implementing OIDC Session management. According to the specification 'http://openid.net/specs/openid-connect-session-1_0.html#CreatingUpdatingSessions' I need to send ' client_id + " " + session_state' from RP iFrame to the OP iFrame. I should pass a json here as the session_id which indicates the login status of the OP. In my OP I'm maintaining a cookie to store the login status. But I can't access it in the RP iFrame as accessing cookies through different domains is impossible. So how can I pass the session_state from RP to OP? Can I pass the cookie from OP to RP as a post message? Please advice me on this.
Thanks

A: The RP received the session_state value from the OP at the time of logon. To the RP this is an opaque value (which may or not be a JSON object) that just needs to be passed back to the OP in the RP iframe.
The RP communicates the session_state to the OP by by sending it from the RP iframe to the OP iframe using postMessage.
Be aware the RP creates both the RP iframe and the OP iframe. It is just that the content in the OP iframe is served by the OP and thus may access/use/process the cookie value in a way that is specific to the OP and independent of the RP and the RP iframe.


text:
Q: After grouping and sorting: Why is my python dataframe column name row, not in a single row? Firstly, I am not sure that I am doing this the best way, so alternatives appreciated!
I have a python pandas dataframe which I have created:
raw_data = {'Name' : pd.Series(['david','andrew','calvin','david','calvin','david'], index=['a', 'b', 'c', 'd','e','f']),'Age' : pd.Series([35, 40, 5, 35, 5, 35], index=['a', 'b', 'c', 'd', 'e','f'])}
df = pd.DataFrame(raw_data, columns = ['Name','Age'])
I want to now groupby and also sort (based on the frequency of the count of the occurrences of 'Name') and return the top 2 records. ie the following output:
  Name Count
david      3
calvin     2

I start by adding a "Count" column:
df = pd.DataFrame(raw_data, columns = ['Name','Age'])

Gives:
     Name   Age Count
a   david   35  3
b   andrew  39  1
c   calvin  5   2
d   david   34  3
e   calvin  5   2
f   david   35  3

I then can group and sort this with the below code:
df[['Name','Count']].groupby('Name').count().sort_values('Count',ascending=0).head(2)

This is where I have the problem, the data is "correct", but the column headers appear to be in separate rows...See the screenshot:
Column Header Alignment problem pic
I have 3 questions
1) Why does this happen?
2) How can I fix it?
3) Is there a better way to do this?
Thanks!
[EDIT] - I have answered question 2, (How to fix it). Apparently i need to reset the index:
df.reset_index()

Would love to know, why and is there a better way?

A: You can use nlargest and reset_index:
print df

#     Name  Age
#a   david   35
#b  andrew   40
#c  calvin    5
#d   david   35
#e  calvin    5
#f   david   35

df1 =  df.groupby('Name').apply(len)
print df1

#Name
#andrew    1
#calvin    2
#david     3
#dtype: int64
print df1.nlargest(2).reset_index(name='Count')

#     Name  Count
#0   david      3
#1  calvin      2


text:
Q: Datatables server-side with defered pages On a server-side table, I want to initialize a table with the first 3 pages. The deferLoading property allows you to skip the loading of the first elements, before doing a Ajax call. But I'm not being able to paginate those already loaded elements.
When you get to the page where the table is loaded, you want to display some set of results. As said, you can load the first 10 records and doing a "normal pagination", but we'd like to load the first 30 records, but still display it with 10 elements per page. If the user navigated to the second page, the data would already be loaded and the page would be displayed as-in client-side pagination. The same for the third page. If the user reached the 4th page, then it would trigger the Ajax call to get the server-side loaded data.


text:
Q: PHP table not showing even the variable are exaclty the same let me first show you guys my code:
    <?php
session_start();
include("selectDB.php");
        myconnection();
        $type="Payment";

        $loan1="201410000account-00002";
        $loan=$_GET['lid'];
        echo $loan;
        $myquery="select time,month,day,year,amount from payment,loan,account where account.transactiontype='".$type."' and account.memberid='" .$_SESSION['memberid']. "' and payment.accountid=account.accountid and payment.loanid=loan.loanid and loan.loanid='".$loan."'";
        $results=mysql_query($myquery);
        echo "
";
        echo "
Rows	Transaction Type	Amount	Time	Date
";
        $counter=0;
        $payment=0;
        while($rs=mysql_fetch_array($results))
        {
                $payment+=$rs['amount'];
                $counter+=1;
                echo"".$counter."	";
                echo"".$type."	";
                echo"".number_format($rs['amount'], 2, '.', ',')."	";
                echo"".$rs['time']."	";
                echo" ".$rs['month']."/".$rs['day']."/".$rs['year']."	";
                echo "
";

        }
        echo "
";

        $paymentformat=number_format($payment, 2, '.', ',');

        ?>

This is what it looks like:  http://s1.postimg.org/m3zo71f8f/Screen_Shot_2014_12_10_at_10_49_54_AM.pngas you can see there is a text there that says:

201410000account-00002

because of the code:
$loan=$_GET['lid'];
echo $loan;

Notice $loan variable is exactly the same this $loan1 because i directly assign the variable of $loan1 to match the contents of $_GET['lid'];
$loan1="201410000account-00002";

The weird thing is that when i change my query to this:
loan.loanid='".$loan1."'";

The table shows. I dont get it guys $loan is exaclty the same with $loan1
This is the where $_GET['lid']; comes from:

A: I guess it is the space or newline thing.
Please use var_dump() to check if $loan and $loan1 are exactly the same:
var_dump($loan);

should out put
string(22) "201410000account-00002".

I guess you might get something like
string(23) "201410000account-00002 ".

A: To trim the data change the following to trim selectedTd
$('tr').click(function(){
    selectedTd = $(this).find('td:first-child').text().trim();
});

or better yet do:
$loan = trim($_GET['lid']);


text:
Q: Button changes in 12.3 In the new 12.3 version I noticed a change in how buttons react to the Background option. For instance, take
Button["Button 1"]
Button["Button 2", Background -> RGBColor[0.5, 0.75, 0.5, 0.5]]

Not only a thick boundary is formed, but it also seems that the text is slightly off-center. Any ideas on how to fix this and simply get


text:
Q: External Hard Drive Won't Mount - MAC OSX I have a Western Digital hard drive that's about 4 or 5 years old.  It's 500 GB, USB.  I use it to backup my Mac every so often.  I had it partitioned:  1 side for full backups, and the other side for general storage of music, installers, etc.
I decided to get rid of the partition today and dump all the data.  So I opened disk utility, and hit 'erase'.  It started thinking and then disk utility crashed.  After the crash, the hard drive won't mount, however disk utility still sees the drive, but not the individual volume within.
I tried booting up Disk Warrior and no luck there either.  It has the drive as an "unknown drive". When I hit rebuild, it goes through all it steps and then stops cause of this error:
The drive "unknown" is severely damaged and DiskWarrior is unable to determine its case sensitivity
What can I do at this point?  There isn't any physical damage to the drive.  Never been dropped or anything.

A: Is there anything on the drive you still need to retrieve?  Or would running a fresh backup solve your current issues?
If nothing is on it you can't simply rerun a backup of, then forget diskwarrior and reformat the drive.  If, however, you have unique files on the drive and require them I would suggest running a long generic test using Seatools from www.seagate.com.  If it fails, it may be time to enlist a pro like myself to aid your efforts.  If it passes, I have posted a simple article nearly a year ago that explains the use of a slightly more advanced recovery program from Stellar.  It's not perfect but garners the best results of any publicly available Macintosh data recovery program I've come across in recent years.
Let me know how you make out, or reply if you have further questions.


text:
Q: Multiple CTEs with Arel I have an sql query of the following format:
 with from as (#{select * query}),
 to as (#{another select *}),
 rates as (#{yet another select *})
 select rates.* from rates, from, to
 where rates.from_id = from.id and rates.to_id = to.id

How can I convert this to Arel? I looked into Arel CTE, but there are no examples of using multiple aliases like in the query above.

A: This should do the trick:
from_table = Arel::Table.new(:from)
to_table = Arel::Table.new(:to)
rates_table = Arel::Table.new(:rates)
query = rates_table.
  join(from_table).on(rates_table[:from_id].eq(from_table[:id])).
  join(to_table).on(rates_table[:to_id].eq(to_table[:id])).
  project(rates_table[Arel.star]).
  with([
    Arel::Nodes::As.new(from_table, Arel::Nodes::SqlLiteral.new("select * query")),
    Arel::Nodes::As.new(to_table, Arel::Nodes::SqlLiteral.new("another select *")),
    Arel::Nodes::As.new(rates_table, Arel::Nodes::SqlLiteral.new("yet another select *")),
  ])
puts query.to_sql

You should replace the Arel::Nodes::SqlLiteral.new("another select *") expressions with an actual Arel query. To get the Arel query from an ActiveRecord relation, you can call .ast on it. Example: User.where(active: true).ast.


text:
Q: Drop down for Unique Values for a ArcGIS Custom Tool Can an ArcGIS Tool have a drop down field with unique values derived from a list? For example, user selects a table, the tool will then find all of the values in field X and populate a drop based on this.
I've been playing with parameters but can't get anything to work. The closest I got was is creating a drop down with the field names.


text:
Q: Finding the mean value (or rolling average) of a scattered dataset with Python I have a large two column dataset representing a scattered functional behaviour. Say for each time value (x) there exist an amount of widely spread measurement values (y). I want to get for each time value (or thinking of histograms within certain time intervals) the average of the measurement values y in there. I was searching for rolling/moving averages and spline interpolations but I'm stuck. Below is a minimal example code of what should happen:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.interpolate import UnivariateSpline

#generate testdata which usually is read in from a huge file
def testdata(x):
    return 1/(1+10.*x**2)

x = np.random.uniform(-1,1,1000)
y = testdata(x) + np.random.normal(0, 1, len(x))

#convert it to dataframes, as I usually work with them
df = pd.DataFrame(list(zip(x,y)))

#sort the x-values as they are randomly distributed in the dataset
df_new = df.sort_values(by=[0])

#show the data and how the (analytical average shhould look like)
plt.scatter(df_new[0],df_new[1],s=1)
plt.scatter(df_new[0],testdata(df_new[0]), s=1, c='r')

#try a spline - however it fails
spl = UnivariateSpline(df_new.iloc[:, 0], df_new.iloc[:, 1])
xs = np.linspace(-1, 1, 10000)
plt.plot(xs, spl(xs), 'g--', lw=3)

plt.show()

So blue is my data - red is what the averaged values should look like (in this test case I obviously know it) and green ist what the spline method would give me.
For sure someone of you knows a better method to achieve the red curve by a smart (built-in) algorithm?

A: You could round the x values then groupby to get the average.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.interpolate import UnivariateSpline

# generate testdata
def testdata(x):
    return 1/(1+10.*x**2)

# create x, y
x = np.random.uniform(-1,1,1000)
y = testdata(x) + np.random.normal(0, 1, len(x))

# convert to df and sort values inplace
df = pd.DataFrame({'x': x, 'y': y})
df.sort_values(by='x', inplace=True)

# round x values then group by to create bins
round_by = 2
bins = df.groupby(df.x.round(round_by)).mean()

# plot
fig, ax = plt.subplots()

ax.scatter(df.x, df.y, s=1)
plt.plot(bins.index, bins.y, 'g--', lw=3)

plt.show()


text:
Q: How to integrate Quill-comment with React-quill? I currently have this Code SandBox where I am trying to get React-Quill and Quill-Comment to work together so that I can let users comment on content that has been written.

Quill comment is not a react package and I am a react noob so I don't know if what I am trying to do it even possible. It appears to partially work because the toolbar add comment button registers the click event.
  let commentCallback;
  function commentAddClick(callback) {
    setOpen(true); //show the modal

    commentCallback = callback; //Appears to do nothing?
    console.log("callback :>> ", callback); //Nothing is ever in the callback
    console.log("commentAddClick");
  }

However, the callback value doesn't appear to have or do anything. When I click the add comment button in the modal:
const commentSave = () => {
    const comment = "This is a comment, forced for testing";
    commentCallback(comment);
    console.log("comment :>> ", comment);

    //let comment = $('#commentInput').val();
    commentCallback(comment);
    addCommentToList(comment, currentTimestamp);
  };

it throws an error that tells me
commentCallback is not a function

I am attempting to following the Vanilla JS example see line 68 here. I assume this problem is related to this warning message that spams on every keypress.
quill:toolbar ignoring attaching to nonexistent format comments-add
<button type="button" class="ql-comments-add"></button>

How do I resolve the warning message, and get the callback to work? Or, secondarily, is there another good commenting library that will work with Quill?
A working example in Vanilla JS can be found here:
https://github.com/nhaouari/quill-comment/tree/master/example/quill-comment-test
I'd like to replicate this in React.

A: The library you are referring to says that callback function will be null when nothing is selected in the editor. So, you need to select some text in the editor for the callback function to work.


text:
Q: embedding laravel route in js file I have a js file where I append/remove a navbar-item in the navbar depending upon the size of the screen. One of the problems I have run into is when I use this href="{{URL::to('/product1')}}" this works fine and the console it displays as href="http://localhost/devFairtex/public/product1". But when I do the same thing in javascript file like so
 var aboutUsLink = "{{URL::to('/aboutUs')}}";
 $('.navbar-nav').append('
 About Us
');

in the console it display as the actual text it does not change to the actual link it displays as href="{{URL::to('/aboutUs')}}"
I don't understand the problem. How can I overcome this problem?

A: When you access the JS file is from the public directory, it does not get parsed by the blade templating engine thus leaves your blade code {{}} as it is.
An approach to solve this is
in your view (blade file) write this code:

and in your javascript file add the following code:
$(document).ready(function(){
    $('.navbar-nav').append('
 About Us
');
});


text:
Q: Boost shared pointers C++ : shared pointer unable to free resource on release I'm running into a problem where I can't get rid of the last shared pointer and I kinda need it actually.
So what I have is a manager and some worker threads.  The manager keeps a collection of shared pointers to different resources.  A worker may ask the manager for a shared pointer to a resource.  There will always be 1 or more workers with a shared pointer to the resource.  My end goal is that when all workers are done with the resource, the resource is deleted.  However, in this scheme, the manager always maintains a shared pointer to the resource so even when no workers are hanging on to the shared pointer, the resource won't get deleted b/c the ref count should always be at least 1 since the manager is hanging onto it.  I need the manager to hang on to a shared pointer to the reference so that if any worker comes asking for a shared pointer, the manager will be able to provide it one.

edit: When the resource is created a worker already has it.  So at its creation its ref count should be two (manager has it, and a single worker has it).  When the ref count hits one (only the manager has it), I would like it to be deleted.  If the resource had already been deleted and a worker comes looking for it, the resource shall be recreated.

edit2: some code:
SomeSharedPointer Manager::getResource(String unique_id)
{ // if unique id exists, return its mapped shared pointer, if unique id doesn't exist, create the resource, assign it a shared pointer, and stick it in the map
}

class Worker
{
    SomeSharedPointer my_sp;

    Worker()
    {
       String someUniqueId = "http://blah.com"
       my_sp = Manager::getResource(someUniqueId);
       // do some work on the resource
    }

    ~Worker()
    {
        my_sp.reset(); // done with resource
    }
}

A: Why is the manager holding a shared_ptr (strong reference) to the object if it doesn't need to retain control, only pass it on? Not seeing your code, it seems like having the manager hold a weak_ptr and then pass that on to the workers, who lock it into a shared_ptr on their end. That will allow the manager to pass on references without owning one of its own.
class Worker
{
    SomeSharedPointer my_sp;

    Worker()
    {
        String someUniqueId = "http://blah.com"
        weak_ptr wp = Manager::getResource(someUniqueId);
        my_sp = wp.lock();

        // do some work on the resource
    }

    ~Worker()
    {
        //my_sp.reset(); // handled automatically, as part of how shared pointers work
    }
}

If a worker finishes and releases the resource, it will be destroyed and the manager will no longer be able to hand out references (which can be tested in getResource and reloaded). This doesn't seem quite optimal, but is part of your design, so it should work like that well.
Edit: You could also have getResource return a shared pointer, and have the manager hold the weak pointer, attempt to lock, do checking/reloading internally, and then return the shared pointer. As weak_ptrs can't be directly created, that may work somewhat better.
On the other hand, you could provide a function to compliment the one providing the workers with the pointer that releases it and does count checking in the manager.

A: Use a weak pointer in the manager and shared pointer in the workers, when a worker comes asking for the pointer create a shared pointer using the lock method.
as in  boost::shared_ptr fptr = weakfoo.lock();
if shared pointer is empty, the pointer has either been released by the last worker or has not been created yet and needs creating
I would definitely avoid any solutions that involve looking at the ref count... only pain will ensue :)

A: I think the following is key:

I need the manager to hang on to a shared pointer to the reference so that if any worker comes asking for a shared pointer, the manager will be able to provide it one.

You need to decide at which point no more workers can come asking for the shared pointer. Once you know that's the case, the master can simply reset its instance of the shared pointer, thereby releasing the reference.


text:
Q: flutter: cant access non ssl api after set proxy i need to set proxy globally in my project, i did that with flutter_socks_proxy package.
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SocksProxy.initProxy(
      proxy: 'SOCKS5 192.111.139.165:4145',
      onCreate: (client) {
        client.badCertificateCallback =
            (X509Certificate cert, String host, int port) => true;
      });

  runApp(MyApp());
}

it works but i have a problem, i can't access http (non ssl) api after set the proxy.
final url = Uri.parse('http://worldtimeapi.org/api/timezone/Europe/London');
final response = await http.get(url);
print(response.body);

this is the error
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Connection reset by peer

it works fine with https apis.

A: I think the problem is related to the allowance of Clear Text Traffic, which in this case is the HTTP, you can allow it by the following steps:
For Android:

*

*Navigate to the this file: ./android/app/src/main/AndroidManifest.xml

*In the proprites of the application tag, add this property: android:usesCleartextTraffic="true"
The final file should be something like:
<?xml version="1.0" encoding="utf-8"?>
 <manifest ...>
 <uses-permission android:name="android.permission.INTERNET" />
 <application
    ...
    android:usesCleartextTraffic="true"
    ...>
    ...
</application>
</manifest>

For IOS:

*

*Navigate to the this file: ./ios/Runner/info.plist

*Add the following key-value pair:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Note:
You may need to run flutter clean after applying the above changes to ensure that the native files compiles again with a fresh run.


text:
Q: Add 2 dictionary with tuple keys and multiple values I tried creating a 1D array of a grid point with values of x, and y as a list and then formed a dictionary to make a complete grid with some values stored w.r.t. each key (grid point x,y), in this case, (Vx, Vy,1).
I am trying to add two dictionaries but while I am using the below method dictionary is getting appended instead of getting a sum of values. I tried using the counter as well but that seems to give the error "'>' not supported between instances of 'list' and 'int'". If there is any other more efficient way to add the values of the same keys please mention it.
Edit :- For sake of simplicity, I am adding here same grid but in actuality there will be two different grids with different keys and values stored in dictionary. I wanted method to add values for same keys.
  #Define the lower and upper limits for x and y
minX = -1
maxX = 1
minY = -1
maxY = 1
#Spac=Spacing Between gridpoints
Spac = 1

cordinates = {(x,y): [] for x in np.linspace(minX, maxX, XSpac) for y in np.linspace(minY, maxY, YSpac)}
grid={(x,y): [Vx,Vy,1] for (x,y) in cordinates}
print(grid)
pprint(grid)

   for key in grid:
        if key in grid:
            grid2[key] = grid[key] + grid[key]
        else:
            pass
    print(grid2)
    pprint(grid2)

>>>grid
>>>    {(-1.0, -1.0): [1, 1, 1],
     (-1.0, 0.0): [1, 1, 1],
     (-1.0, 1.0): [1, 1, 1],
     (0.0, -1.0): [1, 1, 1],
     (0.0, 0.0): [1, 1, 1],
     (0.0, 1.0): [1, 1, 1],
     (1.0, -1.0): [1, 1, 1],
     (1.0, 0.0): [1, 1, 1],
     (1.0, 1.0): [1, 1, 1]}

  >>> grid2
  >>>   {(-1.0, -1.0): [1, 1, 1, 1, 1, 1],
         (-1.0, 0.0): [1, 1, 1, 1, 1, 1],
         (-1.0, 1.0): [1, 1, 1, 1, 1, 1],
         (0.0, -1.0): [1, 1, 1, 1, 1, 1],
         (0.0, 0.0): [1, 1, 1, 1, 1, 1],
         (0.0, 1.0): [1, 1, 1, 1, 1, 1],
         (1.0, -1.0): [1, 1, 1, 1, 1, 1],
         (1.0, 0.0): [1, 1, 1, 1, 1, 1],
         (1.0, 1.0): [1, 1, 1, 1, 1, 1]}

Desired output is
 >>>    {(-1.0, -1.0): [2, 2, 2],
     (-1.0, 0.0): [2, 2, 2],
     (-1.0, 1.0): [2, 2, 2],
     (0.0, -1.0): [2, 2, 2],
     (0.0, 0.0): [2, 2, 2],
     (0.0, 1.0): [2, 2, 2],
     (1.0, -1.0): [2, 2, 2],
     (1.0, 0.0): [2, 2, 2],
     (1.0, 1.0): [2, 2, 2]}


text:
Q: mysql check that user have more than N rows (pagination alternative) I implementing a alternative to pagination.
I have a items table, each item have user owner.
I have index on user field.
Then user open page, I want to show first 10 items of this user
order by ids desc and a "more" button if more than 10 items exist.
User can click more and next 10 rows uploaded to the bottom and so on.
What is a more efficient way to check that more then N rows exists for check if I need to render "more" button.
I think about:
select 1 from items where user_id=%s and id<min_id limit 1;

there the min_id is the minimum id of prev. page.
is more effective solution exists?

A: It may be more useful to have the order determined by some other factor than userid like date, name or something depending on the use case. The query & its syntax is not exactly clear but I understand what you are trying to achieve. Maybe this would help you to get started.
     SELECT * FROM items LIMIT 20, 10

This essentially means display 10 records starting from the 20th record. You can couple this with ORDER BY user id DESC and code logic to modify the record number according to the page number.


text:
Q: October CMS trigger form fields on multiple conditions Im using a form with several fields. When the create form view is loaded,only  a select field will be visible with other fields set to hidden. Once I change the options of the select field, specific fields regarding to the option will be visible and will be hidden. I did this using trigger event from form field options.
product_type:
    label: Choose type
    type: dropdown
    options:
        web: Web
        mobile: Mobile

title:
    label: Title
    type: text
    trigger:
        action: show
        field: product_type
        condition: value[web]

It works good but since some specific fields has to be visible for two or more select options, I could not able to apply this method. Say, for example I want the price field to appear for both the web and mobile. But I could not able to set the trigger condition with additional value. I have referred this from the documentation. https://octobercms.com/docs/ui/input-trigger . Yet its not working
price:
    label: Price
    type: text
    trigger:
        action: show
        field: product_type
        condition: value[web][mobile]

At present I have solved this problem by definig filterFields method in model.
https://octobercms.com/docs/backend/forms#filter-form-fields. Also I know how to do this in js
But what I want to know is that why the trigger condition is not  supporting multiple values. Or did I made any mistake. Or should I have to include something else ?

A: For me works like this
price:
label: Price
type: text
trigger:
    action: show
    field: product_type
    condition: value[web] | value[mobile]

A: Even this works value[web][mobile]
label: Price
type: text
trigger:
    action: show
    field: product_type
    condition: value[web][mobile]

but not with the current version of october-min.js because some part of the js has been deprecated. I have identified this by viewing the pagesource of the js file from the documentation
https://octobercms.com/docs/ui/input-trigger. In this documentation it is mentioned that it is possible and it also works with the example which is provided over there. So replace the trigger condition function defined in the local js file with the trigger condition function defined in the documentation js file . In local, the js file is located in modules\backend\assets\js\october-min.js. When you view the page source you could find the iframe; view the pagesource of the iframe and get the js file. Or else you could get the trigger condition function from http://kopy.io/tyehc.
But remember this is only to tell that trigger condition for multiple values is possible, I still dont know why it is not working with the installed october-min.js, may be the October CMS team could be working on it and they might announce an official updation.


text:
Q: Google Analytics 4 API Error with R - Request failed 500 - with a specific query, other queries work as intended I'm trying to query the product sold the last week froma GA4 property with googleAnalyticsR package.
I can run multiple queries for other metrics and dimensions but I keep getting an error for this specific query:
top_products_sold_last_week <- googleAnalyticsR::ga_data(property_id,
                                                   date_range = c(last_monday, last_sunday),
                                                   metrics = c("itemPurchaseQuantity", "itemRevenue", "averagePurchaseRevenue"),
                                                   dimensions = c("nthWeek", "itemId"),limit = -1)

Request failed [500]. Retrying in 1.8 seconds...
Request failed [500]. Retrying in 2.4 seconds...
i 2022-08-08 10:43:33 > Request Status Code:  500
i 2022-08-08 10:43:33 > Trying again:  1  of  1
i 2022-08-08 10:43:36 > All attempts failed.
Error in `abort_http()`:
! http_500 Internal error encountered.

last_monday and last sunday are dynamically generated and are both correct since in the other queries I get a correct response from the api.
I tried to manually query with the Query Explorer and I get a correct response, what am I missing?
This is the JSON request from the Query Explorer
{"dimensions":[{"name":"itemId"},{"name":"nthWeek"}],"metrics":[{"name":"averagePurchaseRevenue"},{"name":"itemPurchaseQuantity"},{"name":"itemRevenue"}],"dateRanges":[{"startDate":"2022-08-01","endDate":"2022-08-07"}]}

A: It does seem like a bug as I can replicate it, could you raise an issue on the project GitHub page? https://github.com/MarkEdmondson1234/googleAnalyticsR/issues
You can still progress if you have valid JSON by using the raw_json parameter with your request e.g.
raw <- '{"dimensions":[{"name":"itemId"},{"name":"nthWeek"}],"metrics":[{"name":"averagePurchaseRevenue"},{"name":"itemPurchaseQuantity"},{"name":"itemRevenue"}],"dateRanges":[{"startDate":"2022-08-01","endDate":"2022-08-07"}]}
'

ga_data(propertyId = propety_id, raw_json = raw)
# Making API request with raw JSON:  {"dimensions":[{"name":"itemId"},{"name":"nthWeek"}],"metric ...

# # A tibble: 10,000 × 5
   itemId  nthWeek averagePurchaseRevenue itemPurchaseQuantity itemRevenue
   <chr>   <chr>                    <dbl>                <dbl>       <dbl>
 1 5016395 0000                    15177.                    2      3390.
 2 5048751 0000                     9378.                   44      8798.


text:
Q: Migrating a GitLab repository with large files into GitHub while maintaining both upstreams I have access to a GitLab repository that I need to migrate into GitHub. I need to be able to pull changes from the GitLab repository and push those to GitHub, while still working on the GitHub repository in a different new branch.
So, I pulled the repo from GitLab, added my GitHub remote upstream, created a new branch and tried to push the new branch to GitHub.
The problem is, they pushed a node_modules.zip (in a subfolder) on one of the earliest commits into the GitLab upstream and this file is over 200MB in size.
I know that I need Git LFS to support those files, but since the files are already in the history of the GitLab upstream, I cannot migrate to Git LFS without losing the upstream, I think. I was thinking about just getting rid about those files, because I don't need need files that I can get with npm i real quick.
Since I don't need the master branch on GitHub at all, I was hoping to rewrite the history on my new branch, but I have problems to figure out how this can be done.
The very important part is that I am able to pull new commits from GitLab, merge them to my own branch and push my own branch to GitHub.
Is this possible? If so, how?

A: History, in any Git repository, is nothing more or less than the set of commits in that repository (as found by starting from some branch names, tag names, and/or other names and working backwards, the way Git does in general).  Commits themselves hold full snapshots of every file, plus metadata; the metadata hold the hash IDs of previous commits; and the resulting chains of commits form Merkle trees which guarantee the validity of the commits.

The problem is, they pushed a node_modules.zip (in a subfolder) on one of the earliest commits into the GitLab upstream and this file is over 200MB in size.

Which of course exceeds the GitHub maximum size.  So this commit cannot be sent to GitHub.

Since I don't need the master branch at all, I was hoping to rewrite the history on my new branch, but I have problems to figure out how this can be done.

The rewrite is not difficult (use a tool such as filter-branch, filter-repo, or the BFG).  But once the rewrite is done, this is a completely new chain of commits: a different Merkle tree.  It is a different history.  It can be used with itself, but if it is combined with the original history, what you now have is a tree that requires both histories to be valid and complete.

The very important part is that I am able to pull new commits from GitLab, merge them to my own branch and push my own branch to GitHub.

The short version of all of this is "you can't".
The longer version is that you can, but only by maintaining a parallel history and never combining your history with their history.  This is messy, ugly, painful, and difficult or impossible to automate.  There are as far as I know no tools for doing this.  You use one repository (e.g., on your own machine) that has both histories in it, and another (on GitHub) that has only your rewritten history.  When they have new commits, you cherry-pick them to your own history.  How you keep track of which commits are new-to-your-history is up to you: this is where a tool would come in handy.  Such tools might exist, or you could write one.  A barely-adequate one is probably not hard to write, but a good one would be hard.


text:
Q: Show Grid in XtraTreeList on a specified Node How do I show XtraGrid  Control in XtraTreeList on specific Node  during TreeBuilding ?

A: It is impossible to show an XtraGrid in a TreeList node.  Currently, this can be done in ASP.NET only...


text:
Q: SNMP Bandwidth Monitoring - Billion Router I have several sites around the country, all sites are using the Billiion BiPAC 7402GX router.
I need to setup bandwidth monitoring tools to allow me to see the sites visitied, amount of bandwith up and down, traffic volume over specific ports etc.
If possible, I would like them to send me daily emails containing the reports.
If that is not possible, I am happy to setup a centailized server that the individual sites can publish their reports to.
Is there such a tool like this?
Thanks
Ian

A: Maybe have a look at Cacti, the PHP SNMP monitoring web tool, which could simply management of several devices and corresponding graphs/reports.
In terms of customising a template for the router you're using have a look at this forum posting to get ideas.

A: Given that particular broadband router supports SNMP v3 MIB-I/II you could script something to give you some of what you're looking for.
That said I'm not sure that the router, in particular that level of router, is where you should be doing that kind of work; traditionally you'd measure those metrics from a proxy or firewall - they're built to do that sort of thing.
Oh and if you do choose to go for this via the router be aware that the reporting data itself will be counted in the information the router is handling so remember to discount it or it'll throw your stats.

A: Instead of using snmp, you might get more information out of netflows.  If your device can't generate netflows, you can generate your own if you can port-mirror the interesting interface on your router (presumably, the inside or trust interface).
Here are my notes on installing fprobe and nfsen, which in this configuration generates and then analyzes netflow information.
However you still won't be able to get specific target URL information out of this configuration.  For that you need a proxy or some software that reads the network stream and can pick URLs out of the passing requests.  (If anyone knows of such software, I would be very interested in hearing about it!)


text:
Q: Kotlin distinctBy with condition I have array with multiple objects with the same key, Other objects have empty values and I was hoping to use distinctBy to remove duplicates and get objects which values has the longest string.
data class ObjA(val key: String, val value: String)

fun test() {
    val listOfA = mutableListOf(
            ObjA("one", ""), //This will be taken in distinctBy.
            ObjA("one", "o"),
            ObjA("one", "on"),
            ObjA("one", "one"), //This will be ignored in distinctBy. I WANT THIS ONE.

            ObjA("two", ""), //This will be returned in distinctBy
            ObjA("two", "2"),
            ObjA("two", "two"), //But I want this.

            ObjA("three", "3"),
            ObjA("four", "4"),
            ObjA("five", "five")
    )

    val listOfAWithNoDuplicates = listOfA.distinctBy { it.key }

    for (o in listOfAWithNoDuplicates) {
        println("key: ${o.key}, value: ${o.value}")
    }
}

Output
key: one, value:
key: two, value:
key: three, value: 3
key: four, value: 4
key: five, value: five

How to make this work. Any help will be appreciated.

A: As distinctBy just returns the distinct keys based on your selector (and in the order of the list), you end up with unique keys, but not yet with the values you want.
For that particular use-case I would probably just sort beforehand, followed by the distinctBy
listOfA.sortedByDescending { it.value.length }
       .distinctBy { it.key }

Which creates a new list at sortedByDescending or you just sort the current list beforehand (sortByDescending) and apply distinctBy later on, e.g.:
listOfA.sortByDescending { it.value.length }
listOfA.distinctBy { it.key }

In both cases you get a new List<ObjA> with the expected values.
Several other variants come to my mind as well. All those variants will put the results into a Map<String, ObjA> where the key is actually the unique ObjA.key. You may want to call .values directly if you are not interested in the key/ObjA-mapping.

*

*variant using groupingBy and reduce:
listOfA.groupingBy { it.key }
       .reduce { _, acc, e->
         maxOf(e, acc, compareBy { it.value.length })
       }

*variant using a plain forEach/for and filling its own Map:
val map = mutableMapOf<String, ObjA>()
listOfA.forEach {
    map.merge(it.key, it) { t, u ->
        maxOf(t, u, compareBy { it.value.length })
    }
}

*variant using fold and merge (very similar to the previous... just using fold instead of for/forEach):
listOfA.fold(mutableMapOf<String, ObjA>()) { acc, objA ->
  acc.apply {
    merge(objA.key, objA) { t, u ->
      maxOf(t, u, compareBy { it.value.length })
    }
  }
}

*variant using groupBy followed by mapValues (but you are then actually creating 1 map which you discard immediately):
listOfA.groupBy { it.key } // the map created at this step is discarded and all the values are remapped in the next step
       .mapValues { (_, values) ->
          values.maxBy { it.value.length }!!
       }

A: You can use maxBy{} like:
val x = listOfAWithNoDuplicates.maxBy { it.key.length }
println(x)

Output
ObjA(key=three, value=3)


text:
Q: Rotate div 90 degrees and position fixed in the upper left corner This is what I'm trying to accomplish:

I want to have a navigation that will be rotated 90 deegres and fixed to the upper left corner of the window.
HTML:

lasange

spaghetti

CSS:
.outer {
    position: fixed;
    left: 20px;
    top: 20px;
    background: red;
}

.inner {
    -webkit-transform: rotate(-90deg);
    transform-origin: 0 0;
    background: green;
}

I can't get it to look like in the image above. The problem is with the rotation. The inner div is positioned and then rotated, and as a result ends up outside the outer div. No matter what I put as the origin of the transformation it doesn't work the way I want it to. I've tried positioning the inner div with position: absolute but with no luck. I don't know the height/width parameters of the menu list.
Here's a fiddle: https://jsfiddle.net/949cjcnq/7/
Any help would be greatly appreciated.
Best regards,
Paul

A: So I manage to position it the way you want, no matter how big your content is using position: absolute; for your .inner-div.
The only drawback is that your text is facing downwards and not upwards. Couldn't get around that issue with my CSS :S
If you -webkit-transform: rotate(180deg); the child of .inner you can turn the text the right way up :)

.outer {
  position: fixed;
  left: 20px;
  top: 20px;
  background: red;
}

.inner {
  position: absolute;
  bottom: 100%;
  -webkit-transform: rotateZ(90deg);
  transform-origin: 0 100%;
  background: #AACAD7;
  white-space: nowrap;;
}
.rotate {
  -webkit-transform: rotate(180deg);
}
ul { list-style: none; padding: 0; margin: 0; white-space: nowrap; }
ul li { padding: 5px 10px; }

lasange | spaghetti

A: I think what you want to do is move the rotation from the inner to the outer class. Your css should look like this:
.outer {
    -webkit-transform: rotate(-90deg);
    position: fixed;
    left: 20px;
    top: 80px;
    background: red;
}

.inner {
    background: green;
}

To make the text appear side by side after rotation, using a table would work better than using a list:

                lasange
                 |
                spaghetti

Working Fiddle: https://jsfiddle.net/949cjcnq/12/

A: Despite what you chose for the angle or rotation unfortunately you cannot do this without knowing the width of your item, as such I don't think it can be done in pure CSS/CSS3 without an expanded framework. As such to solve this you will need to use some JavaScript and get the computed width of the element and change the transformation appropriately:
var inner = document.querySelectorAll('.inner')[0];
var width = inner.offsetWidth;
inner.style.transform = "translateY("+width+"px) rotate(-90deg)";

Keep transform-origin: 0 0 as it will have the top of the element to the edge of the screen. Then we simply need to translate in the Y direction by the width, this will place the element in the left corner:
Fiddle Example

A: In the below snippet you will see that I removed the outer and inner html and just rotated the entire UL -90deg. The result is your example image. Further proper styling is up to you  ;-)
See snippet for comments:

/* {outline: 1px dotted red } /* for debugging */

ul, li { list-style-type: none; padding: 0; margin: 0 }

ul { height: 1; /* 1 x line-height */
    position: relative;
    float: left;
    padding: 0 6px;

    /* would be regular without transform */
    top: 20px; left: 20px;

    /* but transform-origin now pivots around
    top-right so UL element gets moved right.
    So left position needs correction:
    left = -1 x (total width of LI's + line-height + UL margin-LR + UL padding-LR) + wanted-left-margin */
    top: 20px; left: -134px; /* (optically estimated) */
}

li {
    display: inline; /* result is horizontal menu */
}

.list {
    transform: rotate(-90deg); /* removed -webkit-*/
    transform-origin: top right;
    background: #acc9d7;
}

lasange |

spaghetti

A: You can add a translateX(-100%) to  your transform, that will set it where you want

.outer {
    position: fixed;
    left: 20px;
    top: 20px;
    background: red;
}

.inner {
    -webkit-transform: rotate(-90deg) translateX(-100%);
    transform: rotate(-90deg) translateX(-100%);
    transform-origin: 0 0;
    background: green;
}

.list {
  margin-top: 0px;
}

lasange

spaghetti


text:
Q: How to retrieve numbers from NSString I have a NSString which looks like this @"1, 5, 23, 15, 6". What i need is to retrieve all these numbers from this string. Probably the result might look like an array of NSStrings - @"1" , @"5", @"23" and so on. How do i do that?

A: NSString *string = @"1, 5, 23, 15, 6";
NSArray *chunks = [string componentsSeparatedByString: @", "];


text:
Q: Does an http post to a guest site count toward API limits? I'm using a Twilio Studio Flow in conjunction with Salesforce. The flow makes an HTTP POST to a remote site set up on the org. (An apex class receives the data and fires a platform event, returning no data.)
The endpoint is https://[domain].sandbox.my.salesforce-sites.com/twilio/services/apexrest/.
The apex class handling the inbound data is this:
@RestResource(urlMapping='/InboundTwilioService/*')
global without sharing class InboundTwilioService {
  //parses inbound data, fires platform event, no dml

}

Is this considered an api call to Salesforce? Will it affect our api call limits?

A: Your example is an inbound Apex REST service and is governed by this bit of the APEX REST doc

Governor Limits
Calls to Apex REST classes count against the organization's API governor limits. All standard Apex governor limits apply to Apex REST classes. For example, the maximum request or response size is 6 MB for synchronous Apex or 12 MB for asynchronous Apex

So, yes, the call counts against your org's API call limits


text:
Q: How to convert cells in a pandas data frame with multiple values to multiple rows? I am facing an issue while developing a piece of code for the below function. I have a dataframe with the below values

Date
Name
UserId
task
Client
duration

1/2/2022
'Alex, J'
101
'C'
QAT
8

2/2/2022
'Alex, J'
101
'C'
QAT
8

1/2/2022
'Marc, B' 'Marc, B'
102 102
'A' 'B'
App Dev
8

2/2/2022
'Marc, B' 'Marc, B'
102 102
'A' 'B'
App Dev
8

Now, I want to convert to the below dataframe.

Date
Name
UserId
task
Client
duration

1/2/2022
'Alex, J'
101
'C'
QAT
8

2/2/2022
'Alex, J'
101
'A'
QAT
8

1/2/2022
'Marc, B'
102
'A'
App
4

1/2/2022
'Marc, B'
102
'B'
Dev
4

2/2/2022
'Marc, B'
102
'A'
App
4

2/2/2022
'Marc, B'
102
'B'
Dev
4

I want to separate out the values in Name, UserId, task and Client column and want to divide the duration by the number of tasks for a particular day.
For example, I had 2 tasks here i.e A and B for the same day(1/2/2022). So i divided the duration of 8 by 2 and got 4 for each A and B.
I would request you to please help me in this. Thanks alot.

A: The key here is to convert your string in each row to list and then use explode:
# Sample data:
df = pd.DataFrame({'user':['102 102', '103 103'],
                   'task':["'A' 'B'", "'A' 'B'"],
                   'duration':[8, 8]})

# Convert to list
df['user'] = df['user'].str.split(' ')
df['task'] = df['task'].str.split(' ')

# Split row to multiple rows base on list
df.explode(['user', 'task'])

df

If your string is more complicated to separated, consider using import re. Or you can view it here: How to group by columns and merge only the unique strings of another column which are separated by a delimiter?
I think the rest is easy and you can do it well


text:
Q: Create class at runtime, serilize and de-serilize then cast to Interface froblem Hi,
I have the following code :
public static object CreateTypedReport(string typeName, string inheritFrom)
{
    DirectoryInfo dirInfo;
    CSharpCodeProvider c = new CSharpCodeProvider();
    CompilerParameters cp = new CompilerParameters();

    foreach (Assembly asm in System.AppDomain.CurrentDomain.GetAssemblies())
    {
        if(!asm.FullName.StartsWith("ReportAssembly, Version=0.0.0.0"))
            cp.ReferencedAssemblies.Add(asm.Location);
    }

    cp.CompilerOptions = "/t:library";
    cp.GenerateInMemory = true;

    dirInfo = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\MyApp\\ReportAssemblies\\");

    if (!dirInfo.Exists)
        dirInfo.Create();

    cp.OutputAssembly = dirInfo.FullName + typeName + "Assembly";
    cp.ReferencedAssemblies.Add(typeof(XtraReport).Assembly.Location);

    //cp.OutputAssembly = typeName + "Assembly";

    StringBuilder sb = new StringBuilder("");

    sb.Append("using System;\n");
    sb.Append("using MyNamespace.UI;\n");

    sb.Append("namespace TypedReports { \n");
    sb.Append("public class " + typeName + " : " + inheritFrom + "{ \n");
    sb.Append("} \n");
    sb.Append("}\n");

    CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());

    if (cr.Errors.Count > 0)
    {
        MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText, "Error evaluating cs code", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return null;
    }

    return cr.CompiledAssembly.CreateInstance("TypedReports." + typeName);
}

This will create a class based on the typeName and inheritFrom parameters and then finally an object will be created and returned. inheritFrom will point at a class that implements IMyInterface.
It's possible to cast this object to a IMyInterface if it's needed.
When we then serialize and de-serialize this object we will not be able to cast it to IMyInterface anymore?
Why? And how could I solve it?

A: The problem was in the serialization och deserialization of the object. When this was changed it worked great. The solution is in a third party product so I can´t post it here.


text:
Q: custom Hover CSS style on caldera forms I am trying to add custom css style to my caldera forms on a wordpress website.
what i am trying to achieve is to add a hover style to my fields of radio checklist
Right now i was only able to add style to the bullets ,I am currently stuck with adding a hover style to the fields
this is the link to the form
https://purdywordy.com/order-here/
This is the CSS that i have used
.caldera-grid input[type=checkbox]:hover,
.caldera-grid input[type=radio]:hover {
    cursor: pointer;
}
input[type=radio]:before,
input[type=checkbox]:before {
    font-family: FontAwesome !important;
    font-size: px;
}
input[type=radio]:before {
    content: '\f111';
    border-radius: 50%;
    padding: 0px 15px 0px 0px;
}
input[type=checkbox]:before {
    content: '\f14a';
    color: red;
    background: red;
    border-radius: 3px;
    padding: 2px;
}
input[type=radio]:checked:before {
    color: red;
}

A: When inspected, your form (HTML) is structured like this:
<div class="radio">
  <label>
    <input type="radio">
  </label>
</div>

Since you have used nested input inside of a label, you don't even need for/id attributes, but I am guessing that is automatically generated by the form. Btw, do you have control over the structure of HTML or the proposed form simply spits it out?
For your current structure, you could style it like this:
.radio:hover > label {
  /* add the style for the label */
}

.radio:hover input[type="radio"] {
  /* add the style for the radio button */
}

Whatever you need to apply the style to, "listen" for a hover on the parent and then target its direct children. You get the point.
EDIT: My bad. I have said that input is nested inside of label. Therefore, radio:hover > input will not target it. Omit the > and it will target any input inside div with the class .radio. Sorry for the possible confusion. You can learn more about CSS selectors and differences between them here.

A: This should work. Your radio buttons and labels sit inside a class of 'radio'. You can remove the .form-group reference here unless there are other places on the page that you don't want this styling to apply to.
.form-group .radio:hover {
   cursor: pointer;
   background-color: grey;
   border: 2px solid blue;
   border-radius: 5px;
   // other hover properties
}


text:
Q: SQL Server Circle I'm trying to create a circle in a SQL Server based on a midpoint and a radius.
This seems to be close as a solution, but it creates an oval or an ellipse vs a circle. Is there another way to create a circle?
DECLARE @g geometry;
SET @g = geometry::STGeomFromText('POINT(-88.0 44.5)', 4326);
select @g.BufferWithTolerance(5, .01, 1)

I'm currently using SQL Server 2008.
This code also demonstrates the problem. The spatial results look like a circle, but when I draw the circle on google maps it is oval. Also, when I use STContains to see what points are in the circle, it is definitely following the oval outline.
IF EXISTS (SELECT * FROM [tempdb].[sys].[objects] WHERE [name] = N'##circle')
    DROP TABLE ##circle;

CREATE TABLE ##circle
(
    [Polygon] [geometry] NOT NULL
)

DECLARE @g geometry;
SET @g = geometry::STGeomFromText('POINT(-88.0 44.5)', 4326);

insert into ##circle (Polygon)
values (@g.BufferWithTolerance(.5,.01,1))

select Polygon from ##circle

A: Your problem is that you draw a circle in geographical coordinates. Google Maps is using web mercator projection https://en.wikipedia.org/wiki/Web_Mercator, so that your circle is going to be an oval. If you want to make something that looks like circle in Google Maps, you must make it in a data set with the web mercator projection. (I am deliberately saying "looks like a circle" since if you Project it to another system, e.g. utm for a large scale map, it may end up as an oval again.)
the epsg code for web_mercator is 3857, so if you project your x and y coordinates to web_mercator
DECLARE @g geometry;
SET @g = geometry::STGeomFromText('POINT(-9796115.18981 5543147.20386)', 3857);
SELECT @g.BufferWithTolerance(5, .01, 1)

Should work (just input the -9796... 5543... Are the web_mercator coordinates for your geographical X and Y)
It seems like you need to use SQL server spatial Tools (https://gis.stackexchange.com/questions/2723/is-it-possible-to-reproject-spatial-data-using-sql-server) or an external tool to do the reprojection. If you have just a few Points, http://cs2cs.mygeodata.eu/ may be useful.


text:
Q: Does ayone know how to replace space with nothing at all in notepad++? I want to replace " " with "" (nothing) on notepad++ .
does anyone know how I can do this?
see the example below.
from:
a b c d
to abcd

A: Ctrl+H
Set 'Find What' to [press the space bar], then set Replace with to blank [delete everything out]
Click Replace All


text:
Q: Iterating List in Map and create new map in java8 I am trying to implement below code in Stream in java8.  Not getting right implementation in stream. Is it possible to optimize below code using stream
MySampleObject
    field1;
    field2;

 Map<String, List<MySampleObject>>  dbMap = new HashMap<>();
  Map<String, String>  finalMap = new HashMap<>();
            for (Entry<String, List<MySampleObject>> mapid : dbMap.entrySet()) {
                List<MySampleObject> sampleList = mapid.getValue();
                for(MySampleObject obj : sampleList) {
                    try {
                        if (null != obj.getField1() ) {
                            finalMap.put(obj.getField1+"_"+obj.getField2, obj.getField1());
                        } else {
                            ..
                        }

                    } catch ( Exception e) {
                    }
                }
            }

A: You could use the flatMap function like
dbMap.values().stream().flatMap(Collection::stream).forEach(obj -> {
  try {
    if (null != obj.getField1()) {
      finalMap.put(obj.getField1() + "_" + obj.getField2(), obj.getField1());
    } else {
       ..
    }
  } catch (Exception e) {
  }
});


text:
Q: Selenium button submit /click is not redirecting to success page from chrome web driver I am facing issues with Selenium when navigating from one page to another.
Below is the code. If I click on following element a jQuery image will open until the next page gets loaded. But it's not navigating to next page itself. The image keeps on rotating and window will close that. Why?
I am getting a NoSuchElementFoundException
Chrome Version : 58.0.3029.110
driver.findElement(By.name("continue")).click();
@Test
public void executeLoginApp() throws InterruptedException {
    driver.navigate()
            .to("url with login application");
    WebElement userName = driver.findElement(By.id("uname"));
    WebElement pwd = driver.findElement(By.id("passwd"));
    userName.sendKeys("test");
    pwd.sendKeys("test");
    Thread.sleep(2000);

    javaScriptExecutor.executeScript("window.scrollTo(0, document.body.scrollHeight)");
    Thread.sleep(2000);
    //driver.findElement(By.xpath("//input[@name='continue']")).click();
    //Thread.sleep(1000);
    //driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
     driver.findElement(By.name("continue")).click();
    //signOn.click();
        callYourInformation();
}

private void callYourInformation() {
    /*try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {

        e.printStackTrace();
    }
    WebDriverWait wait = new WebDriverWait(driver, 10);
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    String previousURL = driver.getCurrentUrl();
    ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }};
        wait.until(e);}*/
       // currentURL = driver.getCurrentUrl();
    if (driver.getCurrentUrl().contains("yourinfo")) {
        // testing yourinfo page
        WebElement emailAddress = driver.findElement(By.id("emailAddress"));
        emailAddress.clear();
        emailAddress.sendKeys("selenium@wwwmail.com");
        WebElement addressLine1 = driver.findElement(By.id("addressLine1"));
        addressLine1.clear();
        addressLine1.sendKeys("New york");
        WebElement grossAnnualIncome = driver.findElement(By.id("grossAnnualIncome"));
        grossAnnualIncome.sendKeys(String.valueOf(6000));
                    WebElement submit = driver.findElement(By.id("submitApplication"));
        submit.click();
        driver.findElement(By.id("Continue")).click();
    }
     else{
     do other logic.
     }

I tried all the ways but no luck. Commented lines are my tries but none of them redirects to that page.


text:
Q: How to upload files to the "SuiteScripts" folder from Netsuite IDE (Eclipse) I am fairly new to NetSuite and NetSuite scripting. My company has several dozen script files already in the NetSuite File Cabinet, under the default SuiteScripts folder. Also, I am using the SuiteCloud IDE, which is just basically Eclipse with a NetSuite plugin. This way I can download all of the scripts into a single SuiteCloud IDE project, work on them locally, and then upload them back to the server for testing.
When you create a new NetSuite project, one of the project settings is File Cabinet Folder. This defaults to a subdirectory  under "SuiteScripts" with the same name as your project. For example, if your project is called "MyScripts", the default will be SuiteScripts/MyScripts. You can of course change this, but it is impossible to just specify the SuiteScripts folder alone, as I get an error saying "File Cabinet folder must have 2 segments." However, the existing scripts all live under SuiteScripts (no subdirectory). Any file that I upload to the server, whether it be a new file that I created locally or even a previously downloaded file that already exists in the File Cabinet, will end up in SuiteScripts/MyScripts. This can be hugely problematic, causing dupes and all kinds of other nastiness. Anyone have any experience with this? Thanks.

A: Yes, NetSuite has decided to limit the uploading functionality to subfolders of SuiteScripts. If I had to guess, their intention there is to force you to place your scripting projects in their own folders so that the SuiteScripts folder itself does not get cluttered with scripts.
You can specify a subfolder of SuiteScripts with any name; it does not have to be the name of your Eclipse project. You have a couple options, depending on how you want your files to be organized in Eclipse and in the File Cabinet.
The way we typically do it is to create a single folder that will house all of our scripts, call it SuiteScripts/Projects/. In the file cabinet, we create this Projects folder under SuiteScripts. In Eclipse's NetSuite Project Settings, we map our Eclipse project to SuiteScripts/Projects. In our Eclipse project, we group related source files logically into folders, like iPad Integration or Approval Process. Then we upload to the File Cabinet, and now we have a nice folder structure of organized scripts, something like:
SuiteScripts
    Projects
        iPad Application
            iPadScript.js
            iPadRESTlet.js
        Approval Process
            SalesOrderApproval.js
            PurchaseOrderApproval.js

We have much more detailed naming standards for our files, but you get the picture.
My recommendation is to create a new folder in your SuiteScripts folder and move all existing scripts into there using the File Cabinet's "Move" button. Then, map your SuiteCloud Project to that new folder and upload/download as needed.

A: I agree with the erictgrubaugh's solution and I've been following stoic software's tutorials. But steavepoll if you want to change it for only one script then you can follow these steps:

*

*Create new SuiteCloud Project under the same folder which you are targeting

*Edit into mainfest.xml file(right click->NetSuite->Add Dependency References to Manifest)

*Validate Project against Account

*Deploy

It worked in my case


text:
Q: MySQL - Find Missing Data I'm trying to list every occurrence of missing data, from a table which should contain 24 rows of data (one for each hour) for every day. From the following example:
Datetime
2015-05-01 00:00:00
2015-05-01 01:00:00
2015-05-01 02:00:00
2015-05-01 03:00:00
2015-05-01 07:00:00
2015-05-01 08:00:00
2015-05-01 09:00:00
...

I would like to return:
Datetime
2015-05-01 04:00:00
2015-05-01 05:00:00
2015-05-01 06:00:00

I can return the first hour and the last hour of missing data like this:
SELECT t1.datetime AS `from`, t2.datetime AS `to`
FROM test.table AS t1
JOIN test.table AS t2
  ON t1.datetime < t2.datetime
LEFT JOIN test.table AS t3
  ON t3.datetime > t1.datetime
   AND t3.datetime < t2.datetime
WHERE t3.datetime IS NULL
  AND t2.datetime > DATE_ADD(t1.datetime, INTERVAL 60 MINUTE)
ORDER BY t1.datetime;

But this is as far as Google has been able to get me.
Any help really appreciated.

A: You need to create a temporary table with all the hours then join temporary table and the table holding the real data.
SELECT temp_table.datetime AS MissingDT
FROM temp_table
LEFT JOIN data_table ON temp_table.datetime = data_table.datetime
WHERE data_table.datetime IS NULL;

DATA_TABLE = Table that holds real data
TEMP_TABLE = Table that holds dummy data - i.e. all the hours


text:
Q: Python + Regex + CSV + Pandas : failed to produce numeric values from alpha-numeric values I am fetching data from a multisheet xlsx file and storing data in separate csv files. The first rows of all the sheets in xslx are stored in the first csv, the 2nd rows of all the sheets are stored in the 2nd csv, and, so on. Now sometimes any of the cells of 3rd to 10th columns contains alpha numeric values like this '1 pkt'. I need to make these values numeric only, like '1' so that I can feed these values to a ML model to predict something. For that purpose I wrote a code:
xls = xlrd.open_workbook(r'Smallys ORDER.xlsx', on_demand=True)
df_list = []

names = xls.sheet_names()
names.remove('EVENT')

for i in range(191):
    rows = []
    for name in names:
        count = 0
        prod = pd.read_excel('Smallys ORDER.xlsx', name, index_col=None, header=0)
        prod['date'] = name
        prod.fillna(0, inplace=True)
        try:
            item = prod.iloc[i]
            item[3] = re.split('[a-z]+', item[3])[0]
            print(item[3])
            '''item[4] = item[4].split(sep, 1)[0]
            item[5] = item[5].split(sep, 1)[0]
            item[6] = item[6].split(sep, 1)[0]
            item[7] = item[7].split(sep, 1)[0]
            item[8] = item[8].split(sep, 1)[0]
            item[9] = item[9].split(sep, 1)[0]
            item[10] = item[10].split(sep, 1)[0]'''

            rows.append(item)

        except:
            print('Row finished !!!')

    writer = csv.writer(open('/home/hp/products/' + 'prod['+str(i)+'].csv', 'w'))
    writer.writerow(prod.columns.tolist())
    writer.writerows(rows)

The print(item[3]) statement prints nothing. Also, in the generated CSVs, only headers got printed. All the cells are empty.
Edit:
Before applying any regex, this:
item = prod.iloc[i]
print(item[3])
print(type(item[3]))

prints this:
0
<class 'int'>
0
<class 'int'>
0
<class 'int'>
0
<class 'int'>
0
<class 'int'>
0
<class 'int'>
0
<class 'int'>
1 btl
<class 'str'>
0
<class 'int'>

So the values are either ints or strings.
Sample data from a sheet of the original xlsx file:

A: As you want to change any text like 1 pkt to 1, rather than splitting using [a-z]+, it should be better to substitute and change this line:
item[3] = re.split('[a-z]+', item[3])[0]

to:
item[3] = re.sub(r'\D*', '', str(item[3]))

which will replace any non-digit characters to empty string.
Let me know if this works. If not, can you print the value of item[3] and show what it prints?


text:
Q: Is it possible for a properly divided factorial to become a square? Let $n>1$  and let $Q$ denote the product of all prime numbers $p$ with $\frac{n}{2}< p\leq n$ .
Is it true that $\frac{n!}{Q}$ is a perfect square for finitely (or infinitely) many $n$?

A: A sharpening of Bertrand's Postulate says that for any $c\gt0$ and any $m\gt m_0(c)$ there is a prime between $m$ and $(1+c)m$. It follows that for all sufficiently large $n$, there is a prime $p$ between $n/4$ and $n/3$. The multiples of $p$ up to $n$ are precisely $p$, $2p$, and $3p$, so $n!/Q$ is divisible by $p^3$ but not by $p^4$, so, for $n$ sufficiently large, $n!/Q$ is not a square.


text:
Q: Dataloader to MySQL with SSL Have scripted a salesforce dataloader import job using cliq with a MySQL source.
see http://code.google.com/p/dataloadercliq/wiki/CLIqWithMySQL
Everything works correctly..  Yet I am required to use SSL to encrypt the MySQL communication.
My understanding is that one would need to provide additional properties to the database-conf.xml file.  Found the following docs which detail how to connect to MySQL using SSL. http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-using-ssl.html
The document point to setting a property called useSSL.
If one specifies in database-conf.xml
<property name="useSSL" value="true"/>

You get the following message -

'useSSL' is not writable or has an invalid setter method.

Does the parameter type of the setter match the return type of the getter?
Has anyone successful got the jdbc driver to work with SSL.  If so can you please point me in the direction on how to configure it.  Can connect directly to the server through a client tool using SSL, so I have to believe I am not configuring the jdbc driver correctly.  Working on a windows server..
Thank you for reading and responding!!


text:
Q: TypeError: Cannot find function rangeToObjects in object [object Object]. (line 4, file "Code") my Code.gs is:
    function createPages(){
  var site = SitesApp.getSiteByUrl('https://sites.google.com/site/typsetgraphics/website-assistance-services/web-graphics');
  var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/14_W42RTQNoTZhl7DodhjJAiZ9kPp4zHxFcI5jVmxPNQ/edit#gid=0').getSheets()[0];
  var productDetails = ObjApp.rangeToObjects(ss.getDataRange().getValues());
  for (var i=0; i<productDetails.length; i++){
    if (productDetails[i].productPage != "") continue;
    var page = site.createWebPage(productDetails[i].title,
                                  ObjApp.camelString(productDetails[i].title),
                                  '<img src="'+productDetails[i].imageUrl+
                                  '" align="left"/><p>'+productDetails[i].description);
    productDetails[i].productPage = page.getUrl();
  }
  var headers = ss.getRange(1,1,1,ss.getLastColumn()).getValues()[0];
  var values = ObjApp.objectToArray(headers, productDetails);
  ss.getRange(2, 1, values.length, values[0].length).setValues(values);
}

function randomString() {
  var ss = SpreadsheetApp.openById('14_W42RTQNoTZhl7DodhjJAiZ9kPp4zHxFcI5jVmxPNQ').getSheets()[0];
  var randomArray = new Array();
  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
  var string_length = 10;
  var lastRow = ss.getLastRow()-1;
  for (var j=0; j<lastRow; j++){
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
      var rnum = Math.floor(Math.random() * chars.length);
      randomstring += chars.substring(rnum,rnum+1);
    }
    randomArray.push([randomstring]);
  }
  ss.getRange(2, 1, lastRow, 1).setValues(randomArray);
}

and line 4 specifically is:
var productDetails = ObjApp.rangeToObjects(ss.getDataRange().getValues());
this is all directly out of James Ferreira's book, Chapter 5, and I only changed the filename to adapt it to my project, so I'm not sure what's wrong. Not to mention the fact that I'm new to Google Apps scripts, and Javascript writing. Can anyone out there assist?

A: Please Install an open source library first. it can be found on ObjService on the Google Script Examples site.
In the Script Editor click Resources, select libraries, add a library  "MTeYmpfWgqPbiBkVHnpgnM9kh30YExdAc", select version is 5, click save.


text:
Q: How can i get pointer's address from other application without Cheat Engine? I want to change or read the pointer's value which is in other program.But i need to know pointer's address.Can i get the address without Cheat Engine and how can i do that ? In the youtube/google/facebook they are using Cheat Engine to know the address.
#include <iostream>
#include <windows.h>

int main() {
  DWORD pointer = 0x006DFEF8;  // I learned this address from Cheat Engine.
  DWORD pid;
  int deger;
  char program_isim[100];

  std::cin >> program_isim;

  HWND program = FindWindow(0, program_isim);
  if (program == 0) {
    std::cout << program_isim << ",bulunamadi." << std::endl;
  }
   else {
    GetWindowThreadProcessId(program, &pid);
    HANDLE hand = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
    while (1) {
           ReadProcessMemory(hand, (void*)pointer, &deger, sizeof(deger), 0);
           std::cout << deger << std::endl;
              }
  }
  return 0;
}

A: Cheat Engine is a disassembler and debugger.  You can find pointers using both of these features, but everything is easiest when using a debugger at runtime.  It allows you to set "break on read" and "break on write" breakpoints.  The "find what accesses" function of Cheat Engine is just using read breakpoints and logging the addresses where the breakpoint is hit.
Cheat Engine will always be the best way to find pointers.  Can you find a pointer via static analysis?  Yes you can but it will be more difficult.
You can replicate Cheat Engine's behavior by writing your own program which registers itself as a debugger with the Windows API and set breakpoints on the target process.
But the reason you can't use Cheat Engine is because the game has anticheat that detects your debugger, it will also detect your debugger you write so this is not the solution.
The solution is to bypass the anticheat and then just use Cheat Engine as normal.


text:
Q: VueJS dependent properties There is a form with 3 fields,

*

*Total Item (QTY)

*UNIT Price (Single Item)

*Total Price (All Items)

The scenario is like this, user will enter Total Item along with one other value, either unit price or total price,
if user enter unit price, I have to calculate total price by multiplying total item into unit price,
if user enter total price, I have to divide it by total item and get the unit price.
I am trying to achieve it with including unit price and total price in watch without success, here is my code,
  watch:{
        unit_rate: function(newVal){
            if(newVal != ''){
                this.total_rate = parseInt(this.total_item) * parseFloat(newVal);
            }else{
                this.total_rate = '';
            }
        },
        total_rate: function(newVal){
            if(newVal != ''){
                this.unit_rate = parseFloat(newVal) / parseInt(this.total_item);
            }else{
                this.unit_rate = '';
            }
        }
    },

I am not sure whether I can modify the property like this while both of them are already in the observe. I did not get the expected output as well, something wrong,,


text:
Q: DECLARE CONTINUE HANDLER FOR NOT FOUND SET variable not working hi i am using a stored procedure in mysql
when i try to
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_prefrences=1 ;

and try to compile , it is giving an error in phpmyadmin .

1193 - Unknown system variable 'no_more_prefrences'

i have used the same line with a different name in another stored procedure . it is working correctly .
this  my stored procedure .
DELIMITER $$
 DROP PROCEDURE IF EXISTS get_all_children_of_lob$$

CREATE PROCEDURE get_all_children_of_lob(
   IN parent_id INT
)

BEGIN

     DECLARE lob_preferenceid INT;
     DECLARE lob_parentid INT;
     DECLARE lob_value VARCHAR(100);
     DECLARE lob_isavailable INT;
     DECLARE lob_ischildavailable INT;
     DECLARE lob_isuseradded INT;

     DECLARE cur CURSOR for select PreferenceID,ParentID,Value,IsAvailable,IsChildAvailable,IsUserAdded from table WHERE ParentID=parent_id ;
     DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_prefrences=1 ;

     CREATE TEMPORARY TABLE IF NOT EXISTS temp_lob(

          ID int(11) NOT NULL AUTO_INCREMENT,
          preferenceIDTmp INT(11),
          parentIDTmp INT(11),
          valueTmp varchar(255),
          isAvailableTmp INT(11),
          isChildAvailableTmp INT(11),
          isUserAddedTmp INT(11),
          PRIMARY KEY (ID)
     );

          SET no_more_prefrences=0;
          OPEN cur;

             dept_loop:WHILE(no_more_prefrences=0) DO

                     FETCH cur INTO lob_preferenceid,lob_parentid,lob_value,lob_isavailable,lob_ischildavailable,lob_isuseradded;
                     IF no_more_prefrences=1 THEN
                        LEAVE dept_loop;
                     END IF;

                                     INSERT  INTO temp_lob(preferenceIDTmp,parentIDTmp,valueTmp,isAvailableTmp,isChildAvailableTmp,isUserAddedTmp)
                                        VALUES  (lob_preferenceid,lob_parentid,lob_value,lob_isavailable,lob_ischildavailable,lob_isuseradded);

                                     CALL get_all_children_of_lob(lob_preferenceid);

             END WHILE dept_loop;

          CLOSE cur;

END$$
DELIMITER ;

i have no idea why is this happening , please help :(

A: It seems the local variable declaration is missing.
Add:
DECLARE no_more_prefrences INT;


text:
Q: Routing a REST API in groups with Slim I'm building a rest api with slim 3 but I'm having some trouble understanding how to do the routing. I initially had the get method working correctly at api.com/v1/companies/get and api.com/v1/companies/get/id and post method at api.com/v1/companies/post, but I refactored so all the methods would be at api.com/v1/companies/id and after this refactoring I get a 405 error on post requests saying that only the get method exists.
So I did a little more researching; the amount of small, but breaking inconsistencies I've found in other slim 3 guides has been a bit annoying, but it looks like my solution is the map() function, only I have no idea how to use it, and even the official docs skip over the part I don't understand.
This is how the code looked after the refactor that broke it:
$app->group('/v1', function() use ($app) {
    $app->group('/companies', function() use ($app) {
        $app->get('/{code}', function($request, $response, $args) {...}
        $app->get('', function($request, $response, $args) {...}
        $app->post('', function($request, $response, $args) {...}
    });
});

And my first attempts at using map():
$app->group('/v1', function() use ($app) {
    $app->map(['GET', 'POST', 'PUT', 'DELETE'], '/companies/{code}', function($request, $response, $args) use ($app) {
        //here's where I don't know what to do
        if($request->isGet()) {
            //What goes here? And I seem to be having problems accessing my parameters?
        }
     }
}

A: This code works for me:
<?php

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require '../vendor/autoload.php';

$app = new \Slim\App;

$app->group('/v1', function() {
    $this->map(['GET', 'POST', 'PUT', 'DELETE'], '/companies/{code}', function($request, $response, $args) {

        if($request->isGet()) {
            $response->getBody()->write("it's GET");
        }

        if($request->isPost()) {
            $response->getBody()->write("it's POST");
        }

        if($request->isPut()) {
            $response->getBody()->write("it's PUT");
        }

        if($request->isDelete()) {
            $response->getBody()->write("it's DELETE");
        }

        return $response;
    });
});

$app->run();

Please don't use $app inside group. In docs you can see that $this inside group point to instance of 'Slim\App' already. Also check your .htaccess file if it's configured as described in Slim3 documentation.


text:
Q: Print text obtained after swapping keyboard keys Problem:
Andi and Bob were friends since childhood days. But, as they grew up Bob started behaving weird and this used to irritate Andi. Once, while Andi took a break after typing a large program Bob came from nowhere and swapped some alphabet keys on Andi's keyboard.
Andi got very angry on seeing this and decided to end their friendship once forever. As we all know Bob is very good at heart and never does anything wrong intentionally. He decided to type the remaining program with the same keyboard Configuration. Given the original fragment of the code that Bob needs to type, You need to tell Bob the code that he should type to get the original code as output.
Help him saving his friendship with Andi.
INPUT :
First line of the input contains a single integer N denoting the number of swaps done by Bob. Next N lines contain a pair of characters A,B denoting the characters which are swapped by Bob (Note that Bob performs these swaps in the given order). From the very next line of input the remaining fragment of the code starts and ends with an end of file character.
OUTPUT:
print the fragment of the program that Bob types.
CONSTRAINTS:
1 <= N <= 106
1 <= |length of codefragment| <= 106
code fragment contains uppercase and lowercase english alphabets only and space.
A,B belongs to Alphabet set (both upper case and lower case letters are included).
My Approach:
public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int N = s.nextInt();
        String[] from = new String[N];
        String[] to = new String[N];
        HashMap<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < N; i++) {
            from[i] = s.next();
            to[i] = s.next();
            map.put(from[i], to[i]);
        }
        String str = s.next();

        for (String st : map.keySet()) {
                str = str.replace(st, "*").replace(map.get(st), st)
                        .replace("*", map.get(st));
        }
        System.out.println(str);
    }

I don't know why, my answer is not correct. What wrong am I doing here?

A: Following is my code in Java. Which solves basic inputs and work for 2 input cases.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

class CharacterSwapping {
    public static void main(String args[]) {
        ArrayList<Character> orgnlAlphabets = new ArrayList<Character> ();
        orgnlAlphabets.add('A');
        orgnlAlphabets.add('B');
        orgnlAlphabets.add('C');
        orgnlAlphabets.add('D');
        orgnlAlphabets.add('E');
        orgnlAlphabets.add('F');
        orgnlAlphabets.add('G');
        orgnlAlphabets.add('H');
        orgnlAlphabets.add('I');
        orgnlAlphabets.add('J');
        orgnlAlphabets.add('K');
        orgnlAlphabets.add('L');
        orgnlAlphabets.add('M');
        orgnlAlphabets.add('N');
        orgnlAlphabets.add('O');
        orgnlAlphabets.add('P');
        orgnlAlphabets.add('Q');
        orgnlAlphabets.add('R');
        orgnlAlphabets.add('S');
        orgnlAlphabets.add('T');
        orgnlAlphabets.add('U');
        orgnlAlphabets.add('V');
        orgnlAlphabets.add('W');
        orgnlAlphabets.add('X');
        orgnlAlphabets.add('Y');
        orgnlAlphabets.add('Z');
        orgnlAlphabets.add('a');
        orgnlAlphabets.add('b');
        orgnlAlphabets.add('c');
        orgnlAlphabets.add('d');
        orgnlAlphabets.add('e');
        orgnlAlphabets.add('f');
        orgnlAlphabets.add('g');
        orgnlAlphabets.add('h');
        orgnlAlphabets.add('i');
        orgnlAlphabets.add('j');
        orgnlAlphabets.add('k');
        orgnlAlphabets.add('l');
        orgnlAlphabets.add('m');
        orgnlAlphabets.add('n');
        orgnlAlphabets.add('o');
        orgnlAlphabets.add('p');
        orgnlAlphabets.add('q');
        orgnlAlphabets.add('r');
        orgnlAlphabets.add('s');
        orgnlAlphabets.add('t');
        orgnlAlphabets.add('u');
        orgnlAlphabets.add('v');
        orgnlAlphabets.add('w');
        orgnlAlphabets.add('x');
        orgnlAlphabets.add('y');
        orgnlAlphabets.add('z');
        ArrayList<Character> swappedAlphabets = new ArrayList<Character> ();
        swappedAlphabets.addAll(orgnlAlphabets);

        try {
            //BufferedReader br = new BufferedReader(new FileReader("/tmp/characterswapping_input.txt"));
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            ArrayList<String> inputs = new ArrayList<String> ();
            String sCurrentLine;
            int glbLineCnt = 0;
            while ((sCurrentLine = br.readLine()) != null && !"".equals(sCurrentLine.trim())) {
                inputs.add(sCurrentLine.trim());
            }
            glbLineCnt = 0;
            sCurrentLine = inputs.get(glbLineCnt++);
            int noOfSwapes = Integer.parseInt(sCurrentLine);
            while (noOfSwapes > 0) {
                sCurrentLine = inputs.get(glbLineCnt++);
                String firstLine[] = sCurrentLine.split(" ");
                int firstCharIndex = swappedAlphabets.indexOf(firstLine[0].charAt(0));
                int secondCharIndex = swappedAlphabets.indexOf(firstLine[1].charAt(0));
                swappedAlphabets.set(firstCharIndex, firstLine[1].charAt(0));
                swappedAlphabets.set(secondCharIndex, firstLine[0].charAt(0));
                noOfSwapes--;
            }
            sCurrentLine = inputs.get(glbLineCnt++);
            Character currentChar, orgnlChar;
            for (int i = 0; i < sCurrentLine.length(); i++) {
                currentChar = sCurrentLine.charAt(i);
                if (" ".equals(currentChar.toString())) {
                    System.out.print(" ");
                } else {
                    orgnlChar = orgnlAlphabets.get(swappedAlphabets.indexOf(currentChar));
                    System.out.print(orgnlChar);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

It is working for sample input as
1
W H
WelloHorld

And gives correct output as
HelloWorld

It also works fine for other inputs
e.g.
1
A B
B C

it gives output as
A C

But that coding site says, your code is not working on every case. So not sure for which case this code will fail.


text:
Q: Probability of an event in relation to a marker - effect plot? I am stuck on the following problem:
I want to create a plot that shows the probability of an event (stroke) in relation to the concentration of a biomarker. Further, the x-axis should be log-transformed.
Can somebody help me out?
Currently I got so far:
library(effects)
glm_mb<- glm(data =  df_analysis, event_stroke ~ nsa(log2(biomarker), c(2000,4000,8000,12000)))
gdf.eff.mb <- Effect("biomarker", glm_mb)
plot(gdf.eff.mb, main= FALSE,rug=T)

However, I am not sure if this is correct and I cannot transform the axis. Next, I would like to add a second line/curve for a second event (bleeding).
This is how it should look like:
Desired Plot
Thank you, Stephan


text:
Q: How to mock a directly-imported function using Jest? I'm trying to verify that my method is correctly invoking another, imported method.  For the life of me, I can't figure out how to mock the imported method using Jest.
Method I want to test
LandingPageManager.ts
import {getJSON} from './getJSON';

public fetchData(url: string) {
    getJSON(url);
}

Method I want to mock
getJSON.ts
export function getJSON(url: string) {
    // XHR requests logic
}

Test method
LandingPageManager.test.ts
import 'jest';
import {getJSON} from '../../../src/web/getJSON';
import {LandingPageManager} from '../../../src/web/LandingPageManager';

describe('fetchData', () => {
  let manager = new LandingPageManager();
  it('passes the correct URL to getJSON', () => {
    const getJsonSpy = jest.mock('../../../src/web/getJSON', jest.fn());

    manager.fetchData('sampleValue');
    expect(getJsonSpy).toHaveBeenCalledWith('sampleValue');

    getJsonSpy.restoreAllMocks();
  });
});

Error I'm getting
 jest.fn() value must be a mock function or spy

I've tried setting up the mock a variety of different ways.  But I can't seem to get the syntax right.
Can anyone help point me in the right direction?  I feel like this should be possible.

A: Finally figured out the answer.
Nothing needed to change in the source code (either the imported module or the class under test).
The import needed to change from:
import {getJSON} from '../../../src/web/getJSON';

to:
import * as getJSON from '../../../src/web/getJSON';

And then I was able to directly specify the function for spying with:
const jsonSpy = jest.spyOn(getJSON, 'getJSON');

Fixed test case
Here's how it all works together now.
LandingPageManager.test.ts
import 'jest';
// **** 1.) Changed the below line: ****
import * as getJSON from '../../../src/web/getJSON';
import {LandingPageManager} from '../../../src/web/LandingPageManager';

describe('fetchData', () => {
  let manager = new LandingPageManager();
  it('passes the correct URL to getJSON', () => {
    // **** 2.) Can now specify the method for direct mocking ****
    const jsonSpy = jest.spyOn(getJSON, 'getJSON');

    manager.fetchData('sampleValue');
    expect(jsonSpy).toHaveBeenCalledWith('sampleValue');

    jest.restoreAllMocks();
  });
});