text:
Q: Efeito css ao clicar com mouse Tenho um um efeito css em uma div utilizando a propriedade hover , gostaria de saber se é possível ativar esse efeito somente quando for clicada .

Texto

CSS:
body {
color: #fff;
margin: 30px;
}

.original {
background: #d2d2d2;
margin: 10px 15px;
width: 95px;
}

.box {
background: red;
height: 95px;
width: 95px;
line-height: 95px;
text-align: center;
transform: rotate(-55deg);

  }
 .spin {
  cursor: pointer;
  }
 .spin:hover {
   animation: spin 3s linear infinite;
 }

  @keyframes spin {
  0% {
  transform: rotateY(0deg);
    }
   100% {
  transform: rotateY(360deg);
   }
   }

A: Daria para tentar usar o seletor :target para elementos com IDs combinado com a HASH da URL, por exemplo:
.spin:target {
     animation: spin 3s linear infinite;
}

O código deve ser algo como:

Clica no abaixo no botão executar e depois no link página toda

body {
     color: #fff;
     margin: 30px;
}

.original {
     background: #d2d2d2;
     margin: 10px 15px;
     width: 95px;
}

.box {
     background: red;
     height: 95px;
     width: 95px;
     line-height: 95px;
     text-align: center;
     display: block;
     transform: rotate(-55deg);
}

.spin {
     cursor: pointer;
}

.spin:target {
     animation: spin 3s linear infinite;
}

@keyframes spin {
    0% {
         transform: rotateY(0deg);
    }
    100% {
         transform: rotateY(360deg);
    }
}

        Texto

        Texto

Mas ai complica, porque depende do hash na url para animar, como:
http://site.com/pagina.html#elemento1
http://site.com/pagina.html#elemento2

Então se o hash for mais um problema do que solução para ti, somente usando javascript em com uma classe para isto. No CSS deve ficar assim:
.spin.animar {
     animation: spin 3s linear infinite;
}

O código todo pode ser algo como (leia os comentários para entender o código):

//Detecta quando a página já foi carregada (menos os recursos externos)
window.addEventListener('DOMContentLoaded', function () {

    //Pega todos elementos com a classe spin
    var els = document.querySelectorAll('.spin');

    //Itera todos elementos
    for (var i = els.length - 1; i >= 0; i--) {

        //Aplica o evento onclick
        els[i].onclick = animarElement;
    }
});

function animarElement()
{
    var els = document.querySelectorAll('.spin');

    for (var i = els.length - 1; i >= 0; i--) {
        var el = els[i];

        //Remove a classe CSS animar de todos elementos, menos o elemento clicado (se já tiver a classe nele)
        if (el !== this && el.classList.contains('animar')) {
            el.classList.remove('animar');
        }
    }

    //Se o elemento clicado não tiver a classe animar ainda então aplicamos ela
    if (!this.classList.contains('animar')) {
        this.classList.add('animar');
    }
}
body {
     color: #fff;
     margin: 30px;
}

.original {
     background: #d2d2d2;
     margin: 10px 15px;
     width: 95px;
}

.box {
     background: red;
     height: 95px;
     width: 95px;
     line-height: 95px;
     text-align: center;
     display: block;
     transform: rotate(-55deg);
}

.spin {
     cursor: pointer;
}

.spin.animar {
     animation: spin 3s linear infinite;
}

@keyframes spin {
    0% {
         transform: rotateY(0deg);
    }
    100% {
         transform: rotateY(360deg);
    }
}

Texto

Texto

Note que o uso de :active, :focus e outros semelhantes só funcionam com elementos "clicáveis" ou "focáveis", DIVs não irão suportar isto, logo fazer isto:
.spin:active {
    animation: spin 3s linear infinite;
}

Para elementos DIVs não irá funcionar.
Segue alguns exemplos deles são os elementos que suportam o :active:

*

* (deve conter o atributo href=)

*<button></button>

*E aos elementos associados a um

A: Daria para fazer tb usando radio-button, vc pode colocar um input:radio que quando :checked vao rotacionar o .spin. Mas para isso vc precisa transformar o elemento div.spin em uma label.spin como um for="" para o ID do radio-button, parece complicado, mas não é como vc pode ver no código.

body {
 color: #fff;
 margin: 30px;
}

.original {
 background: #d2d2d2;
 margin: 10px 15px;
 width: 95px;
}

.box {
 background: red;
 height: 95px;
 width: 95px;
 line-height: 95px;
 text-align: center;
 transform: rotate(-55deg);
 display: block;
}

.spin {
 cursor: pointer;
 display: block;
}

@keyframes spin {
 0% {
  transform: rotateY(0deg);
 }

 100% {
  transform: rotateY(360deg);
 }
}
[id^="btn"]:checked + .spin {
 animation: spin 3s linear infinite;
}
[id^="btn"] {
 display: none;
}

 <input type="radio" name="btns" id="btn1">

  Texto

 <input type="radio" name="btns" id="btn2">

  Texto

Para ativar individualmente
Se vc quiser que o usuário possa marcar e desmarcar o elemento basta trocar o input de type="radio" para type="checkbox". Ai ele pode ativar e desativar o .spin individualmente.

body {
 color: #fff;
 margin: 30px;
}

.original {
 background: #d2d2d2;
 margin: 10px 15px;
 width: 95px;
}

.box {
 background: red;
 height: 95px;
 width: 95px;
 line-height: 95px;
 text-align: center;
 transform: rotate(-55deg);
 display: block;
}

.spin {
 cursor: pointer;
 display: block;
}

@keyframes spin {
 0% {
  transform: rotateY(0deg);
 }

 100% {
  transform: rotateY(360deg);
 }
}
[id^="btn"]:checked + .spin {
 animation: spin 3s linear infinite;
}
[id^="btn"] {
 display: none;
}

 <input type="checkbox" id="btn1">

  Texto

 <input type="checkbox" id="btn2">

  Texto


text:
Q: Difference in context this and getContext() What is difference between this and getContext(), when I say this I mean this within an Activity.

A: In general there are two type of classes. Ones that extend ContextWrapper class (Activity, Service, Application) and those that do not extend it (like View).

*

*If class extends ContextWrapper then you can use this as Context. Such classes normally do not have getContext() method.

*Those classes that do not extend ContextWrapper but still save and use Context normally expose getContext() function. And you cannot use this as Context in such cases.
And these two cases are mutually exclusive. At least I don't recall classes that extend ContextWrapper and have getContext at the same time.

A: There is no difference. When you are in an Activity, getContext() will return this. This is because an Activity is a context!

A: getContext() is not defined in an Activity. It's used in a View (or View subclass) to get a reference to the enclosing context (an Activity).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Storing download links within MVC application I'm currently building an MVC C# web application that would be selling digital movies. Basically, users would be allowed to login and create an account and add movies to cart. After adding to cart they may proceed with payments. If payments are successful, they will receive a download link for that movie. I would like to find out how I can include this feature with my web application?
Any help will be appreciated as I'm new to this language, Thanks.

A: You would use a database to store the real location of the movies in the database and once successful payment has been confirmed, you can generate a link that expires after a certain period of time, you can do this by making an additional entry to the database that specify read permissions for x user for y amount of time.
Every time the user tries to use the link, you can first see if the user is authenticated, whether their link has expired (by checking the database) and if its not expired, ensure that the user making the request is the user that the download permission was given to, if all those conditions return true, you can proceed to return the file for download directly....
The way you've posed the question leaves out too many variables, leading to too many other questions... what database you'll be using, whether it'll be hosted on the cloud or on dedicated servers... what payment provider you'll be using... etc... as things stand, your question is too broad.

A: Create download action
public FileResult Download()
{
    //check payment and other condition
    //if condition not passed return null or redirect user to error view
    byte[] fileBytes = System.IO.File.ReadAllBytes(Server.Path($"\\AppData\\{fileName}"));
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

You can read file from database


text:
Q: Using Wicket in a REST call So I recently started using Wicket and I'm trying to make a REST call to an endpoint setup with RestEasy. I can make the call and can see it get hit successfully, but when trying to use Wicket components I'm getting the following error...
org.apache.wicket.WicketRuntimeException: There is no application attached to current thread
I'm assuming this is because I'm entering the application through a point that isn't managed by Wicket. I tried to get around the issue by ignoring Wicket, but it's so tightly coupled to our data that I can't find a way around it without rewriting tons of existing code.
Is there a way that I can either tell Wicket that it needs to manage this endpoint, or a way that I can get my application context once I'm inside my REST service?
Here's some relevant code.
@POST
@Path("/generate/{num}")
@Produces("text/plain")
@RolesAllowed({
        AuthorizeRole.ROLE
})
public Response generate(@PathParam("num") String num) throws Exception {
    Response response;
    Type incomingType = getType(reportBn);

    if(!incomingType.equals(Type.type)) {
        response = Response.status(Response.Status.BAD_REQUEST).entity("Could not process request").build();
        return response;
    }

    SomeObject newObj = new SomeObject(num);

    //This will cause the error, but it's actually
    //getting called later, this is just to show why it's thrown.
    Application.get();

    response = Response.ok(newObj.getNum()).build();
    return response;
}

A: Although you've found a way I'd share with you the official/designed way to accomplish this: https://github.com/apache/wicket/blob/master/wicket-core/src/main/java/org/apache/wicket/protocol/http/servlet/WicketSessionFilter.java
Just make sure WicketSessionFilter is executed around RestEasy's Filter/Servlet.
The extra benefit is that you have access to Wicket's Session as well.

A: So after doing hours of research and not finding a clue I thought I would try something crazy. Using Spring @Autowired to wire the Application into my class. Aaaaand it worked... here's why...
In our Spring setup we have the Application defined as a bean, like so...
<bean id="wicketApplication" class="... class that extends WebApplication">
    ....
</bean>

We use a custom application class so I'm not sure what other setups would look like, but it worked like a charm!
Hope this helps someone in the future!


text:
Q: Where can I find the unicode symbols for Mac functional keys? (Command, Shift, etc.) Is there a list of key-symbols that I could reference?

A: There is no need for third-party apps. Press CTR + SHIFT + Space to bring up the built-in Characters popup and use the search field to type the unicode name of the character, e.g.:

*

*place of interest → ⌘ [Command]

*option → ⌥ [Option]

*arrowhead →  ⌃ [Control]

*upwards white arrow →  ⇧ [Shift]

*upwards white arrow from bar →  ⇪ [Caps Lock]

✔ You can also use it to insert emojis.
 Click the top right icon to get the extended version of the dialog.

If you right-click a character the Get character info popup will be shown from which you can copy to clipboard the name and the unicode code-point in decimal notation, i.e:
⌘ PLACE OF INTEREST SIGN Unicode: U+2318, UTF-8: E2 8C 98

To use it in your HTML prepend the unicode entity escape prefix and append the semicolon, i.e. 2318 ⇢ ⌘.

You can click the ⚙ (or 3 dot) button > Customize List and enable additional unicode characters groups, including Code Tables > Unicode which will show the full unicode table grouped by categories.

A: I like to use the widget...
CharacterPal

*

*When you hover over a symbol, you can see its coding.

*Copy a symbol to the clipboard by clicking on it. (This will copy the coding.)

The widget offers access to various character sets: Keyboard, Math and Science, Greek, ...

A: If you're using TextExpander (and if not, why not?! It's only $45. ), you can just import the "Keyboard" snippet group from Dr. Dang (see the second part of the post) and get the symbols you're likely looking for:
To insert   Type    Key name
    ⌘       ;cmd    Command
    ⌥       ;opt    Option
    ⇧       ;shift  Shift
    ⌃       ;ctl    Control
    ⇥       ;tab    Tab
    ⌫       ;bs     Backspace
    ⌦       ;del    Forward Delete
    ⌅       ;enter  Enter
    ↩       ;return     Return
    ⎋       ;esc    Escape
           ;apple  Apple
    ←       ;left   Left Arrow
    →       ;right  Right Arrow
    ↑       ;up     Up Arrow
    ↓       ;down   Down Arrow
    ␣       ;space  Space

He also has a few other interesting "set of snippets" you might want to have a look at:

*

*Currency icons and Fractions - See here for info.

*Miscellaneous Symbols - see here for info.

Hope this helps!

A: If you are talking about something like this: ⌘ (the ⌘ key), then you are looking for this chart:
HTML Entity     GLYPH  NAME
              Apple
⌘         ⌘      Command, Cmd, Clover, (formerly) Apple
⌃         ⌃      Control, Ctl, Ctrl
⌥         ⌥      Option, Opt, (Windows) Alt
⇧         ⇧      Shift
⇪         ⇪      Caps lock
⏏         ⏏      Eject
↩         ↩      Return, Carriage Return
↵ ↵ ↵      Return, Carriage Return
⏎         ⏎      Return, Carriage Return
⌤         ⌤      Enter
⌫         ⌫      Delete, Backspace
⌦         ⌦      Forward Delete
⎋         ⎋      Escape, Esc
→ →  →      Right arrow
← ←  ←      Left arrow
↑ ↑  ↑      Up arrow
↓ ↓  ↓      Down arrow
⇞         ⇞      Page Up, PgUp
⇟         ⇟      Page Down, PgDn
↖         ↖      Home
↘         ↘      End
⌧         ⌧      Clear
⇥         ⇥      Tab, Tab Right, Horizontal Tab
⇤         ⇤      Shift Tab, Tab Left, Back-tab
␢         ␢      Space, Blank
␣         ␣      Space, Blank

You also can copy the glyphs directly!

A: Events.h defines constants for the menu glyphs, but not the code points used to represent them. There are several unofficial lists like Keyboard icons & terminology - Ask Different Meta or this one posted on an Apple mailing list.
CajunLuke rolled back my edit to daviesgeek's answer, so here's another list. Differences compared to the current revision of the other answer:

*

*Formatted as CSV

*Added ⌧ and ␣

*The numeric character reference for the left arrow key was wrong

*Included named character references added in HTML5

*Removed uncommon variants like ⏎ and ␢

*The numeric character references are in hexadecimal

⌘,⌘,,command
⇧,⇧,,shift
⌥,⌥,,option
⌃,⌃,,control
↩,↩,↩,return
⌤,⌤,,enter
⌫,⌫,,delete
⌦,⌦,,forward delete
⌧,⌧,,clear
⇥,⇥,⇥,tab
⇤,⇤,⇤,backtab
␣,␣,␣,space
⎋,⎋,,escape
⇪,⇪,,caps lock
⏏,⏏,,eject
⇞,⇞,,page up
⇟,⇟,,page down
↖,↖,↖,home
↘,↘,↘,end
←,←,←,left
→,→,→,right
↑,↑,↑,up
↓,↓,↓,down


text:
Q: Postgres: which index to add I have a table mainly used by this query (only 3 columns are in use here, meter, timeStampUtc and createdOnUtc, but there are other in the table), which starts to take too long:
select
    rank() over (order by mr.meter, mr."timeStampUtc") as row_name
  , max(mr."createdOnUtc") over (partition by mr.meter, mr."timeStampUtc") as "createdOnUtc"
from
    "MeterReading" mr
where
    "createdOnUtc" >= '2021-01-01'
order by row_name
;

(this is the minimal query to show my issue. It might not make too much sense on its own, or could be rewritten)
I am wondering which index (or other technique) to use to optimise this particular query.
A basic index on createdOnUtc helps already.
I am mostly wondering about those 2 windows functions. They are very similar, so I factorised them (named window with thus identical partition by and order by), it had no effect. Adding an index on meter, "timeStampUtc" had no effect either (query plan unchanged).
Is there no way to use an index on those 2 columns inside a window function?
Edit - explain analyze output: using the createdOnUtc index
Sort  (cost=8.51..8.51 rows=1 width=40) (actual time=61.045..62.222 rows=26954 loops=1)
   Sort Key: (rank() OVER (?))
   Sort Method: quicksort  Memory: 2874kB
   ->  WindowAgg  (cost=8.46..8.50 rows=1 width=40) (actual time=18.373..57.892 rows=26954 loops=1)
         ->  WindowAgg  (cost=8.46..8.48 rows=1 width=40) (actual time=18.363..32.444 rows=26954 loops=1)
               ->  Sort  (cost=8.46..8.46 rows=1 width=32) (actual time=18.353..19.663 rows=26954 loops=1)
                     Sort Key: meter, "timeStampUtc"
                     Sort Method: quicksort  Memory: 2874kB
                     ->  Index Scan using "MeterReading_createdOnUtc_idx" on "MeterReading" mr  (cost=0.43..8.45 rows=1 width=32) (actual time=0.068..8.059 rows=26954 loops=1)
                           Index Cond: ("createdOnUtc" >= '2021-01-01 00:00:00'::timestamp without time zone)
 Planning Time: 0.082 ms
 Execution Time: 63.698 ms

A:
Is there no way to use an index on those 2 columns inside a window function?

That is correct; a window function cannot use an index, as the work only on what otherwise would be the final result, all data selection has already finished. From the documentation.

The rows considered by a window function are those of the "virtual
table" produced by the query's FROM clause as filtered by its WHERE,
GROUP BY, and HAVING clauses if any. For example, a row removed
because it does not meet the WHERE condition is not seen by any window
function. A query can contain multiple window functions that slice up
the data in different ways using different OVER clauses, but they all
act on the same collection of rows defined by this virtual table.

The purpose of an index is to speed up the creation of that "virtual table". Applying an index would just slow things down: the data is already in memory. Scanning it is orders of magnitude faster any any index.


text:
Q: Only include first N occurrences of secondary column in pandas groupby I'm trying to do in pandas what I would do with a correlated subquery in SQL, and have not been able to figure out a non-iterative and/or speedier solution. Consider a (much larger) dataframe of players, games, and stats for those games, which could be defined as such:
import pandas as pd

def make_mock_df():
    mock_data = {
        "player": ["Bob", "Bob", "Bob", "Bob", "Bob", "Jim", "Jim", "Jim", "Jim", "Jim"],
        "game_id": ["red", "red", "green", "green", "blue", "red", "yellow", "yellow", "blue", "blue"],
        "stat_id": [1, 2, 1, 2, 1, 1, 1, 2, 1, 2],
        "value": [1, 3, 2, 4, 3, 1, 1, 2, 4, 2],
    }
    return pd.DataFrame(mock_data)

In reality, the game ID would be a UUID, and the data would already be sorted first by player and then by game date, recent-first.
What I want to do is create a dataframe that averages each stat type over the last N games per player. This gets tricky, as not every player plays every game (mocked in the data), and thus is why I'd do the correlated subquery in SQL. This is the iterative solution so far, which breaks down the dataframe by player, then concats each limited player dataframe to rebuild the whole:
def filter_last_n_games(df, n_games):
    last_n_games_per_player = pd.DataFrame()

    for _, player_group in df.groupby("player"):
        # this works because games are sorted already
        # and appear sorted in the unique() series as well
        last_n_games = player_group.game_id.unique()[0:n_games]
        # can't do nlargest because games have string IDs
        last_n_mask = player_group.game_id.isin(last_n_games)
        player_last_n = player_group[last_n_mask]
        # build up last N games df piece by piece...
        last_n_games_per_player = pd.concat(
            [last_n_games_per_player, player_last_n]
        )

    return last_n_games_per_player

def avg_stats_last_n_games(df, n_games):
    last_n_games_per_player = filter_last_n_games(df, n_games)

    # calculate averages per game (easy part)
    last_n_avgs = (
        last_n_games_per_player
        .groupby(["player", "stat_id"])
        .mean()
        .filter(["player", "stats_id", "value"])
        .rename(columns={"value": "avg_value"})
    )

    return last_n_avgs

And results in output as such:
stats_df = make_mock_df()
avg_stats_last_n_games(stats_df, 2)
>>>                 avg_value
>>> player stat_id
>>> Bob    1              1.5
>>>        2              3.5
>>> Jim    1              1.0
>>>        2              2.0

Is there a better substitute for the filter_last_n_games() function that would fully take advantage of pandas' capabilities and allow me to ditch the for-loop?

A: For each group, to select last n games requires,

*

*total #'s elements in the group tcount.

*tagging elements in the group index count icount.

For the mock dataframe,

# With your `make_mock_df()` I am getting

#   player game_id  stat_id  value
# 0    Bob     red        1      1
# 1    Bob     red        2      3
# 2    Bob   green        1      2
# 3    Bob   green        2      4
# 4    Bob    blue        1      3
# 5    Jim     red        1      1
# 6    Jim  yellow        1      1
# 7    Jim  yellow        2      2
# 8    Jim    blue        1      4
# 9    Jim    blue        2      2

def add_counters(grp):
    grp['tcount'] = grp.shape[0]
    grp['icount'] = np.arange(grp.shape[0]) + 1
    return grp

gdf = make_mock_df()
gdf = gdf.groupby(['player', 'game_id']).apply(lambda x: add_counters(x))

# Selecting last `N` games
N=2;

gdf = gdf[(gdf['tcount'] >= N) & (gdf['icount'] <= N)]

# After this filtering step i Get
#   player game_id  stat_id  value  tcount  icount
# 0    Bob     red        1      1       2       1
# 1    Bob     red        2      3       2       2
# 2    Bob   green        1      2       2       1
# 3    Bob   green        2      4       2       2
# 6    Jim  yellow        1      1       2       1
# 7    Jim  yellow        2      2       2       2
# 8    Jim    blue        1      4       2       1
# 9    Jim    blue        2      2       2       2

gdf.groupby(['player', 'stat_id'])[['value']].agg('mean').rename(columns={'value': 'avg_value'})

#                 avg_value
# player stat_id
# Bob    1              1.5
#        2              3.5
# Jim    1              2.5
#        2              2.0

Check the edits above

A: IIUC, the equalivant to doing a subquery:
(df[df.groupby(['player','stat_id']).cumcount() < 2] #filter dataframe to first two records
   .groupby(['player','stat_id'])['value'].mean())  #then groupby and take average

Output:
player  stat_id
Bob     1          1.5
        2          3.5
Jim     1          1.0
        2          2.0
Name: value, dtype: float64


text:
Q: Where does this formula for normal ordering in QFT come from? On this Wikipedia page you can find the following equation for free fields
$$:\phi(x)\chi(y):=\phi(x)\chi(y)-\langle0| \phi(x)\chi(y)|0\rangle\tag{1}$$
But I don't understand where this comes from while it seems a very fundamental equation. I tried understanding it by switching the terms:
$$\langle0| \phi(x)\chi(y)|0\rangle=\phi(x)\chi(y)-:\phi(x)\chi(y):\tag{2}$$
Then the following makes sense: you can expand $\phi,\chi$ in terms of creation/annihilation operators. The expectation value of a normal ordered product is zero so it makes sense that by subtracting it on the RHS the normal ordering term doesn't contribute. For example
$$\langle0|a a^\dagger|0\rangle=a a^\dagger-:aa^\dagger:=(a^\dagger a+1)-a^\dagger a=1\tag{3}$$
What doesn't make sense is that $\phi,\chi$ are generally complex sums of creation/annihilation operators so after applying Wick's theorem I would expect there would be many more terms in the RHS of the second equation. So my question is why does this equation have this form? I feel like understanding this equation would really help my understanding of QFT so any help is appreciated.


text:
Q: Does my recurrent neural network look correct? I want to try to reproduce the result of the following article.
http://karpathy.github.io/2015/05/21/rnn-effectiveness/
Rather than inputting words into the RNN you simply input a byte as a 256 long vector.  At the output you get back another 256 length vector which should represent the next byte.  I am using Keras with the theano backend.  I have run this model with a few different variations for a few hours now.  The best accuracy I can achieve is about 30%.  My program converges on that 30% real fast and stops improving.  My loss function also remains the same.  When I run the test and for instance start the first character with 'T' it outputs 'The _________________________' followed by a bunch of spaces.  This makes sense since The is probably the most likely word and there are a lot of spaces in the document (A 5MB text file containing the complete works of Shakespeare).
As for my model I am using the LTSM layers each with 128 outputs.  I have tried using one two and three layers.  I have also tried different output sizes.  Nothing makes a difference.  It always stagnates at 30%.  I am also not really sure I am doing it correctly. I went of some examples in the Keras documentation.  I am only using one time step since I set the stateful flag in the LSTM so that it will connect each batch to the next.  Is this ok or do I need to add time steps?  Also do you see anything else wrong with it?
import random
import numpy as np

batch_size = 32

#byte to vector
def btov(b):
    v = np.zeros(256)
    v[int(b)] = 1
    return v

#vector to byte
def vtob(v):
    return np.argmax(v.flatten())

data = open('/home/chase/Desktop/shakespeare.txt', 'rb').read()
print('Bytes of Training Data:', len(data))

from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.callbacks import *

model = Sequential()
model.add(LSTM(128, batch_input_shape = (batch_size, 1, 256), stateful = True, return_sequences = True))
model.add(LSTM(128, stateful = True))
model.add(Dropout(0.1))
model.add(Dense(256, activation = 'softmax'))

model.compile(optimizer = Adam(),
              loss = 'categorical_crossentropy',
              metrics = ['accuracy'])

model.summary()

#create batched training data
def gen_training():
    x_train = np.zeros((batch_size, 1, 256))
    y_train = np.zeros((batch_size, 256))

    #each batch has a random starting point in the data
    ix = [random.randint(0, len(data)) for _ in range(batch_size)]
    while True:
        #for every batch
        for b in range(batch_size):
            #load the byte at ix into x
            x_train[b][0] = btov(data[ix[b]])

            #advance to the next byte
            ix[b] += 1
            ix[b] %= len(data)

            #the next byte is the desired output
            y_train[b] = btov(data[ix[b]])

        yield (x_train, y_train)

model.fit_generator(gen_training(),
                    samples_per_epoch = batch_size * 10000,
                    nb_epoch = 1000,
                    callbacks = [ModelCheckpoint('best_loss.h5', monitor = 'loss', verbose = 0, save_best_only = True, mode = 'auto'),
                                 ModelCheckpoint('best_acc.h5', monitor = 'acc', verbose = 0, save_best_only = True, mode = 'auto'),
                                 ModelCheckpoint('last.h5', monitor = 'loss', verbose = 0, save_best_only = False, mode = 'auto')])

'''
This is my test of the model.  When I run this I would load the weights and comment out
the fitting.  First I get some data in the memory with the seed.  Then I feed an initial character
into the model such as T in this case.  I read the output of the predicting and feed that back
in on the next loop.  When I have T for example it prints [The                           ]
followed by a bunch of spaces.
'''

seed = 'I grant thou wert not married to my muse\nAnd therefore mayst without attaint o\'erlook'
for c in seed:
    x_prime = np.zeros((batch_size, 1, 256))
    x_prime[0][0] = btov(ord(c))
    model.predict(x_prime, batch_size = batch_size)

x = np.zeros(256)
x[ord('T')] = 1
s = ''
for i in range(100):
    s += chr(vtob(x))
    x_prime = np.zeros((batch_size, 1, 256))
    x_prime[0][0] = x
    x = model.predict(x_prime, batch_size = batch_size)[0].flatten()
    print(x[ord(' ')])
    x = btov(vtob(x))

print('[', s, ']')

A: Well I spent all day figuring it out.  First off I was way under-fitting the data.  Now I have 3 LSTM layers of size 1024.  Also I needed to use a sampling function on the output.  Now my model looks like this.
model = Sequential()
model.add(LSTM(1024, batch_input_shape = (batch_size, 1, len(bytes_set)), stateful = True, return_sequences = True))
model.add(Dropout(0.3))
model.add(LSTM(1024, stateful = True, return_sequences = True))
model.add(Dropout(0.3))
model.add(LSTM(1024, stateful = True, return_sequences = False))
model.add(Dropout(0.3))
model.add(Dense(len(bytes_set), activation = 'softmax'))

In addition I found the following sampling function online which makes the results much better rather than all spaces.
def sample(a, temperature = 1.0):
    a = np.log(a) / temperature
    a = np.exp(a) / np.sum(np.exp(a))
    return np.argmax(np.random.multinomial(1, a, 1))

Now after only running 30,000 iterations with a batch size of 64 characters I get output which looks like this.
If the more for the conbe mance of plainesss rishrrith?
    And of which be have many and frief of all not the pake and so,
    Marrcoing him him the gaest, that out to live him, in seal onier this for that man of a gright my do fare thy warrm of him here the arest distan the teer for boours of this take in he speak,
    The laws his our fear friend, and sur that I fay the cance was whe say may such despratures whe cord whave you dee you the lend is the frain of a cear he ronour?
    On she tatch foulow of the right of me the for so reter greats so him the sur was a dot.
    Seee the more from thou she of su the flie sweet the gormpre whelefive mad of the the or a foul; and this deear canndse have shat grose is de hear lay me,
    The reI where that the day the would like to frait, die hearts thing the meent,

Not very coherent but my network defiantly learned old English grammar very quickly.  I am actually surprised at how fast.  The text file I used for training is only 5MB but my model has 21 million parameters.  I feel like this would cause overfitting.


text:
Q: Visual Studio Class Diagram not showing relationships When I define my class properties with out using fields (which was enabled with C# 3.0), class diagram is not showing my one to one/many relationships. Inheritance is visible in the diagram though..
Is there a way to fix this?

A: In Visual Studio 2013: right click the class, click Add, and select the desired relationship.

More information: http://msdn.microsoft.com/en-us/library/ff657806.aspx

A: It's for people like me who do not find where is the menu item in 1 minute.

A: This combines with Visual Studio and does everything you want to do with Class diagrams.
http://modeling.codeplex.com/

A: When you right click on the field or property you can select show as association or show as collection association.

A: Since someone asked how to download files from old codeplex.com, I will briefly explain the steps below.

*

*Access the link. In this case it is http://modeling.codeplex.com/.

*Click "download archive" button to download the archive.

*Open the downloaded zip file. ex) modeling.zip File structure in the archive file

*Navigate to "releases" folder if you are after the binary not the source.

*Open the releaseList.json file to see the description and the actual name of each file. Detailed info for each file

*Find the one you want and get the folder Id, file Id and FileName from the releaseList.json.

*Navigate to the folder matching the folder Id. ex) 2

*Select the file matching the file Id and copy to some other place. Rename the file with FileName from the releaseList.json.

*You can go from there.


text:
Q: PHP mysql : possible to check if a link is open? Imagine the simple snippet below:
<?
mysql_close();
?>

This will obviously output the following warning (may look different depending on what version of php_mysql(i) you are using):
mysql_close(): no MySQL-Link resource supplied in .....

As there is no link open.
Is there a way in php to test if a mysql link is already established or not?
Thanks!

Note, have been getting a few comments regarding the use of mysql_close(). I just used that as an example. Furthermore, there are (many) situations when the use of mysql_close() is appropriate.

A: If you keep track of the resource identifier, you can use if ($link) which will get destroyed if you call mysql_close and then it will no longer evaluate true.

A: well i'm not sure but see the answer here
Is closing the mysql connection important?

From the documentation:
Note: The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close().

A: If you need reconnect to mysql, look at this function:
http://www.php.net/manual/ru/function.mysql-ping.php


text:
Q: Program crashes when I open it (CDM) . Works fine in (IDLE) I just finish my homework for my python class and for some reason it can't open in CDM. It opens and run fine while i'm in IDLE mode. My friend code looks the same as mine but his can run in CDM. My open and crashes really fast. I thought it was something in my main since if it was my other functions I would be able to pass through the first input. My friend and I look over my code and found nothing wrong and confused why is this happening. Since we are computer noobs I though I would take it here and yes my first post lol. Can someone help me find my error?
#Allen
#CSC 110.09
#11/15/2014
#Home Work 8

def main(): #main
#The following should be displayed in the read file
#introduction
print('This program reads data from a file, calculate the statistics and then write the results             to another file.')
print()
print('THIS PROGRAM WILL FIND:')
print()
print('• number of characters')
print('• number of letters')
print('• number of consonants')
print('• number of digits')
print('• number of white-space')
print('• number of word characters')
print('• number of punctuation characters')
print()
#flag
error_loop = False #making a loop so the user enter a valid file

while error_loop == False:
    try:

        original_file = input('Enter a file name:   ') #user input a file to read

        print()

        old_file = open(original_file, 'r')
    except Exception as nope:
        print(original_file, 'not found. Please try again', nope)
        print()

        found = False
    else:

        error_loop = True

try:
    characters_count = 0 #set counting to 0
    letters_count = 0 #set counting to 0
    consonants_count = 0 #set counting to 0
    digits_count = 0 #set counting to 0
    whitespaces_count = 0 #set counting to 0
    wordcharacters_count = 0 #set counting to 0
    punctuation_count = 0 #set counting to 0

    #reading the file
    read_file = old_file.read()

    #counting the stats
    while read_file != '':
        #counting the characters
        characters_count += characters(read_file)
        #counting the letters
        letters_count += letters(read_file)
        #counting the consonants
        consonants_count += consonants(read_file)
        #counting digits
        digits_count += digits(read_file)
        #counting white spaces
        whitespaces_count += whitespaces(read_file)
        #counting word characters
        wordcharacters_count += wordcharacters(read_file)
        #counting punctuations
        punctuation_count += punctuation(read_file)

        #read the file again
        read_file = old_file.read()

except Exception as nope:
    print()
    print(nope)

else:
    #making the new file
    new_file_name = input("please enter a new file name:  ") #user can rename the new file
    new_file = open(new_file_name + ".txt",'w') #call the new file
    new_file.write('Statistics for ')
    new_file.write(original_file)
    new_file.write(':\n')

    new_file.write('\tCharacters: ')
    new_file.write(str(characters_count)+'\n')

    new_file.write('\tLetters: ')
    new_file.write(str(letters_count)+'\n')

    new_file.write('\tConsonants: ')
    new_file.write(str(consonants_count)+'\n')

    new_file.write('\tDigits: ')
    new_file.write(str(digits_count)+'\n')

    new_file.write('\tSpaces: ')
    new_file.write(str(whitespaces_count)+'\n')

    new_file.write('\tWord characters: ')
    new_file.write(str(wordcharacters_count)+'\n')

    new_file.write('\tPunctuation:')
    new_file.write(str(punctuation_count)+'\n')

finally:

    #closes the file
    old_file.close()
    new_file.close()

    print()
    print("we have created a new file called", new_file_name)

def characters(characters): #function 1

return len(characters) #length of characters

def letters(letter): #function 2

letters_total = 0
letters = ['A', 'B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q',\
           'R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h',\
           'i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#list of the alphabeth
for line in letter:
    if line in letters:
        letters_total += 1
return letters_total

def consonants(consonant): #function 3

consonants_total = 0
consonants = ['B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V',\
              'W','X','Y','Z','b','c','d','f','g','h','j','k','l','m','n','p','q',\
              'r','s','t','v','w','x','y','z'] #list of consonats
for line in consonant:
    if line in consonants:
        consonants_total += 1
return consonants_total

def digits(digit): #function 4

digits_total = 0
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] #list of numbers
for line in digit:
    if line in digits:
        digits_total += 1
return digits_total

def whitespaces(whitespace): #function 5

whitespaces_total = 0
search = ' ' # space
for line in whitespace:
    if line == search:
        whitespaces_total += 1
return whitespaces_total

def wordcharacters(wordcharacter): #function 6

wordcharacters_total = 0
wordcharacters = ['@','#','$','%','&','+','-','=','<','>','*','/'] #list of word characters
for line in wordcharacter:
    if line in wordcharacters:
        wordcharacters_total += 1
return wordcharacters_total

def punctuation(punctuations): #function 7

punctuation_total = 0
punctuation = ['!','~','`','^','(',')','_','{','}',\
               '[',']','|','\\',';',':','"',"'",',','.','?'] #list of punctuation
for line in punctuations:
    if line in punctuation:
        punctuation_total += 1
return punctuation_total

main() #Call out main

A: The problem is in the indentation after the def main(): block.
You have...
def main(): #main
#The following should be displayed in the read file
#introduction
print('This program reads data from a file, calculate the statistics and then write the             results             to another file.')
print()
print('THIS PROGRAM WILL FIND:')
...

What you should have is those print statements indented after you define your main() method. Like this...
def main():
    print('indent after definition is started like this')

Whether this is the only problem with your code, I have no idea. Try changing that and come back if you have more issues.


text:
Q: How to get yahoo weather information using coldfusion I am a newbie coldfusion developer.
And I want to get yahoo weather information using coldfusion.
So I made a cfm file like this.
<cfset theURL = "https://weather-ydn-yql.media.yahoo.com/forecastrss?location=sunnyvale,ca">
<cfhttp url="#theURL#" charset="utf-8" method="post">
    <cfhttpparam type="formfield" name="appid" value="2a0Lkq6k">
    <cfhttpparam type="formfield" name="context" value="dj0yJmk9MkxEcTlzVDNucE5hJnM9Y29uc3VtZXJzZWNyZXQmc3Y9MCZ4PWMx">
    <cfhttpparam type="formfield" name="query" value="madonna">
</cfhttp>

And I got a error like this.

Your call to Yahoo Web Services returned an unexpected HTTP status of: 401

I have rich experience in laravel, django or so.
But I don't know coldfusion as well as yahoo weather api.
How can I fix this and get the result?


text:
Q: TypeError: seasonal_decompose() got an unexpected keyword argument 'period' I'm trying to digest time series data with datetime index. I'm going to use period in my project, but it gives me an error saying there is no argument named period. I couldn't find anything for that. But I see that the interval is mentioned on the statsmodel website, does anyone know how I can overcome this situation?
 from statsmodels.tsa.seasonal import seasonal_decompose
# Multiplicative Decomposition
decomp_mul = seasonal_decompose(df['meantemp'], model='multiplicative', extrapolate_trend='freq', period=365)
decomp_mul.plot()
plt.show()

TypeError                                 Traceback (most recent call last)
 in ()
2
3 # Multiplicative Decomposition
----> 4 decomp_mul = seasonal_decompose(df['meantemp'], model='multiplicative', extrapolate_trend='freq', period=365)
5 decomp_mul.plot()
6 plt.show()
TypeError: seasonal_decompose() got an unexpected keyword argument 'period'
i use google colab

A: #Prueba con este código que me funcionó en colab
#freq=12 es el número de periodos en un año para este caso
La info la obtuve en el libro Mastering Python for Finance de James Ma Weiming (segunda edición, pag 202)
Te dejo  lo que dice junto con el código
Seasonal decomposing
Decomposing involves modeling both the trend and seasonality, and then removing them. We can use the statsmodel.tsa.seasonal module to model a nonstationary time series dataset using moving averages and remove its trend and seasonal components.
By reusing our df_log variable containing the logarithm of our dataset from the previous section, we get the following:
from statsmodels.tsa.seasonal import seasonal_decompose
decompose_result = seasonal_decompose(df_log.dropna(), freq=12)
df_trend = decompose_result.trend
df_season = decompose_result.seasonal
df_residual = decompose_result.resid

The seasonal_decompose() method of statsmodels.tsa.seasonal requires a parameter, freq, which is an integer value specifying the number of periods per seasonal cycle.
Since we are using monthly data, we expect 12 periods in a seasonal year.
The method returns an object with three attributes, mainly the trend and seasonal components, as well as the final pandas series data with its trend and seasonal components removed.
More information on the seasonal_decompose() method of the statsmodels.t  sa.seasonal module can be found here
Let's visualize the different plots by running the following Python code:
plt.rcParams['figure.figsize'] = (12, 8)
fig = decompose_result.plot()

A: Updating your Q:
I checked this today: Note: The frequency parameter of statsmodels' seasonal_decompose() method has been deprecated and replaced with the period parameter in TDS webpage.
And...
The date should be in datetime format and need to be set as index using .set_index(), e.g., df.set_index('Date', inplace=True). In your case Date is t (as per your dataset)


text:
Q: Trigger for multiplying two columns in oracle2 create or replace trigger BAND_T BEFORE insert or update OF average_song_time, number_of_songs on BAND
for each row
declare
   average_song_time number;
    number_of_songs number;
begin
    if (:new.average_song_time * :new.number_of_songs > 100)  ;
        then
        raise_application_error(error -2010'Play Time is too high');
    end if;
end;

/

Wanting to multiply two columns together in Oracle2 and when the value of the two columns reaches over a certain amount my trigger will be fired, just wondering where im going wrong with this code?

A: You did several errors (semi-colon where it doesn't fit, ERROR in RAISE statement, DECLARE section which is useless here).
See whether such an improved code does what you need.
create or replace trigger band_t
  before insert or update of average_song_time, number_of_songs
  on band
  for each row
begin
  if :new.average_song_time * :new.number_of_songs > 100 then
     raise_application_error(-20001, 'Play time is too high');
  end if;
end;
/


text:
Q: how to fetch all the row of the result in php mysql? In my table I have 2 records with companyid = 1 , but when I run the php below for companyid = 1 it returns only the first one !
How can I fetch all the records?
The php file:
if (isset($_GET["companyid"])) {
$companyid = $_GET['companyid'];

// get a product from products table
$result = mysql_query("SELECT * FROM `products`
                        WHERE companyid = $companyid;");

if (!empty($result)) {

    if (mysql_num_rows($result) > 0) {

   while($row = mysql_fetch_assoc($result)){
      $product = array();
      $product["pid"] = $row["pid"];
      $product["productname"] = $row["productname"];
    }

   $response["product"] = array();

       array_push($response["product"], $product);

        // success
       $response["success"] = 1;

   echo json_encode($response);

    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No product found";

        // echo no product JSON
        echo json_encode($response);
    }
} else {
    // no product found
    $response["success"] = 0;
    $response["message"] = "No product found";

    // echo no users JSON
    echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}

Using mysql_fetch_array is happening the same.
it returns {"product":[{"pid":"12371","productname":"test"}],"success":1}
when i run a query without parameters select * from table using mysql_fetch_array it returns all the rows ..

A: while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

mysql_free_result($result);

php.net/mysql_fetch_assoc
I would recommend you to use PDO instead of mysql_
if (!empty($result)) {

Could be is_resource($result)

A: You need to loop through the result to pull all the rows:
while($row = mysql_fetch_assoc($result)){
//Do stuff
}

On a side note, you should be using at least mysqli or PDO instead of mysql_* functions.

A: As  NikiC pointed out you should not be using the mysql_ functions any longer, you can fetch the entire array in both PDO and mysqli, Here is a example to fetch all rows using the mysqli->fetch_all function, hope this helps!
//Database Connection
$sqlConn =  new mysqli($hostname, $username, $password, $database);

//Build SQL String
$sqlString = "SELECT * FROM my_table";

//Execute the query and put data into a result
$result = $sqlConn->query($sqlString);

//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);

//Copy result into a numeric array
$resultArray = $result->fetch_all(MYSQLI_NUM);

//Copy result into both a associative and numeric array
$resultArray = $result->fetch_all(MYSQLI_BOTH);

A: I strongly believe the batch processing with Doctrine or any kind of iterations with MySQL (PDO or mysqli) are just an illusion.
@dimitri-k provided a nice explanation especially about unit of work. The problem is the miss leading: "$query->iterate()" which doesn't really iterate over the data source. It's just an \Traversable wrapper around already fully fetched data source.
An example demonstrating that even removing Doctrine abstraction layer completely from the picture, we will still run into memory issues:
echo 'Starting with memory usage: ' . memory_get_usage(true) / 1024 / 1024 . " MB \n";

$pdo  = new \PDO("mysql:dbname=DBNAME;host=HOST", "USER", "PW");
$stmt = $pdo->prepare('SELECT * FROM my_big_table LIMIT 100000');
$stmt->execute();

while ($rawCampaign = $stmt->fetch()) {
    // echo $rawCampaign['id'] . "\n";
}

echo 'Ending with memory usage: ' . memory_get_usage(true) / 1024 / 1024 . " MB \n";

Output:
Starting with memory usage: 6 MB
Ending with memory usage: 109.46875 MB

Here, the disappointing getIterator() method:
namespace Doctrine\DBAL\Driver\Mysqli\MysqliStatement

/**
 * {@inheritdoc}
 */
public function getIterator()
{
    $data = $this->fetchAll();

    return new \ArrayIterator($data);
}

You can use my little library to actually stream heavy tables using PHP Doctrine or DQL or just pure SQL. However you find appropriate: https://github.com/EnchanterIO/remote-collection-stream


text:
Q: What does "stub" means in testing? Can someone please explain me what "stub" means in testing context? For example what does it mean in the comments below?
@Before
    public void stubAllExternalIntents() {
        // By default Espresso Intents does not **stub** any Intents. Stubbing needs to be setup before
        // every test run. In this case all external Intents will be blocked.
        intending(not(isInternal())).respondWith(new ActivityResult(Activity.RESULT_OK, null));
    }

OR here:
@Test
    public void pickContactButton_click_SelectsPhoneNumber() {
        // **Stub** all Intents to ContactsActivity to return VALID_PHONE_NUMBER. Note that the Activity
        // is never launched and result is stubbed.
        intending(hasComponent(hasShortClassName(".ContactsActivity")))
                .respondWith(new ActivityResult(Activity.RESULT_OK,
                        ContactsActivity.createResultData(VALID_PHONE_NUMBER)));

A:
A method stub or simply stub in software development is a piece of
  code used to stand in for some other programming functionality. A stub
  may simulate the behavior of existing code (such as a procedure on a
  remote machine, such methods are often called mocks) or be a temporary
  substitute for yet-to-be-developed code.

https://en.wikipedia.org/wiki/Method_stub


text:
Q: Linq: method cannot be translated into a store expression I am currently trying to limit which users can access which groups, and am doing this by using linq.  My problem occours when I am adding the relevant groups to the view.
The error I keep getting is:

LINQ to Entities does not recognize the method 'System.String
  GetUserId(System.Security.Principal.IIdentity)' method, and this
  method cannot be translated into a store expression

This is my code:
  var groupUser = db.GroupUsers.Where(u => u.ApplicationUserId == User.Identity.GetUserId()).Select(gr => gr.GroupId);
  pv.GroupList = db.Groups.Where(g => groupUser.Contains(g.Id)).ToList();
  return View(pv);

A: You need to call GetUserId() outside the lambda expression, as Linq to Entities is not able to translate it to corresponding SQL (of course there is no SQL alternative for GetUserId()):
var userId = User.Identity.GetUserId();
var groupUser = db.GroupUsers.Where(u => u.ApplicationUserId == userId)
                             .Select(gr => gr.GroupId);


text:
Q: Can't Split Items in a List Correctly I'm loading items from a CSV file into a list.  Now, I'm trying to split the list on each newline, and i'm getting this.
Here is my code.
mylist=[]
file = open('C:\\Users\\Excel\\Desktop\\test.csv')
for line in file:
    mylist.append(line)

import pandas as pd
import pypyodbc
cnxn = pypyodbc.connect('Driver={SQL Server Native Client 11.0};'
                        'Server=server_name;'
                        'Database=db_name;'
                        'Trusted_Connection=yes;')

#print(cnxn)
for item in mylist:
#for line in mylist:
    print(item)
    sql_for_df = 'select * ' + item.split(',')
    item_order = pd.read_sql(sql_for_df , cnxn)
    order_details = pd.read_sql(sql_for_df , cnxn)
    orders = pd.read_sql(sql_for_df , cnxn)

from functools import reduce
dfs = [item_order, order_details, orders]
df_final = reduce(lambda left,right: pd.merge(left,right,on='OrderID'), dfs)

This:
print(item)

Gives me this:
ItemOrder

Order Details

Orders

But, when I try to concatenate it, like this:
sql_for_df = 'select * ' + item.split(',')

I'm getting this error.
TypeError: can only concatenate str (not "list") to str

It's almost like the list is split correctly and then it goes back to the original format from the list.  What am I doing wrong here?

A: After another look, I figured it out myself.  Thanks for the down-votes!!
Here is the final, working, solution.
mylist=[]
file = open('C:\\Users\\Excel\\Desktop\\test.csv')
for line in file:
    mylist.append(line)

import pandas as pd
import pypyodbc
cnxn = pypyodbc.connect('Driver={SQL Server Native Client 11.0};'
                        'Server=server_name;'
                        'Database=db_name;'
                        'Trusted_Connection=yes;')

for item in mylist:
        #print(item)
        sql_for_df = 'select * from ' + item
        orders = pd.read_sql(sql_for_df , cnxn)
        print(orders)

from functools import reduce
dfs = [item_order, order_details, orders]
df_final = reduce(lambda left,right: pd.merge(left,right,on='OrderID'), dfs)


text:
Q: Prevent HTML/CSS-Navbar from changing height while using border-bottom I got a little problem when using a border-bottomwith a hover-effect on my navbar.
Is there any way to stop that? Or, lets say, give the Navbar the height it would actually by while hovering?
I would preffer a solution for not changing the height on hovering, but I'm open for anything.
Here is a JSFiddle of my Navbar: https://jsfiddle.net/ay3u7trd/
Thanks!

A: Add border-bottom: 3px solid RGBA(0,0,0,0); to your a { }.  This will add the 3px padding to all of your hyperlinks without applying a specific color (the background color native to the object will appear).
Then once the :hover effect takes place it just shows up right there, since the border is already present you have no weird height issues.

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
  border-bottom: 1px solid #121214;
  z-index: 10;
  text-transform: uppercase;

}

li {
  float: left;
  border-right: 1px solid #121214;
  text-decoration: none;
}

a {
  color: #ff8800;
  border-bottom: 3px solid RGBA(0,0,0,0);
}

a:hover {
  color: #ff8800;
  text-decoration: none;
  border-bottom: 3px solid #1290FF;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  background-color: #ff8800;
  text-decoration: none;
  color: #121214;
  transition: background 0.3s ease-in;
}

.active {
  background-color: #ff8800;
  color: #121214;
  text-decoration: none;

Home

News

Contact

About

A: Add a default border bottom to all of them and make it the same color as the background.
a {
  color: #ff8800;
  border-bottom: 3px solid #333;
}

a:hover {
  color: #ff8800;
  text-decoration: none;
  border-bottom-color: #1290FF;
}

Updated demo
UPDATE – Don't forget to change the bottom border color on the active element
.active {
  border-bottom-color: #ff8800;
}

Or you make the default border color transparent (probably the better solution)
a {
  color: #ff8800;
  border-bottom: 3px solid rgba(0,0,0,0);
}

A: The right answer depends on the UX you want to achieve. The easiest way would be to move the border to the  element (or to move the hover to the
 element). And use a 3px border in all cases-- black for non-hovered, blue for hovered.
Like this: https://jsfiddle.net/sh5a8v6y/

Home

News

Contact

About

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 10;
  text-transform: uppercase;

}

li {
  float: left;
  border-right: 1px solid #121214;
  text-decoration: none;
}

a {
  color: #ff8800;
  border-bottom: 3px solid #121214;
}

a:hover {
  color: #ff8800;
  text-decoration: none;
  border-bottom: 3px solid #1290FF;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  background-color: #ff8800;
  text-decoration: none;
  color: #121214;
  transition: background 0.3s ease-in;
}

.active {
  background-color: #ff8800;
  color: #121214;
  text-decoration: none;
}

A: a:hover {
  color: #ff8800;
  text-decoration: none;
  border-bottom: 3px solid #1290FF;
  padding-bottom:11px;
}

Fiddle

A: One simple approach is to change the ul properties as follows:
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: visible;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
  border-bottom: 1px solid #121214;
  z-index: 10;
  text-transform: uppercase;
  height: 48px;
}


text:
Q: SMO generate database script using PowerShell, so it was same way as when creating script manually from Management Studio I need to generate script in code using SMO so it was totally same as if I'm creating it manually using Management Studio. I.e. Database -> Tasks -> Generate scripts.. -> choose Schema and Data.
So as a result I would like to have something like:
USE [master]
GO

CREATE DATABASE [MyDatabase]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'MyDatabase', FILENAME = N'C:\Databases\Data\MyDatabase.mdf' , SIZE = 100KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
( NAME = N'MyDatabase_log', FILENAME = N'C:\Databases\Data\MyDatabase_log.ldf' , SIZE = 100KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO

ALTER DATABASE [MyDatabase] SET COMPATIBILITY_LEVEL = 100
GO

IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
BEGIN
    EXEC [MyDatabase].[dbo].[sp_fulltext_database] @action = 'enable'
END
GO

ALTER DATABASE [MyDatabase] SET ANSI_NULL_DEFAULT OFF
...
GO

/****** Object:  DatabaseRole [StoreRW]    Script Date: 22.02.2019 10:14:14 ******/
CREATE ROLE [StoreRW]
GO

...
GO

CREATE TABLE [dbo].[MyTabale1](
...

I.e. the result should contain CREATE DATABASE statement.
But currently I'm not succeeding in this. I've got database schema and data, but not CREATE DATABASE .
I'm using this code:
$My="$ms.Management.Smo" #
$s = new-object ("$My.Server") $DataSource

if ($s.Version -eq $null) { Throw "Can't find the instance $Datasource" }

$ver = $s.Version
echo " SQL Server version is $ver"
$db= $s.Databases[$Database]

if ($db.name -ne $Database) { Throw "Can't find the database '$Database' in $Datasource" };

$transfer = new-object ("$My.Transfer") $db

if ($transfer -eq $null) { Throw "Can't create transfer object" }

$transfer.Options.Default = $true;
$transfer.Options.ScriptBatchTerminator = $true # this only goes to the file
$transfer.Options.ToFileOnly = $true # this only goes to the file

$transfer.Options.ExtendedProperties = $true;
$transfer.Options.IncludeDatabaseContext = $true;
$transfer.Options.WithDependencies = $true;
$transfer.Options.IncludeHeaders = $true;
$transfer.Options.SchemaQualify = $true;
$transfer.Options.DriAll = $true;

$transfer.Options.ScriptData = $true;
$transfer.Options.ScriptSchema = $true;
$transfer.Options.FileName = $BackupFile;
$tmp = $transfer.Options;
echo " Transfer options are: $tmp";
$transfer.EnumScriptTransfer();
echo "Scripting database '$dbName' to '$BackupFile' done"

What do I need to add to get CREATE DATABASE in there too?

A: This line needs to be added once $db is assigned:
$db.script()

If you want that script data to be output to a file, then just add the following instead:
$db.script() | out-file "c:\folder\create-db.sql"


text:
Q: Is it possible to tell that one of the coin was biased if coins are changed mid experiment? Suppose I have two coins one is baised i.e its probality of head $\ne 0.5$ and another is a fair one with head and tails as equally likely outcome.
Now I begin tossing the baised coin first and note down the results for very large number of experiments(finite), then I switch to the fair one and do the some but this time I do it for even a larger number.
Then I note the total number of heads and total number of tails.
Now my question : If I perform the experiment with fair coin for a very large number would it be able to hide the fact that a unfair coin was involved?

A: Absolutely, but the ratio of fair coin flips to unfair coin flips (in order to hide that an unfair coin was ever used) is dependent on the unfairness of the biased coin.


text:
Q: Rspec Helper method with same name getting executed by Rails Controller while running tests I have the following code in my ApplicationController :
application_controller.rb
class ApplicationController < ActionController::Base
 protect_from_forgery
 include SessionsHelper
end

app/helpers/sessions_helper.rb
module SessionsHelper
 def sign_in(user)
  cookies.permanent[:remember_token]= user.remember_token
  self.current_user = user
 end
end

I'm using rspec-rails and have used a helper method 'sign_in' in my utilities.rb file:
spec/support/utilities.rb
def sign_in(user)
 visit signin_path
 fill_in "Email",with:user.email
 fill_in "Password",with:user.password
 click_button 'Sign in'
 cookies[:remember_token]=user.remember_token
end

My static_pages_spec looks like this :
 describe "When signed in" do
  let(:user) {FactoryGirl.create(:user)}
  before do
    sign_in user
  end
  describe "When no lists are present" do

    it "should show message asking to create list" do
      page.should have_selector("div",text:"You have no lists ! Create a list now !")
    end
  end
 end

When I run the tests , it gives me this error :  StaticPages Home page When signed in When no lists are present should show message asking to create list
     Failure/Error: sign_in user
     NoMethodError:
       undefined method visit' for #<SessionsController:0x00000003630c10>
     # ./spec/support/utilities.rb:2:insign_in'
     # ./app/controllers/sessions_controller.rb:13:in create'
     # (eval):2:inclick_button'
     # ./spec/support/utilities.rb:5:in sign_in'
     # ./spec/requests/static_pages_spec.rb:24:inblock (4 levels) in top (required)>'

This is "create" action of SessionsController :
def create
 user = User.find_by_email(params[:session][:email])
 if user && user.authenticate(params[:session][:password])
   sign_in user  # CODE ERRORS OUT HERE..sign_in of spec/support/utilities.rb executed
   redirect_back_or
 else
   flash.now[:error]= "Invalid email/password"
   render 'new' ,layout: "signin_fail"
 end
end

TL,DR: So, my SessionsController is executing the wrong "sign_in" method(the method which belongs to specs/support instead of app/helpers.session_helper.rb) . When I change the name of helper in spec/support to "log_in" , then the problem gets resolved . What could be the problem here ?


text:
Q: How do I specify a private key for decrypting in gpg I use gpg on ubuntu and I have two keyrings I want to decrypt a message with my second private key but gpg uses the first key for decryption.
How I specify private key for decryption?
Thanks!

A: You should be able to use --keyring <file> and --no-default-keyring.
From the gpg man page:
   --keyring file
          Add  file to the current list of keyrings. If file begins with a tilde and a slash, these are replaced by the $HOME directory. If the filename does not contain a slash, it is assumed to
          be in the GnuPG home directory ("~/.gnupg" if --homedir or $GNUPGHOME is not used).

          Note that this adds a keyring to the current list. If the intent is to use the specified keyring alone, use --keyring along with --no-default-keyring.

It does seem odd this would be necessary. Perhaps the encrypted file does not specify the recipient properly or at all?
If it is anonymous you might need to use --try-all-secrets also.


text:
Q: How can unexpected '{' error in if condition be fixed in PHP? my php code is
<?php
session_start();
if(!isset($_SESSION["userId"]){
header('Location: index.php');
exit;
}
?>

and i got an error
Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\page\login.php on line 3

can anyone help me to solve this problem

A: That's because you forgot a closing bracket ) before the opening curly bracket {:
<?php
    session_start();
    if(!isset($_SESSION["userId"])){
        header('Location: index.php');
        exit;
    }
?>

When you get an unexpected character syntax error in PHP, it's usually because there is a character missing right before it


text:
Q: Python - object - df.type() - what is it ? What can I do with it? I have spent my whole day, scratching my head and searching for infos without any success.
I am trying to import an XLS file. 28 columns. 1010 rows.
In these rows/columns, I thought I would import basic int/float/strings ...
And I thought that I would be able to make calculations between ints, and find some strings contained in some column values...
But that was a newbie utopia. as usual... ;)
here's the codes :
import pandas as pd
import numpy as np
filename = ("D:/PRIVATE/Turb002/Downloads/suivialso3.xlsx")
df = pd.read_excel(filename)
df.columns = ['Reference','Artiste','Titre','Code_Prix','Sortie','Suppr','Profit_Center','O_D','J_2_QTE NETTE','J_1_QTE_NETTE','S_2_QTE_NETTE','S_1_QTE_NETTE','S_QTE_NETTE','M_1_QTE_NETTE','M_QTE_BRUTE','M_QTE_DEPOT_VENTE','M_QTE_RETOUR','M_QTE_STOCK_RACHETE','M_QTE_NETTE','ORIGINE_QTE_BRUTE','ORIGINE_QTE_RETOUR','ORIGINE_QTE_NETTE','CDES_EN _ATTENTE','PORTEFEUILLE_RETOUR','STOCK','STOCK_RETOUR','NON_ENCORE_RECONDITIONNABLE','STOCK_AVANCE']
df.dtypes

the answer to that :
>>> print (df.dtypes)
Référence                              object
Artiste                                object
Titre                                  object
Code Prix                              object
Sortie                         datetime64[ns]
Suppr                                 float64
Profit Center                          object
O / D                                  object
J-2 QTE NETTE                         float64
J-1 QTE NETTE                         float64
S-2 QTE NETTE                         float64
.....
dtype: object

I can manipulate the floats without any problems.
But :
1) what is an object ?
3) Any good tutorial to understand Object manipulation with Panda (couldn't find anything .... ) ?
2) What are his attributes ?
And most importantly.....
3) How can I manipulate it ?
I would like to select/find/ what's in this object when needed as I usually do with strings, int's, etc etc....
when :
    df['Artiste'] contains at least a string as 'oen' even if df['Artiste'] is 'Phoenix'
or when
    df['Artiste'] contains exact "value" of 'Phoenix' = True
or sort by any possibility.. or replace....

And weirdly, df['Référence'] type is an object but it's really only a number so should be a FLOAT64... when J-2 QTE NETTE is also a number but is typed as a FLOAT64
I understand that I'm stuck just because I don't understand well how to apprehend this 'Object' type... and couldn't find any meaningful informations online regarding my problem.
I don't know if I should import differently the file by changing attributes/encoding, or if it's better to manipulate objects than strings (memory, calculations...), if I can convert these objects or else....
Any help is more than welcomed...

A: Ok, found by myself !
I was completly stuck. sincerely. for a few days...
Soooooo I don't know if it's the simple/easiest way but just decided to clean my csv files before importing them into my pandaframe :

*

*get rid of whitespaces or any non-numeric characters

*transforms the specific columns to float and strings

*create a new clean_csv file

*open it in panda

All good - working.


text:
Q: Failed to register layer: How to recover docker from deleting btrfs subvolums? [Update: this turned out to be a non-issue, please see my comment below]
So, when I try to pull an image with "docker pull IMAGE", I'm getting this error:
failed to register layer: stat /var/lib/docker/btrfs/subvolumes/a8a6006af1d850f2dbb7052630731907fe6a2938af338a3c1a0f683e7ba178bf: no such file or directory

It started by not being able to run the docker daemon, because of a "no space left on device" problem on my machine. Since deleting larger files didn't help, I started to remove btrfs subvolums with
for subvolume in /var/lib/docker/btrfs/subvolumes/*; do btrfs subvolume delete $subvolume; done

(that I got from here https://github.com/moby/moby/issues/3894)
Now I'm getting the above error.
I'm looking now for ways to recreate the docker machine from scratch, starting on a fresh btrfs filesystem.
Docker info
Server Version: 17.12.0-ce
Storage Driver: btrfs
Build Version: Btrfs v4.9.1
Library Version: 102


text:
Q: How to plot a barycentric line I want to plot a barycentric function on an equilateral triangle (ternary plot). For example
f1 = {Abs[Sin[x]], Mod[x, 2], Abs[Cos[x]]};

At the moment I evaluate a list of data points and join them with a line
Show[{b3["PlotAxis"],ListPlot[b3["Data"][Range[0,100,1/#],f1],Joined->True]}]&/@{1,10,100}

Where b3 is:
b3 = GetBarycentric[3];
b3["Axis"] = {{1/2, Sqrt[3]/2}, {1, 0}, {0, 0}};
b3["Convert"][{a_, b_, c_}, axis_: b3["Axis"]] := Module[{
    abc = {a, b, c}, sum = Total[{a, b, c}]},
   Piecewise[{{ (axis[[1]] a + axis[[2]] b)/sum, sum > 0}, {axis[[2]], sum <= 0}}]];
b3["Data"][values_, rlines_] := b3["Convert"][#] & /@ Transpose[rlines /. x -> values]
b3["PlotAxis"] := Graphics[{Thin, Line[{#1, #2, #3, #1}]}] & @@ b3["Axis"];

I can not use listplots 'Joined->True', because lines are intermittent.

How can I transform the function and plot it?

A: You can use Exclusions to exclude points where your function is discontinuous. For example
Plot[Evaluate[f1/Total[f1]], {x, 0, 10}, Exclusions -> Range[0, 10, 2]]

and
triangle = {{0, 0}, {1, 0}, {1/2, Sqrt[3]/2}};

ParametricPlot[f1.triangle/Total[f1], {x, 0, 200},
 Epilog -> {EdgeForm[Red], FaceForm[], Polygon[triangle]},
 PlotRange -> {{0, 1}, {0, 1}}, PlotRangePadding -> .1, Axes -> False,
 Exclusions -> Range[0, 200, 2]]

Edit
As whuber pointed out in the comment below, the plot looks a bit ragged near the bottom and right edge. You can correct this by increasing the number of plot points and the maximum number of recursions, e.g.
ParametricPlot[f1.triangle/Total[f1], {x, 0, 200},
 Epilog -> {EdgeForm[Red], FaceForm[], Polygon[triangle]},
 PlotRange -> {{0, 1}, {0, 1}}, PlotRangePadding -> .04,
 Axes -> False, PlotPoints -> 200,
 MaxRecursion -> 10,
 Exclusions -> Range[0, 200, 2]]

A: A ternary plot is a plot on the nonnegative unit simplex in $\mathbb{R}^3$, so apply an affine change of basis (and rescale f1 to be sure its values lie on the simplex):
ClearAll[f1];
f1[x_] := {Abs[Sin[x]], Mod[x, 2], Abs[Cos[x]]};

With[{xyToTernary = {{0, 1, 1/2}, {0, 0, Sqrt[3]/2}}},
 ParametricPlot[xyToTernary . (f1[x] / Total[f1[x]]), {x, 1, 3^5},
  AxesOrigin -> {0, 0}, PlotRange -> {0, 1},
  Prolog -> {White, EdgeForm[Black], Polygon[{{0, 0}, {1, 0}, {1/2, Sqrt[3]/2}}]}]
 ]

Due to the nature of your function, it would be a good idea to break it at integral values of x by including the option Exclusions -> Range[3^5]:

If you would like to visualize the 3D to 2D relationship inherent in these plots, you can ask Mathematica to do the projecting for you (but the 2D quality is degraded):
Show[
 Graphics3D[{White, EdgeForm[Black], Polygon[{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}]},
  ViewVector -> {1, 1, 1}, ViewPoint -> {-8, -8, -8},
  ViewVertical -> {0, 0, 1}, ViewCenter -> {1/3, 1/3, 1/3},
  ViewAngle -> \[Pi]/2,  Lighting -> {{"Ambient", White}}],
 ParametricPlot3D[f1[x] / Total[f1[x]], {x, 1, 3^5},
  Exclusions -> Range[3^5]], Axes -> {True, True, True}
 ]

(Image not shown.)


text:
Q: Openlayers html5 canvas text bold one word I am building an app that will allow users to add to text to a map. I am using Openlayers ol.style.Text to achieve this, see below:
text: new ol.style.Text({
  text: "Your text \n on a new line",
  textAlign: 'left',
  textBaseline: 'bottom',
  offsetX: 10,
  offsetY: -5,
  scale: 1.5,
  placement: 'point',
  font: '12px sans-serif',
  backgroundFill: new ol.style.Fill({
    color: 'rgba(255,255,255,1)'
  }),
  backgroundStroke: new ol.style.Stroke({
    color: 'rgba(0,0,0,1)',
    width: 1
  }),
  padding: [5,5,5,5]
})

I know that I can make all of the text bold by changing font: '12px sans-serif' to font: 'bold 12px sans-serif'
My question is: Is there a way I can make just one word bold ('line' for example)?


text:
Q: wordpress session and cookie handling from outside I have 2 problems with cookies and sessions while using WP.
1)
I have custom CMS where I set a cookie. Cookie's path is / so it should work on every path on current domain.
Problem is wordpress can't read it (its not in developer console either).
My guess is they unset cookies which are not theirs?
2)Similar thing goes with sessions
if I set session from my CMS it's not readable (again empty).
I tried setting
session_start();

in the wp-config.php but does not work. If I set session variable inside wp-config.php then it works, but that's not what I want.
Can anyone suggest me fix or workaround?
Thanks

A: Paste this code into your functions.php file for sessions:
function register_my_session()
{
  if( !session_id() )
  {
    session_start()
  }
}

add_action('init', 'register_my_session');

Now if you want to use sessions its:
$_SESSION['username'] = 'tjcafferkey';


text:
Q: complex Mysql query for chat with Sort by desc leaving NULL on last I have two tables sms_contacts and  sms_twoway_chat. Contact table use id as PK and contact_type is used for 3 psooible types of contacts (0,1 and 2)
sms_twoway_chat holds all chats between two contacts.
I need all contacts with contact_type 0, either they have chat or not
I need only contacts with contact_type 1 and 2 who has received replies
I need unread  (is_read = 0) and recent response of chat (date_time desc ) on top
What I have done is showing Null on top, like contact of type 0 who don't have any record in chat table are displaying on top, whereas they should be on last
CREATE TABLE IF NOT EXISTS `sms_contacts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `contacts_name` varchar(50) DEFAULT NULL,
  `contacts_phone` varchar(11) DEFAULT NULL,
  `date_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `date_time_unix` bigint(20) DEFAULT NULL,
  `contact_type` int(1) DEFAULT '0' COMMENT '0=>contact 1=>group , 2=>instant msg',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;

CREATE TABLE IF NOT EXISTS `sms_twoway_chat` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `inbound_id` varchar(50) DEFAULT NULL,
  `sender_id` int(11) DEFAULT NULL,
  `receiver_id` int(11) DEFAULT NULL,
  `is_read` int(1) DEFAULT '0',
  `msg_body` text,
  `date_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `date_time_unix` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=89 ;

This is what I have tried
SELECT a.*
  FROM ( SELECT c.id,c.`contacts_name` FROM sms_contacts c
LEFT JOIN sms_twoway_chat tc ON c.id = tc.`receiver_id`
WHERE user_id = 1 AND c.contact_type = 0
ORDER BY -tc.`is_read`,  tc.date_time DESC
       ) a
 UNION
SELECT b.*
  FROM ( SELECT c.id,c.`contacts_name` FROM sms_contacts c
INNER JOIN sms_twoway_chat tc  ON c.id = tc.`receiver_id`
WHERE user_id = 1 AND c.contact_type IN(1,2)
ORDER BY -tc.`is_read`,tc.date_time DESC
       ) b;

What about this as a solution ??

SELECT *
    FROM (
        SELECT c.id AS i,  1 AS dt
        FROM sms_contacts c
        WHERE user_id = 1 AND c.contact_type = 0
    ) t1
LEFT  JOIN
(SELECT *
    FROM (
        SELECT DISTINCT sender_id AS i, MAX(date_time) AS dt
        FROM sms_twoway_chat
        WHERE `inbound_id` <> "" AND `receiver_id` =1
        GROUP BY sender_id
        ORDER BY MAX(date_time) DESC, sender_id
    )t3 )t2
ON t1.i = t2.i
ORDER BY t2.dt DESC

A: This might help someone
SELECT *
    FROM (
        SELECT c.id AS i,  1 AS dt, c.`contacts_name`
        FROM sms_contacts c
        WHERE user_id = 1 AND c.contact_type = 0
    ) t1
LEFT  JOIN
(SELECT *
    FROM (
        SELECT DISTINCT sender_id AS i, MAX(date_time) AS dt, 2 AS contacts_name

        FROM sms_twoway_chat
        WHERE `inbound_id` <> "" AND `receiver_id` =1
        GROUP BY sender_id
        ORDER BY MAX(date_time) DESC, sender_id
    )t3 )t2
ON t1.i = t2.i
ORDER BY t2.dt DESC LIMIT 0,100


text:
Q: How to get User IP address surfing internet on my Android App through his phone/tablet I have created an Android app which uses WebView to load internet pages. I want to get the mobile user IP Address. How to do it??

A: This will load ip address on screen
 webview.loadUrl("http://www.whatismyip.com")

A: public static String getipAddress() {
            try {
                for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress=inetAddress.getHostAddress().toString();
                            Log.e("ip address",""+ipaddress);
                            return ipaddress;
                        }
                    }
                }
            } catch (SocketException ex) {
                Log.e("Socket exception in GetIP Address of Utilities", ex.toString());
            }
            return null;
    }

Also add in mainfest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


text:
Q: Can Google Places API take a live text input and generate an address/place as the user is typing (Python)? I'm mainly wondering about how robust the Google Places API is, and whether it can be used to scan a text input in real-time (possibly even auto-completing it) and parse a location from that input.
And is there a way to do that without making multiple API calls on a single text input?
This might help with visualizing what we're trying to build out. It may be easier to parse the remaining portion of the text input after other parts of the text (date/time, title) would be tagged and removed from scanning.

A: Got it: so according to the Places Autocomplete component of Places API:

The Place Autocomplete service can match on full words as well as
  substrings. Applications can therefore send queries as the user types,
  to provide on-the-fly place predictions.


text:
Q: CursorLoader and setUpdateThrottle I'm building an application that leverages a CursorLoader, CursorTreeAdapter and LoaderManager to display information backed by a ContentProvider / SQLite database.
I'm inserting new rows in to the database in rapid succession (around every ~500 milliseconds) and would like to throttle the refresh of the list so it does't jump all over the place when I insert data.
Looking through the documentation there's a function on AsyncTaskLoader (which CursorLoader inherits from) - setUpdateThrottle

public void setUpdateThrottle (long delayMS)
Added in API level 11
Set amount to throttle updates by. This is the minimum time from when the last loadInBackground() call has completed until a new load is scheduled.
Parameters
delayMS   Amount of delay, in milliseconds.

Unfortunately, setting this to something like 5000 milliseconds doesn't seem to slow the reloads of the CursorTreeAdapter.
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    ...
    CursorLoader cl = new CursorLoader(getActivity(),
            NotesContract.Notes.CONTENT_URI,
            projection,
            selection,
            selectionArgs,
            null);

    // setUpdateThrottle Doesn't seem to change anything
    cl.setUpdateThrottle(5000);
    return cl;
}

Any ideas on how to use this throttle function?
If this isn't the right way to use it, do you have any ideas on the best way to batch redraws using CursorLoader, CursorTreeAdapter and LoaderManager?


text:
Q: Absolute path to lua script running on virtual machine My Lua script runs on a virtual machine.
Physically the script file is on my laptop on disk C. Here you can see the path:

This is how it looks like on my laptop:

During work, script works with file calendar_5min.txt
I use line
f = io.open('calendar_5min.txt', "r")

Sometimes it works, but sometimes I get errors because the script cannot find file calendar_5min.txt.
How can I write the absolute path to this file?
Something like
f = io.open('\\tsclient\C\_RollingMoonLua\calendar_5min.txt', "r")

...but with this spelling, it doesn't work.


text:
Q: Show that the current in a cylindrical conductor is uniformly distributed across its cross section Using relevant equations for E and J, show that the current in a steady current I in a cylindrical conductor with uniform conductivity $\sigma$ is uniformly distributed across its cross-section.
I think the relevant equations are the divergence of the E field from the Maxwell equations and $\sigma$E=J but calculating the divergence of J using the symmetry of the problem doesn't seem to work at all. I think I might be confused about the definition of the variables or using something I should be.

A: By the steady state assumption and cylindrical symmetry, both the potential $V$ and the current per unit area $j_z$ are functions only of the radial distance $\rho$ and the distance along the cylinder $z$, and not of the angle $\phi$.  And since there can be (in the steady state) no current perpendicular to the center of the cylinder,  the potential cannot have a non-zero $\rho$ derivative; thus
$V(\rho,z) = V(z)$.
Now let the current $j_z$ integrated over in a ring of radius $r$ to $r+\delta r$
be $I(z,r,\delta_r)$. Ohm's law $\delta V_{ab} = j_ab R_ab$ applied to points in the ring at $z$ and the ring at $z+\delta z$ tells us that
$$
j_z(z, \rho) \sigma \delta z= V(z+\delta z,\rho) - V(z,\rho)
$$
where $\sigma$ is the resistivity of the wire.  This can be integrated over the area $A$ of the ring:
$$
I(z,r,\delta r) = \sigma \int_{\rho = r}^{r+\delta r} j_z(z,\rho) d\rho  = A [V(z+\delta z,\rho) - V(z,\rho) ]
$$
Taking the limit as $\delta z \to 0$,
$$
\frac{\partial}{\partial z}  \sigma \int_{\rho = r}^{r+\delta r}j_z(z,\rho) d\rho = \frac{\partial V(r,z)}{\partial z}
$$
Now comes the first key point: In the ring from $r - \Delta r$ to $r$, with $r - \Delta r$ chosen such that the (cross section) area from $r - \Delta r$ to $r$ is the same as the area from $r$ to $r + \delta r$, there is no radial current between the two rings so $V(r,z)$ cannot be different for the two rings.  And this is true for the two rings at $z+\delta z$ as well, so the $z$ derivative of $V$ has to be the same whether you are looking at ring one or ring two.
The second key point is that
that above relation holds for the second ring as well:
$$
\frac{\partial}{\partial z}  \sigma \int_{\rho = r-\Delta r}^{r}j_z(z,\rho) d\rho = \frac{\partial V(r,z)}{\partial z}
$$
So
$$
\frac{\partial}{\partial z}  \sigma \int_{\rho = r-\Delta r}^{r}j_z(z,\rho) d\rho =\frac{\partial}{\partial z}  \sigma \int_{\rho = r}^{r+\delta r}j_z(z,\rho) d\rho \\
I(z,r-\Delta r)=I(z,r,\delta r) \\
\frac{d}{dr} I(z,r-\Delta r) = 0
$$
and this says that the current through a circular ring cross section of the wire must be  dependant only on the area of the ring.
Finally, one can obtain a cross section of arbitrary shape by superposing rings and parts of rings.  By circular symmetry the current passing through an arc of a ring of angle $\theta$ will be  $I(z,r-\Delta r) \frac{\theta}{2\pi}$.  And the area of such a shape is obtained by integrating the area of each ring times that same $\frac{\theta}{2\pi}$.  So the current equallity for equal area holds for arbitrary cross-section shapes.


text:
Q: Simple question regarding closure and subsets This is probably a dumb question but I have overthought the result so thought it would be best to ask it on here. Suppose I have two compact sets $A$ and $B$ and denote their interiors as int$(A)$ and int$(B)$. Are the two below statements equivalent?
Statement $1$: $\text{int}(A) \subseteq \text{int}(B)$
Statement $2$: $A \subseteq B$


text:
Q: Is getting values from randomly defined attributes advisable? I am totally shocked when I found that jquery can get value from any randomly defined attribute.
HTML
Delete

JS
$('body').on('click', '.delete_post', function() {
    var id = $(this).attr('postid');
    delete_post(id); //$.post request for deleting post
});

I made fiddle here for testing this.
My question here is => Is it advisable to use such randomly defined attributes to get value?
Generally I get value using below code.
HTML

    Delete
    <input type='hidden' class='id' value='10' />

JS
$('.delete_post').on('click', 'a', function() {
    var id = $(this).parent().find('.id').val();
    delete_post(id); //$.post request for deleting post
});

(I tested this successfully in chrome, firefox and internet explorer.)

A: Although this will generally work, it is not advisable to use proprietary/user-defined attributes.  These will not validate and there is the possibility of you incorrectly using a real attribute. Your code is also not future-proof in that you may define an attribute that is not used now, but could be used later.
Instead, you should use data- attributes / .data:
<input data-postid=10 class=delete_post>

var postID = $(this).data('postid');

Spec: http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes

A: HTML5 defines it acceptable to use data-* attributes.  "any random" probably is less effective than data-any-random.


text:
Q: How to make perticular column readonly in excel using apache POI I am generating an excel file using apache poi  and i want to make  last two columns read only in that excel file. So i have  tried the locked feature of poi but it is making all cells  readonly , where i want to the last two readonly .Here i am posting what i have done so far
   HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        sheet.protectSheet("password");
        HSSFRow row = null;

        HSSFCell cell = null;

        /* cell style for locking */
        CellStyle lockedCellStyle = wb.createCellStyle();
        lockedCellStyle.setLocked(true);
        /* cell style for editable cells */
        CellStyle unlockedCellStyle = wb.createCellStyle();
        unlockedCellStyle.setLocked(false);

cell = row.createCell(columnNo);
                if (null != taskDiaryItem.getDueDate()) {
                    SimpleDateFormat formater = new java.text.SimpleDateFormat(InboxItemValue.INBOX_DATE_FORMAT.value());
                    cell.setCellValue(new HSSFRichTextString(formater.format(taskDiaryItem.getDueDate())));
                } else {
                    cell.setCellValue(new HSSFRichTextString(" "));
                }
                columnNo = columnNo + 1;
                /*** End Change : CR#20 CQ#fklnp00272463 ***/

                cell = row.createCell(columnNo);
                if (null != taskDiaryItem.getTaskPriorityDescription()) {
                    cell.setCellValue(new HSSFRichTextString(taskDiaryItem.getTaskPriorityDescription()));
                } else {
                    cell.setCellValue(new HSSFRichTextString(" "));
                }
                columnNo = columnNo + 1;

                cell = row.createCell(columnNo);
                if (null == taskDiaryItem.getContractNumber() || (taskDiaryItem.getContractNumber().isEmpty())) {
                    cell.setCellValue(new HSSFRichTextString(taskDiaryItem.getContractNumber()));
                } else {
                    cell.setCellValue(new HSSFRichTextString(" "));
                }
                columnNo = columnNo + 1;

                cell = row.createCell(columnNo);
                if (null != taskDiaryItem.getTaskStatusDescription()) {
                    cell.setCellValue(new HSSFRichTextString(taskDiaryItem.getTaskStatusDescription()));
                } else {
                    cell.setCellValue(new HSSFRichTextString(" "));
                }
                columnNo = columnNo + 1;

                if (!fromContext.equals(InboxItemValue.USER_INBOX.value())
                        && !fromContext.equals(InboxItemValue.TEAM_MEMBER.value())) {

                    cell = row.createCell(columnNo);
                    if (null != taskDiaryItem.getAssignedToName()) {
                        cell.setCellValue(new HSSFRichTextString(taskDiaryItem.getAssignedToName()));
                        cell.setCellStyle(unlockedCellStyle);
                    } else {
                        cell.setCellValue(new HSSFRichTextString(" "));
                    }
                    columnNo = columnNo + 1;
                }

                cell = row.createCell(columnNo);
                if (null != taskDiaryItem.getAssignedBy()) {
                    cell.setCellValue(new HSSFRichTextString(taskDiaryItem.getAssignedBy()));
                    cell.setCellStyle(lockedCellStyle);
                } else {
                    cell.setCellValue(new HSSFRichTextString(" "));
                }
            } else if(InboxItemValue.PST_INBOX.value().equals(fromContext)) {
                cell = tasksForPSTAndPlacement(taskDiaryItem, cell, row, columnNo, fromContext);
            } else if(InboxItemValue.PLACEMENT_INBOX.value().equals(fromContext)) {
                cell = tasksForPSTAndPlacement(taskDiaryItem, cell, row, columnNo, fromContext);
            }
            j++;
        }
        response.setHeader("Content-Disposition", "attachment; filename=Inbox.xls");
        response.setHeader("Content-type", "application/vnd.ms-excel");
        ServletOutputStream fileOut = response.getOutputStream();
        wb.write(fileOut);
        fileOut.close();

A: You might have to try the opposite to make it working.
Protect the whole sheet and call setLocked(false) for the cells which should be editable.
I have tried this sample code here if you run this you will find that cell havinf TEST is editable where as cell having value TEST2 is read only, you can use this  code to build your logic.
String file = "C:\\poitest.xlsx";
        FileOutputStream outputStream = new FileOutputStream(file);
        Workbook wb = new XSSFWorkbook();

        CellStyle unlockedCellStyle = wb.createCellStyle();
        unlockedCellStyle.setLocked(false);

        Sheet sheet = wb.createSheet();
        sheet.protectSheet("password");
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("TEST");
        cell.setCellStyle(unlockedCellStyle);

        Cell cell2 = row.createCell(1);
        cell2.setCellValue("TEST2");

        wb.write(outputStream);
        outputStream.close();


text:
Q: Problem when plotting a two-dimensional summation function I am currently carrying out a project on antenna group theory. I started developing the theory on shaped patterns from a continuous planar aperture distribution. The next step was to develop this theory on a discreet number of radiating elements.
We should consider a planar aperture with a circular boundary being incised by a family of m concentric circles with N_{m} radiators. Using circular coordinates and applying some simple algebra we can obtain this two-variable Function:
$F(\theta, \phi) = 4 \sum_{m=1}^{20} \sum_{n=1}^{m} I_{m} \cdot \cos \left[\frac{\pi (2m-1)}{4}\cdot \cos\left(\frac{(2 n-1) \pi}{4m}\right) \sin (\theta) \cos (\phi)\right] \cdot \cos \left[\frac{\pi (2m-1)}{4} \sin \left(\frac{(2 n-1) \pi}{4m}\right) \sin (\theta) \sin (\phi)\right]$
Being m the number of circles (20 on this case), N_{m}=4m elements, I_{m} is the current, which has a certain value for each circle and \phi and \theta being the spherical coordinates angles (taking values from -\pi to \pi and from 0 to \pi, respectively).
The fact is that I want to represent this function on a 3D graph. I am going to explain what I tried so far.
I decided to define \phi and \theta as numpy arrays with 50 values each one. Then I decided to create a 20x20 zero matrix, where the double sum calculations will be. Then I defined the double sum with a double loop.
The code I used was the following:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

p=np.linspace(-np.pi, np.pi, 50) #phi angle
t=np.linspace(0,np.pi,50)        #theta angle
F=np.zeros((20,20))              #matrix
I=np.array([1,0.961,0.851,0.689,0.510,0.377,0.360,0.429,0.497,0.521,0.494,0.427,0.340,0.257,0.199,0.178,0.181,0.191,0.200,0.204]) # I current array

for i in range(20):
    for j in range(i):
        F[i,j]= 4*I[i]*np.cos(np.pi*(2(i+1)-1)/4 * np.cos(np.pi*(2*(j+1)-1)/(4(j+1))) * np.sin(t)* np.cos(p)) * np.cos(np.pi*(2(i+1)-1)/4 * np.sin(np.pi*(2*(j+1)-1)/(4(j+1))) * np.sin(t)* np.sin(p))

ax = plt.axes(projection='3d')
ax.plot_surface(p, t, F, rstride=1, cstride=1,
                cmap='viridis', edgecolor='none')
ax.set_title('surface');

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('F')

When running the file I have the following TypeError:'int' object is not callable
I do not know what it is going wrong or how could I improve the program in order to obtain the graph or even make it more efficient.

A: You have a typo in your code:
F[i,j]= 4*I[i]*np.cos(np.pi*(2(i+1)-1)/4 * np.cos(np.pi*(2*(j+1)-1)/(4(j+1))) * np.sin(t)* np.cos(p)) * np.cos(np.pi*(2(i+1)-1)/4 * np.sin(np.pi*(2*(j+1)-1)/(4(j+1))) * np.sin(t)* np.sin(p))

in that line, you have a typo, it should be:
F[i,j]= 4*I[i]*np.cos(np.pi*(2*(i+1)-1)/4 * np.cos(np.pi*(2*(j+1)-1)/(4*(j+1))) * np.sin(t)* np.cos(p)) * np.cos(np.pi*(2*(i+1)-1)/4 * np.sin(np.pi*(2*(j+1)-1)/(4*(j+1))) * np.sin(t)* np.sin(p))

You basically missed 4 *.

Edit:
This fixes your error, however, you get another one, since F[i,j] describes one element, but t, and therefore np.sin(t) consists of 50 elements, which do not fit into your provided index.
The way you did it is unnecessary complex. Try this:

*

*loop over your variables theta and phi, as well as the summation.

*sum afterwards using np.sum() instead of using complex vectorization. If you understood how this works, you can change it later on for speed anyways.


text:
Q: Count object in array (HTML) I want to count the objects in an array, I have this code which does not work in HTML.
It has to be shown in HTML.
I only want it to show one of the object at time:
Type:
Chocolate: 1, Fruit: 2, Food: 3, Liquid: 2

//This is the variable, i need to count
var markers = [{
    type: "Chocolate",
    name: "KitKat",
    group: "candy",
    icon: "candy",
    coords: [5246, 8980],
  },
  {
    type: "Fruit",
    name: "Orange",
    group: "fruits",
    icon: "fruis",
    coords: [9012, 5493],
  },
  {
    type: "Fruit",
    name: "Banana",
    group: "fruits",
    icon: "fruis",
    coords: [9012, 5493],
  },
  {
    type: "Food",
    name: "Rice",
    group: "foods",
    icon: "foods",
    coords: [6724, 9556],
  },
  {
    type: "Food",
    name: "Meat",
    group: "foods",
    icon: "foods",
    coords: [6724, 9556],
  },
  {
    type: "Food",
    name: "Beam",
    group: "foods",
    icon: "foods",
    coords: [6724, 9556],
  },
  {
    type: "Liquid",
    name: "Water",
    group: "liquids",
    icon: "liquids",
    coords: [6724, 9556],
  },
  {
    type: "Liquid",
    name: "Coffe",
    group: "liquids",
    icon: "liquids",
    coords: [6724, 9556],
  },
]

var count = []

for (var i = 0; i < markers.length; i++) {
  count[markers[i].type] = count[markers[i].type] + 1 || 1;
}
document.getElementById('data').innerHTML = count;

It has to look like this
    Chocolate: 1, Fruit: 2, Food: 3, Liquid: 2

I hope somebody can help me, it has to be vanilla javascript

A: You can use reduce too to count fruit types.

var markers = [
    {
      type:"Chocolate",
      name:"KitKat",
      group:"candy",
      icon:"candy",
      coords:[5246,8980],
    },
    {
      type:"Fruit",
      name:"Orange",
      group:"fruits",
      icon:"fruis",
      coords:[9012,5493],
    },
    {
      type:"Fruit",
      name:"Banana",
      group:"fruits",
      icon:"fruis",
      coords:[9012,5493],
    },
    {
      type:"Food",
      name:"Rice",
      group:"foods",
      icon:"foods",
      coords:[6724,9556],
    },
    {
      type:"Food",
      name:"Meat",
      group:"foods",
      icon:"foods",
      coords:[6724,9556],
    },
    {
      type:"Food",
      name:"Beam",
      group:"foods",
      icon:"foods",
      coords:[6724,9556],
    },
    {
      type:"Liquid",
      name:"Water",
      group:"liquids",
      icon:"liquids",
      coords:[6724,9556],
    },
    {
      type:"Liquid",
      name:"Coffe",
      group:"liquids",
      icon:"liquids",
      coords:[6724,9556],
    },
 ];

const countFruitTypes = markers.reduce((a, {type}) => {
    a[type] = (a[type] || 0) + 1;
    return a;
}, {});

console.log(countFruitTypes);

A: 1) You'll have to make count an Object. It'll allow you to store count of different type unlike array.
2) You can't show Object directly onto the HTML page. You'll have to stringify it.

var markers = [
  {
    type:"Chocolate",
    name:"KitKat",
    group:"candy",
    icon:"candy",
    coords:[5246,8980],
  },
  {
    type:"Fruit",
    name:"Orange",
    group:"fruits",
    icon:"fruis",
    coords:[9012,5493],
  },
  {
    type:"Fruit",
    name:"Banana",
    group:"fruits",
    icon:"fruis",
    coords:[9012,5493],
  },
  {
    type:"Food",
    name:"Rice",
    group:"foods",
    icon:"foods",
    coords:[6724,9556],
  },
  {
    type:"Food",
    name:"Meat",
    group:"foods",
    icon:"foods",
    coords:[6724,9556],
  },
  {
    type:"Food",
    name:"Beam",
    group:"foods",
    icon:"foods",
    coords:[6724,9556],
  },
  {
    type:"Liquid",
    name:"Water",
    group:"liquids",
    icon:"liquids",
    coords:[6724,9556],
  },
  {
    type:"Liquid",
    name:"Coffe",
    group:"liquids",
    icon:"liquids",
    coords:[6724,9556],
  },
];

var count = {}

for (var i = 0; i < markers.length; i++) {
  count[markers[i].type] = count[markers[i].type] + 1 || 1 ;
}
document.getElementById('data').innerHTML = JSON.stringify(count);

Alternate solution without using JSON.stringify and using Object.entries
Also for your reference since you're new to coding, I have used Template literals to combine the key and value into a string.

var markers = [
  {
    type:"Chocolate",
    name:"KitKat",
    group:"candy",
    icon:"candy",
    coords:[5246,8980],
  },
  {
    type:"Fruit",
    name:"Orange",
    group:"fruits",
    icon:"fruis",
    coords:[9012,5493],
  },
  {
    type:"Fruit",
    name:"Banana",
    group:"fruits",
    icon:"fruis",
    coords:[9012,5493],
  },
  {
    type:"Food",
    name:"Rice",
    group:"foods",
    icon:"foods",
    coords:[6724,9556],
  },
  {
    type:"Food",
    name:"Meat",
    group:"foods",
    icon:"foods",
    coords:[6724,9556],
  },
  {
    type:"Food",
    name:"Beam",
    group:"foods",
    icon:"foods",
    coords:[6724,9556],
  },
  {
    type:"Liquid",
    name:"Water",
    group:"liquids",
    icon:"liquids",
    coords:[6724,9556],
  },
  {
    type:"Liquid",
    name:"Coffe",
    group:"liquids",
    icon:"liquids",
    coords:[6724,9556],
  },
];

var count = {}

for (var i = 0; i < markers.length; i++) {
  count[markers[i].type] = count[markers[i].type] + 1 || 1 ;
}

var countString = '';

for (let [key, value] of Object.entries(count)) {
  countString += `${key}: ${value} `;
}

document.getElementById('data').innerHTML = countString;