Q:

Using thread.sleep in controller

I need to delay my method to give a time for animation (1500ms) in my frontend.
After animation I want to return refreshed list of objects.
@RequestMapping(value = "/delete_client/{clientId}")
public String deleteClient(@PathVariable String clientId,
    @ModelAttribute("deleteClient") Client client) {
       client.setId(clientId);
       clientRepository.delete(client);
       try {
          Thread.sleep(1600);
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
       return "redirect:/clients";

}

I am curious if its a good way to delay this method.

A:

I believe that's absolutely awful idea to delay controller. Make it in your JS! And only there!


Q:

How to "Float" a label on a TabControl

Can you "Float" a Label on a TabControl like this:

Like that "About" Label on the right of the picture or the "Minimize to Tray" CheckBox?

A:

If using the designer, then place the label above the TabControl, then use your arrow keys to move it into place. Set the anchor properties appropriately. If it falls behind the TabControl, right click it and select BringToFront.
If the Label is inside the TabControl, you can use the "View" - "Other Windows" - "Document Outline" panel to control the hierarchy of the child controls.


Q:

This question already exists

Read this first.
So I came to this point where I had enough and came to figure things out here. I've been using this site for almost a month, but recently I started getting pressure from this one mod. Today is the day, when my post got deleted for the second time, not the same question, but a different one. Apparently, it is a "duplicate" question. The post was hidden and I was provided with those duplicate questions, one was already researched before and it didn't work, the other one was obsolete so it didn't work too.
I always try to figure things on my own before I ask my teacher, just like here. But when you can't, you just ask. But things here seem different, though not sure yet. I posted a new question, providing even more details, like the protruding ring lines in the picture, which wasn't shown the first time. It's hidden again, because duplication. Well, how do you ask otherwise when those other peoples' problems are similar, but I have different outcomes and their provided solutions doesn't solve mine?

This is what should be at least fixed, if the moderator is proved to be not guilty. "If this question doesn't resolve your question, ask a new one." OK, the text obviously means that if the provided questions by the moderator doesn't resolve my problem, I should ask a new one again (at least, that's how most people understand). And like I said before, I did ask a new one, it got hidden, then I edited it, evaluating the mod's work. If it's a duplicate, then provide how is it the same, give proof not just "I pressed a couple of buttons, read this question and figure it yourself." I have never experienced this kind of situation, although I ask a lot when there's no other way, that's called activity, but here it's seems the opposite of it.

A:

I understand you want to get this sorted and you're probably frustrated with this process.

The message you are seeing on your question is slightly misleading and I understand why you asked the question again.
A closed question is not hidden from anyone and it can be voted to be reopened by users who have enough reputation (not just moderators).
Drop the petty comments. They just wont get you anywhere and will make people less likely to want to help you. No one is 'guilty' or 'failing'.

I don't know if the message you're seeing on your question suggesting you ask the question again has always been like that or whether it's changed recently, but it does seem misleading. What Duarte is suggesting is correct and what we advise anyone to do when a question has been closed and they feel it shouldn't have been: edit it and explain why the answers in the duplicate don't help or why your question is different. Once edited your question will enter the review queue and if the edits clearly (and calmly) explain why the duplicate question isn't a duplicate, people will vote for it to be reopened.
To summarise:

I understand the message you're seeing is different from what Duarte suggested, but he is correct. And he has, in my opinion, dealt with this correctly, despite your comments towards him.
To proceed, use the 'edit' link below the question you want reopened to add information explaining how it's not a duplicate or how the answers don't help.
Threats or rudeness aimed at any user will not be tolerated.

This post goes over this quite thoroughly:
Someone flagged my question as already answered, but it's not

Some other related posts (slightly unclear which posts relate to how the site currently works):

"Please ask a new question" encourages question repetition for duplicates
Duplicate explanation should encourage improvement of original
How could we improve our planned post notice improvements?
New Post Notices rollout on Stack Overflow


Q:

How do I write a Visual Basic Application (Excel) program that writes text from two cells into a new text file?

How can I write a Visual Basic Application (Excel) program that writes text from two cells into a new text file when I click a button? I know very little, if anything at all, about Visual Basic, much less about Visual Basic Application.
All of the online resources have failed me as either they don't work the way I intend the program to or don't work at all, giving me errors I have no idea how to solve.

A:

Sub Makro1()
'
' Makro1 Makro
'

'
    Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
    myFile = Application.DefaultFilePath & "\text_file.txt"
    Set rng = Selection
    Open myFile For Output As #1
    cellValue = Range("A1").Value
    Write #1, cellValue
    cellValue = Range("B1").Value
    Write #1, cellValue
    Close #1
End Sub


Q:

Adding a clickable, action-firing JMenuItem directly to a JMenuBar?

Is there a way to add a JMenuItem (or similar button-type object) to  a JMenuBar?
Adding a JMenuItem doesn't play well with the layout of a JMenuBar, and buttons look too button-like.
Should we be tweaking the button to look like a JMenuItem or tweaking the JMenuBar to display the JMenuItem correctly? Or something else altogether?

A:

The following code implements camickr's solution, although I would have come up with the same thing after seeing the default way JMenuItems are rendered in a JMenuBar. It looks reasonably authentic and responds to clicks, but not to the mnemonic.
I tried giving the JMenuItems accelerators (see code) and that works but that looks really weird.
public class TheDude19 extends JFrame {

   private class Action1 extends AbstractAction {
      private Action1() {
         super("Action1");
         putValue(MNEMONIC_KEY, (int) '1');
         // putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK));
      }
      public void actionPerformed(ActionEvent arg0) {
         System.out.println("Action 1!");
      }
   }
   private class Action2 extends AbstractAction {
      private Action2() {
         super("Action2");
         putValue(MNEMONIC_KEY, (int) '2');
      }
      public void actionPerformed(ActionEvent arg0) {
         System.out.println("Action 2!");
      }
   }
   private class NarrowMenuItem extends JMenuItem {

      public NarrowMenuItem(Action a) {
         super(a);
      }
      public Dimension getMaximumSize() {
         return new Dimension(super.getPreferredSize().width, super.getMaximumSize().height);
      }
   }
   public TheDude19() {
      JMenuItem menu1 = new NarrowMenuItem(new Action1());
      JMenuItem menu2 = new NarrowMenuItem(new Action2());
      JMenuBar mb = new JMenuBar();
      mb.add(menu1);
      mb.add(menu2);
      add(mb, BorderLayout.NORTH);
      setSize(400, 300);
   }

   public static void main(String[] args) {
      (new TheDude19()).setVisible(true);
   }

}


Q:

Webpack bundle returns 'Cannot find module' for CSS

I have an app which folders are structured like this:
 /app/
    |- /assets/
    |   |- /css/
    |       |- myapp.css
    |- index.html
    |- index.js
 /dist/
 /node_modules/
 .babelrc
 package.json
 webpack.config.js

myapp.css is a simple, plain css, with nothing special. Just a styling on body to see if it was working.
And my webpack.config.js file has this:
// In webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/app/index.html',
  filename: 'index.html',
  inject: 'body'
});
module.exports = {
  entry: [
    './app/index.js'
  ],
  output: {
    path: __dirname + '/dist',
    filename: "index_bundle.js"
  },
  module: {
    loaders: [
      {test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"},
      {test: /\.css$/, loaders: ['style', 'css']}
    ]
  },
  plugins: [HTMLWebpackPluginConfig]
};

I have put the required css file on index.js like this:
var React = require('react');
var ReactDOM = require('react-dom');

require('assets/css/myapp.css');

var HelloWorld = React.createClass({
    render: function () {
        return (
            <div> Hello ReactJs</div>
        )
    }
});

ReactDOM.render(
    <HelloWorld />,
    document.getElementById('app')
)

I have tried all the ways to get it loaded, adding ../ before assets word, and everythig, but I just keep receiving this error on console:
Error: Cannot find module "assets/css/myapp.css"
I have double check, and css-loader and style-loader are both on /node_modules folder.
What am I doing wrong? I am stuck on it for more than 3 hours, checking tens of tutorials, and I have done all specified. Thanks for the help!

A:

Well... I just needed to add ./ to the require line, like this:
require('./assets/css/myapp.css');
Hope this helps someone else. Thanks, @QoP


Q:

Loader with five column bars

I have created a loader in css with three bars, the code is as given below. The bars are based on :before and :after. But if I want a five bar loader how can I do that ?

.loader,
.loader:before,
.loader:after {
    background: black;
    -webkit-animation: load1 1s infinite ease-in-out;
    animation: load1 1s infinite ease-in-out;
    width: 1em;
    height: 4em;
}

.loader {
    color: black;
    text-indent: -9999em;
    margin-top: 10px;
    margin-right: auto;
    margin-bottom: 10px;
    margin-left: auto;
    position: relative;
    font-size: 8px;
    -webkit-transform: translateZ(0);
    -ms-transform: translateZ(0);
    transform: translateZ(0);
    -webkit-animation-delay: -0.16s;
    animation-delay: -0.16s;
}

.loader:before,
.loader:after {
    position: absolute;
    top: 0;
    content: '';
}

.loader:before {
    left: -2em;
    -webkit-animation-delay: -0.32s;
    animation-delay: -0.32s;
}

.loader:after {
    left: 2em;
}

@-webkit-keyframes load1 {
    0%,
    80%,
    100% {
        box-shadow: 0 0;
        height: 4em;
    }
    40% {
        box-shadow: 0 -2em;
        height: 5em;
    }
}

@keyframes load1 {
    0%,
    80%,
    100% {
        box-shadow: 0 0;
        height: 4em;
    }
    40% {
        box-shadow: 0 -2em;
        height: 5em;
    }
}

.loader-wrapper {
    display: block;
    position: relative;
    height: 56px;
}

Loading...

A:

You could use the CSS propriety ntnchild. Your HTML and CSS will be like:

.loading-bar {
  display: inline-block;
  width: 4px;
  height: 18px;
  border-radius: 4px;
  animation: loading 1s ease-in-out infinite;
}

.loading-bar:nth-child(1) {
  background-color: #3498db;
  animation-delay: 0;
}

.loading-bar:nth-child(2) {
  background-color: #c0392b;
  animation-delay: 0.09s;
}

.loading-bar:nth-child(3) {
  background-color: #f1c40f;
  animation-delay: .18s;
}

.loading-bar:nth-child(4) {
  background-color: #27ae60;
  animation-delay: .27s;
}

.loading-bar:nth-child(5) {
  background-color: #000000;
  animation-delay: .36s;
}

@keyframes loading {
  0% {
    transform: scale(1);
  }

  20% {
    transform: scale(1, 2.2);
  }

  40% {
    transform: scale(1);
  }
}


Q:

Exporting database from MySql Workbench

I have made a database in MySql Workbench. Along the design, I deleted a couple of tables since they weren't necessary.
   But, when I try to export the database to phpmyadmin, all of those tables appear in the code.
   How do I solve this?

A:

In MySQL Workbench 6.0 CE.
I think it is very easy.
Suppose first you add a table in the database. for doing that.

Click on Database Menu. and then click on "Next to Database".
You all database will show on left side.
Click on db and then right click on table. Create New Table.
Now you will create a new table. Click on Apply and you watch table is created.

Now You need to drop this table.
Just right click on a table. and click on drop table. and a dialog box will open. Choose drop and the your created table will be deleted.
Now if you export your db, this deleted table will not show up.
If you had made relationships among different tables then the table will not be deleted until you remove that relationship.
Thanks.


Q:

Vim: Navigating to Previous and Next Buffers in Edit History

When I edit multiple files I oftentimes want to go back and forth between the last edited files. I know about :bn(ext) and :bp(revious) to switch between buffers but they don't keep the history of the last used files. Instead they use the order in which the files were opened. E.g., if I opened the files in this order
A, B, C

an my navigation history would be
A, B, C, B

then :bprevious in the last buffer (B) would send me to A. Is there a command or plugin that would send me to C? I know of Ctrl-6, but this only switches between the last two buffers. I would like to go back and forth multiple buffers.

A:

I have been wanting the same functionality for quite some time now as well. Your question inspired me to finally do something about it. Have a look at bufsurf, a small plugin that provides the required functionality. It provides the user with two commands:
:BufSurfBack

to navigate backwards in history, and similarly:
:BufSurfForward

to navigate forwards in history. For each window or tab a separate navigation history is kept in memory. Please let me know if you experience any problems, I did not have the chance to test this extensively yet.

A:

Check out the lustyjuggler buffer plugin. It's awesome for this. It keeps the buffers in last used order and maps them to the home row keys so you can very quickly go back/forth between them.
http://www.vim.org/scripts/script.php?script_id=2050
You can see it demoed toward the end of my most recent vim screencast were I go over buffers:
http://lococast.net/archives/185


Q:

alias for login page as /accounts

We have a magento website on /store folder.
Idea is, on root folder, index.php will have company website.
/store folder will have magento folder.
Idea is, www.example.com/account should load login form from
www.example.com/store/customer/account/login/

and
www.example.com/account/register

should load register form from
www.example.com/store/customer/account/create/

Can we do this using .htaccess?
I was trying following code
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/account
RewriteRule ^(.*)$ /store/customer/account/login/ [NC,L]

this code redirects to /accounts to /store

A:

A way to do it :
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/account
RewriteRule ^(.*)$ /store/customer/account/login/ [P]

It use P Proxy flag (which implies L flag too).
To use it, make sure you have mod_proxy_http and mod_proxy enable.
a2enmod proxy_http
a2enmod proxy
service apache2 restart

These last commands can depend of your OS.
However, you need to know that Apache advice that you should not activate mod_proxy if your server is not secure (see here).


Q:

Formspree contact form using ajax not working

I am using formspree to send data to my email. The code looks like this.
 HTML:
    <form id="contact-form" >

              Name
                <input type="text"  class="field-light"  id="inputName" placeholder="Name" name="name" />
              Email
                <input type="email" class="field-light"  id="inputEmail" placeholder="Email" name="email" />
                Message
                <textarea id="inputMessage" class="field-light"  rows="5" placeholder="Leave a Message" name="message" ></textarea>
        <button class="field-light center" type="submit" value="Submit">Submit</button>

</form>

and javascript code as :

The code looks  fine but I don't receive any of the emails on submission of the form(I tested it localhost as well on web server). I have checked the unblock feature on formspree site and it seems my email is not blocked. I have read other answer and it works fine but I want to fix this code.

A:

Formspree has a Gold account. That will hide the email address. If you use another service, like hosting on CloudCannon or a form through the formsubmit.io or formbucket service, your email address will also be truly hidden. Then you can use a simple post in the action of the form.
UPDATE: Currently (May 2020) the free plan hides your email address too (registration required).


Q:

php if && || OR statement returning nothing ... but does separately

I'm truly puzzled and need someone to shed some light on this matter for me please.
When I use those 2 statements separately they get results:
$ads->where('country_to', '=', $_COOKIE['country_from'])

$ads->where('country_from', '=', $_COOKIE['country_from']);

... but once I tried to use the OR statement then I get no results, just wondering why?
$ads->where('country_to', '=', $_COOKIE['country_from']) || $ads->where('country_from', '=', $_COOKIE['country_from']);

I also tried this way, no results either:
$ads->where('country_to', '=', $_COOKIE['country_from'] || 'country_from', '=', $_COOKIE['country_from']);

Can someone tell me what I'm doing wrong here? Thanks all ;-)

A:

It seems like you are using Codeignitor,if yes then use orWhere()
$ads->where('country_to', '=', $_COOKIE['country_from']);

$ads->orwhere('country_from', '=', $_COOKIE['country_from']);// or try or_where

Or
$select = "country_to = '".$_COOKIE['country_from']."' OR country_from = '".$_COOKIE['country_from']."'";

$ads->where($select);

Or
$country_from = $_COOKIE['country_from'];

$select = "country_to = $country_from OR country_from = $country_from";

$ads->where($select);


Q:

How to simplify this alternating modulo expression?

The value of $(1000^i \mod 7)$ alternates between 1 and 6, as such:
$$ 1000^0 \mod 7 = 1 $$
$$ 1000^1 \mod 7 = 6 $$
$$ 1000^2 \mod 7 = 1 $$
$$ 1000^3 \mod 7 = 6 $$
But as $i$ grows larger, these expressions can no longer be calculated easily by hand.
I can simplify the expression as such:
$$ 1000^i \mod 7 = (1000 \mod 7)^i \mod 7 = 6^i \mod 7 $$
But even here, when $i$ grows larger, say, when $i = 50$, the expression $6^{50} \mod 7$ isn't easy to calculate, and necessitates splitting $6^{50}$ into smaller "pieces" and composing them.
But I know that the value of $6^i \mod 7$ is very simple: it alternates between 1 and 6 depending on the parity of $i$, so I feel like there must be a way to simplify this expression to capture this alternating property without having to resort to manually calculating each one by hand.
Am I missing something? Thanks for your help.

A:

$$1000\equiv-1\pmod7$$
$$\implies(1000)^n\equiv(-1)^n\pmod7$$
If $n=2m+1,(-1)^n=(-1)^{2m+1}=-1\equiv6\pmod7$


Q:

NameError: name 'horas' is not defined

Añadir duración a una tarea: Escribir un programa que dada la hora de comienzo de una tarea y la duración en segundos de esta, diseñar el algoritmo que calcule la hora en la que finalizará la tarea (nota: la duración de la tarea puede ser de varias horas, nunca superior a media jornada <=14400). Una jornada laboral como mucho será de 8 horas, comienza a las 8:00 y finaliza a las 16:00.
Ese es el enunciado, creo tener el programa completo pero a la hora de ejecutarlo me da un error.
Adjunto foto del codigo

y el error que me da es el siguiente

A:

El siguiente codigo te corrige el error mostrado, siguelo puliendo hasta que consigas lo buscado.
hora_aux = int (input ("Dame las hora: "))
minutos_aux = int (input ("Dame los minutos: "))
segundos_aux = int (input ("Dame los segundos: "))

duracion = int (input ("Dame la duracion: "))

dia = False

print ("La hora de comienzo es: " + str (hora_aux) + ":" + str (minutos_aux) + ":" + str (segundos_aux))

segs = 60
mins = minutos_aux + (segs/60)
horas = hora_aux + (mins/60)

if duracion <= 14400:
    segs = segundos_aux + duracion

    while segs > 59:
        segs = (segs & 60)
        mins = minutos_aux + (segs/60)

    while mins > 59:
        mins = (mins & 60)
        horas = hora_aux + (mins/60)

    while horas > 16:
        horas = 8 + (horas-16)
        dia = True

print ("La hora final es: " + str(horas) +" / " + str(mins) +" / " + str(segs) + "  Dia es: " + str(dia))


Q:

Two Weeks in Cambridge (England), practicing sport in group

In January, I am going to be in Cambridge for 2 weeks to attend a school to improve my English skills. I'm searching for things to do during the weekends, and since my goal is to improve my English, I'd like to do activities involving groups.
I like sport and wild activities, so it would be fun to find a good organization that organises sport or walking events during the week.
Any other ideas are welcome :)

A:

This is a shopping question, which isn't usually allowed on travel.se BUT, since there is only one thing everybody visiting Cambridge should do, I'll answer. What everybody should do when visiting Cambridge is Punting.
 (Source: Wikicommons)
What to do else really depends on personal preference. I would suggest to resort to Travel guides (e.g. Guide Routard, Lonely planet, etc) or sites like Tripadvisor for ideas.


Q:

How to specify a linear programming-like constraint (i.e. max number of rows for a dimension's attributes) in SQL server?

I'm looking to assign unique person IDs to a marketing program, but need to optimize based on each person's Probability Score (some people can be sent to multiple programs, some only one) and have two constraints such as budgeted mail quantity for each program.
I'm using SQL Server and am able to put IDs into their highest scoring program using the row_number() over(partition by person_ID order by Prob_Score), but I need to return a table where each ID is assigned to a program, but I'm not sure how to add the max mail quantity constraint specific to each individual program. I've looked into the Check() constraint functionality, but I'm not sure if that's applicable.
create table test_marketing_table(
    PersonID int,
    MarketingProgram varchar(255),
    ProbabilityScore real
);

insert into test_marketing_table (PersonID, MarketingProgram, ProbabilityScore)
values (1, 'A', 0.07)
       ,(1, 'B', 0.06)
       ,(1, 'C', 0.02)
       ,(2, 'A', 0.02)
       ,(3, 'B', 0.08)
       ,(3, 'C', 0.13)
       ,(4, 'C', 0.02)
       ,(5, 'A', 0.04)
       ,(6, 'B', 0.045)
       ,(6, 'C', 0.09);

--this section assigns everyone to their highest scoring program,
--but this isn't necessarily what I need
with x
as
(
select *, row_number()over(partition by PersonID order by ProbabilityScore desc) as PersonScoreRank
from test_marketing_table
)
select *
from x
where PersonScoreRank='1';

I also need to specify some constraints: two max C packages, one max A & one max B package can be sent. How can I reassign the IDs to a program while also using the highest probability score left available?
The final result should look like:
PersonID    MarketingProgram    ProbabilityScore    PersonScoreRank
3               C                 0.13                  1
6               C                 0.09                  1
1               A                 0.07                  1
6               B                 0.045                 2

A:

You need to rethink your ROW_NUMBER() formula based on your actual need, and you should also have a table of Marketing Programs to make this work efficiently. This covers the basic ideas you need to incorporate to efficiently perform the filtering you need.
MarketingPrograms Table
CREATE TABLE MarketingPrograms (
    ProgramID varchar(10),
    PeopleDesired int
    )

Populate the MarketingPrograms Table
INSERT INTO MarketingPrograms (ProgramID, PeopleDesired) Values
    ('A', 1),
    ('B', 1),
    ('C', 2)

Use the MarketingPrograms Table
with x as (
    select *,
        row_number()over(partition by ProgramId order by ProbabilityScore desc) as ProgramScoreRank
    from test_marketing_table
    )
select *
from x
INNER JOIN MarketingPrograms m
   ON x.MarketingProgram = m.ProgramID
WHERE x.ProgramScoreRank <= m.PeopleDesired


Q:

¿Por qué "millón" no se puede usar como adjetivo, mientras que "mil" sí?

Supongamos la siguiente secuencia de frases:

Los siete primeros elementos.
Los setecientos primeros elementos.
Los siete mil primeros elementos.
Los setecientos mil primeros elementos.
Los siete primeros millones de elementos.

Una vez que alcanzamos los millones de elementos, el número ("siete millones") se debe partir e intercalar "primeros" en medio. Esto es así porque la palabra mil se puede usar como adjetivo y sustantivo, mientras que millón sólo se usa como sustantivo. Así, tenemos:

Los siete mil primeros elementos (uso como adjetivo).
Los siete primeros miles de elementos (uso como sustantivo).

En cambio no hay una versión adjetivo de millón:

Los siete millones primeros elementos.

Y de ahí para arriba, billón, trillón y demás, son todos sustantivos. ¿Qué hizo que la palabra mil se pudiera tratar de forma diferente? ¿Por qué se puede usar como adjetivo y el resto no? ¿Proviene este uso como adjetivo del latín o es algo más reciente?

A:

En latín, los cardinales solían usarse como adjetivos. Esto es válido para los numerales diez, cien, mil y sus combinaciones, que son los que hemos tomado del latín.
En cambio, los numerales millón, billón... los hemos tomado del francés, porque en latín no existían. Y en francés, solo están reconocidos como sustantivos. Así que imagino que esa es la razón (no soy una autoridad en el tema).

A:

Los números relativamente pequeños como cien o mil son muy antiguos, existen y son usados de una manera u otra en el habla común desde hace milenios. Creo recordar que el numeral común más grande en la época clásica europea occidental era miríada (diez mil), que en griego provenía de una palabra que significaba "número vasto, incontable" (los griegos agrupaban las potencias decimales de a cuatro, según entiendo, igual que hacen los chinos y japoneses). Las palabras que designaban a los números, al ser de uso común, funcionaban con la misma flexibilidad que otras (por ejemplo, transformándose de sustantivos en adjetivos, o permitiendo que se formasen derivados de todo tipo).
Los números más elevados y menos usuales ni siquiera existían como palabras en la antigüedad (millón es del siglo XIII) y cuando fueron adoptados lo fueron como términos técnicos. Incluso hoy no hablamos con frecuencia de millones; en nuestra vida diaria podemos pasar de números tan inmensos salvo en dominios muy específicos. De ahí que estos números no hayan sido "flexibilizados" como los otros.

A:

Acabo de ver que el artículo cardinales del Diccionario Panhispánico de Dudas habla de este tema:

6. Las voces millar, millón, millardo, billón, trillón y cuatrillón son sustantivos, a diferencia de los demás cardinales, cuya función primaria es adjetiva; por lo tanto, cuando estos numerales cuantifican por sí solos a un sustantivo, este debe ir necesariamente precedido de la preposición de: un millón DE personas, dos billones DE pesos; pero si, por formar parte de un numeral complejo, van seguidos de otros cardinales, el sustantivo cuantificado no va precedido de preposición: un millón doscientas mil personas. Lo mismo sucede si se escriben con números: 1 000 000 DE personas, 1 200 000 personas. Además, estos sustantivos numerales, cuando se usan en singular, deben ir siempre precedidos de un determinante: Acudieron un millón doscientas mil personas (no X Acudieron millón doscientas mil personas); Mañana te devolveré EL millón de pesos que me prestaste. El caso de mil es especial, puesto que pertenece a ambas categorías: mil es el adjetivo cardinal correspondiente al número 1000: mil casas, mil personas; mientras que el plural miles es un sustantivo masculino sinónimo de millares (→ mil): miles de euros, muchos miles de personas, etc.


Q:

Mac OS X, make a window go over menu bar

Is it possible to make a window to go over the menu bar, without going in fullscreen?
Thanks in Advance!

A:

Yes, trivially:
window.level = NSMainMenuWindowLevel + 1;

(Reference: Drawing to the Full Screen, OpenGL Programming Guide for Mac OS X.)
sebastianmarkow is correct in that this is terrible behaviour for a normal document window, but there are several window types for which this is normal: cursors, tool tips, and special utilities like Xscope.

A:

I liked Jens Ayton's answer, but rather than pick an arbitrary number like that, I think it would be preferred that you use one of the defined constants.
Personally, I used NSPopUpMenuWindowLevel as in:
self.window.level = NSPopUpMenuWindowLevel;

Other constants that you might prefer, as of my posting this answer, include:

NSNormalWindowLevel
NSFloatingWindowLevel
NSSubmenuWindowLevel
NSNormalWindowLevel
NSMainMenuWindowLevel
NSStatusWindowLevel
NSModalPaneWindowLevel
NSPopUpMenuWindowLevel
NSScreenSaverWindowLevel

Here's the reference (Apple has a tendency to change how they organize their docs and break these links over the years, but the APIs don't change much, which is why I included that list above. I doubt this link will work in 3 years or so, but these constants probably won't change much in the next 20 years.)
https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSWindow_Class/Reference/Reference.html#//apple_ref/doc/constant_group/Window_Levels


Q:

How do I get list of all application packages together with their activity label from adb shell?

Sometimes I have a trouble matching application's package name in /data/data/ or /data/app/*.apk with the user-friendly activity label I see in GUI.
How do I list application packages together with their activities?
Expecting something like this:
$ adb shell list_apps
de.shandschuh.sparserss "Sparse rss"
org.vudroid "VuDroid"
jcpezzullo.statical "StatiCal"
tone.control "Tone Control"
...

A:

Based on my answer on the question Andrew linked to, this is what should be in your list_apps script:
for app in $(ls /data/app/*.apk); do
    appname=$(aapt d badging $app | grep 'application: label' | sed -n \"s/.*label\='\([^']*\)'.*/\1/p\")
    pkgname=$(basename $app)
    echo ${pkgname} "${appname}"
done

Run this on your Android device.

Requirements: Either a CM based ROM with Kitkat or higher (which seems to ship with the aapt binary) – or a rooted device where you can install aapt onto yourself (find it here; tested with Android 4.1).
Known issues: app name most likely gets truncated when it contains a single quote (see sed expression). Not having such one installed here I could not test that.
Only lists user apps. Easy to fix by repeating the block for /system/app ;)


Q:

missing number from two squence

How do I findout missing number from two sequence using bash script
from example I have file which contain following data
1 1
1 2
1 3
1 5
2 1
2 3
2 5

output : missing numbers are
1 4
2 2
2 4

A:

This awk one-liner gives the requested output for the specified input:
$ awk '$2!=l2+1&&$1==l1{for(i=l2+1;i<$2;i++)print l1,i}{l1=$1;l2=$2}' file
1 4
2 2
2 4


Q:

Oracle Sequences, Entity Framework and getting nextval in an MVC3 View

I'm currently using Entity Framework inside an MVC3 application to connect to an Oracle Database. I want to write a new record to a table in the Oracle database which includes a sequence that defines it's primary key. Of course, the primary key is defined to be not null. All my views are written in ASP.Net instead of Razor.
I see that most posts out there recommend setting a StoreGeneratedPattern directly on the edmx model. However, I notice that most edmx model examples like this one: Oracle entity in VS entity framework doesnt update the primary key in code  include the tables defined using EntityTypes -the table in question I want to do this on is actually encompassed in an EntitySet:
<EntitySet Name="REGISTERED_PERSON" EntityType="Model.Store.REGISTERED_PERSON" store:Type="Tables" Schema="MYSCHEMA" />

and when I try to set StoreGeneratedPattern=Identity on this, I get an error that the StoreGeneratedPattern attribute is not allowed, presumably because it is not an EntityType. I had originally thought about just getting the max. registered_person_id from the database via LINQ statement and then assigning that into the model, but then the problem arises that you'd get a duplicate ID if two inserts were executed at the same time.
I also checked the database and I don't have any triggers written. I know that in Oracle you can opt to select from dual to get the next value which is generated by the sequence, such as illustrated below:
select MY_SEQ.nextval,'some value' from dual
This post here: postgresql nextval question on sequences has a great title, but the problem with that is that I'm not working with postgresql or PHP, so unfortunately it doesn't help me. I also don't have any triggers written to fire the sequence upon insert of a record.
How do I go about getting the nextvalue from the sequence and assign it to my Registered_Person_Id, preferably in the view before the entire model object gets passed back to the controller to insert in the database?

A:

I have found that you do need both a trigger and sequence to make this work in Oracle. Here is the trigger pattern that I use in production:
CREATE OR REPLACE TRIGGER MYSCHEMA.TRIGGER_NAME
BEFORE INSERT ON MYSCHEMA.REGISTERED_PERSON
FOR EACH ROW
WHEN ( NEW.REGISTERED_PERSON_ID IS NULL )
BEGIN
  SELECT MY_SEQUENCE.NEXTVAL INTO :NEW.REGISTERED_PERSON_ID FROM dual;
END;


Q:

Does Throne of the God-Pharaoh work with tapped vehicles?

Does Throne of the God-Pharaoh trigger with tapped vehicles?
At the beginning of end step, which happens first?

vehicles cease to be creatures
Throne of the God-Pharaoh triggers with tapped vehicles as they're still creatures

A:

The Throne will see the Vehicles as creatures and work with them just fine.
This is because the ending phase works through the following steps:

End Step — Triggered abilities that say “at the beginning of the end step” or “at the beginning of the next end step” trigger. Players get priority and can cast spells and activate abilities.
Cleanup step — In order: the active player discards down to 7, damage is cleared off all permanents, and all “until end of turn” and “this turn” effects wear off. (Then under rare circumstances, the players might get priority and more cleanup steps might happen.)

Your Throne triggers at the beginning of the end step, and your Vehicles don't stop being creatures until the cleanup step happens.

Also, just so you know, Throne of the God-Pharaoh's ability will always trigger even if you have no creatures out (its rulings mention as much), and we only determine the amount of life to be lost as that triggered ability resolves.
This means after it triggers and before it resolves, you have the opportunity to ensure you have more tapped creatures. Handily, you can also activate a crew ability for a vehicle even when it's already crewed, as confirmed by vehicle rulings:

You may activate a crew ability of a Vehicle even if it’s already an artifact creature. Doing so has no effect on the Vehicle. It doesn’t change its power and toughness.

So if you have a Vehicle sitting around, if you'd like to, you can crew it some more to get more tapped creatures.


Q:

How to use pandas to pull out the counties with the largest amount of water used in a given year?

I am new to python and pandas and I am struggling to figure out how to pull out the 10 counties with the most water used for irrigation in 2014.
%matplotlib inline
import csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = pd.read_csv('info.csv') #reads csv

data['Year'] = pd.to_datetime(['Year'], format='%Y') #converts string to
                                                     datetime
data.index = data['Year'] #makes year the index
del data['Year'] #delete the duplicate year column

This is what the data looks like (this is only partial of the data):
County  WUCode  RegNo   Year    SourceCode  SourceID    Annual    CountyName
1       IR      311     2014    WELL        1           946       Adams
1       IN      311     2014    INTAKE      1           268056    Adams
1       IN      312     2014    WELL        1           48        Adams
1       IN      312     2014    WELL        2           96        Adams
1       IR      312     2014    INTAKE      1           337968    Adams
3       IR      315     2014    WELL        5           81900     Putnam
3       PS      315     2014    WELL        6           104400    Putnam

I have a couple questions:
I am not sure how to pull out only the "IR" in the WUCode Column with pandas and I am not sure how to print out a table with the 10 counties with the highest water usage for irrigation in 2014.
I have been able to use the .loc function to pull out the information I need, with something like this:
data.loc['2014', ['CountyName', 'Annual', 'WUCode']]

From here I am kind of lost. Help would be appreciated!

A:

import numpy as np
import pandas as pd
import string
df = pd.DataFrame(data={"Annual": np.random.randint(20, 1000000, 1000),
                "Year": np.random.randint(2012, 2016, 1000),
                "CountyName": np.random.choice(list(string.ascii_letters), 1000)},
              columns=["Annual", "Year", "CountyName"])

Say df looks like:
   Annual  Year CountyName
0  518966  2012          s
1   44511  2013          E
2  332010  2012          e
3  382168  2013          c
4  202816  2013          y

For the year 2014...
df[df['Year'] == 2014]

Group by CountyName...
df[df['Year'] == 2014].groupby("CountyName")

Look at Annual...
df[df['Year'] == 2014].groupby("CountyName")["Annual"]

Get the sum...
df[df['Year'] == 2014].groupby("CountyName")["Annual"].sum()

Sort the result descending...
df[df['Year'] == 2014].groupby("CountyName")["Annual"].sum().sort_values(ascending=False)

Take the top 10...
df[df['Year'] == 2014].groupby("CountyName")["Annual"].sum().sort_values(ascending=False).head(10)

This example prints out (your actual result may vary since my data was random):
CountyName
Q    5191814
y    4335358
r    4315072
f    3985170
A    3685844
a    3583360
S    3301817
I    3231621
t    3228578
u    3164965


Q:

In PHP would this be deemed correct?

I already wrote a post about an issue I had before about this but I had that issue taken care of. Like my last post I have a form, text-box and a button. I have everything done with this including Printing the original word, Printing the number of characters in the word, Printing the word in all caps and Printing the word in reverse order. My only issue I'm having is trying to get whatever text I enter and then click the button to output to Print the first letter of the word and Print the last letter of the word. I've been doing a lot of looking around of PHP.net and I found that substr is used to return a part of a string that I could use. The only issue is when I write the code for it and try to execute my program it errors out on that specific line. I'm not looking for the answer but could someone just take a look and see what I'm doing wrong because I understand everything completely but this is the only thing I'm hung up on.
$first = substr($_POST['entertext']);
echo "The first letter of the word is " . $first. "
\n";

$last = substr($_POST['entertext']);
echo "The first letter of the word is " . $last. "
\n";

A:

Try this:
$first = substr($_POST['entertext'], 0, 1);
echo "The first letter of the word is " . $first. "
\n";

$last = substr($_POST['entertext'], sizeof($_POST['entertext'])-2, 1);
echo "The first letter of the word is " . $last. "
\n";


Q:

Sharing file for reading and writing in .NET

I am trying to figure the FileAccess / FileShare combination that will allow me opening a file for reading, and then opening it for writing. So far the next two lines of the test code are giving me UnauthorizedAccessException on the second line:
Stream s1 = File.Open(name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Stream s2 = File.Open(name, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);

In real life I have a web application which (server side) uses certain ZIP with data. Several handlers are taking files from this archive, and one handler tries to update it. So in practice these two lines are most likely to be in the different threads of the same IIS Application Pool.

A:

Use FileShare.ReadWrite for both streams.
FileShare.Read basically means: disallow any other write handle, and since there is one from the first line, the second line fails.


Q:

Fixing warnings from Hibernate

I am currently working on a Hibernate project. My current development setup has a rather long debug printout on startup, from alot of hibernate warnings.
I would like to clean this up.

2009-02-18 09:14:19
  org.hibernate.util.JDBCExceptionReporter
  logWarnings WARNING:
  [Microsoft][SQLServer 2000 Driver for
  JDBC][SQLServer]Changed language
  setting to us_english.

How do i fix this one? Google was unable to give me the answer

2009-02-18 09:14:19 org.hibernate.util.JDBCExceptionReporter logWarnings
  WARNING: SQL Warning: 0, SQLState:

This i dont understand. Can anyone explain?

2009-02-18 09:48:36 org.hibernate.util.JDBCExceptionReporter logWarnings
  WARNING: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Changed database context to 'bess_test'.

How do i specify the Database, to avoid this?

A:

You might find this helpful in the future when you want to turn on logging for a specific part of Hibernate.  This configuration should also hide the warnings that you are seeing.
# Hibernate logging
# Log everything (a lot of information, but very useful for troubleshooting)
log4j.logger.org.hibernate=FATAL
# Log all SQL DML statements as they are executed
log4j.logger.org.hibernate.SQL=INHERITED
# Log all JDBC parameters
log4j.logger.org.hibernate.type=INHERITED
# Log all SQL DDL statements as they are executed
log4j.logger.org.hibernate.tool.hbm2ddl=INHERITED
# Log the state of all entities (max 20 entities) associated with the session at flush time
log4j.logger.org.hibernate.pretty=INHERITED
# Log all second-level cache activity
log4j.logger.org.hibernate.cache=INHERITED
# Log all OSCache activity - used by Hibernate
log4j.logger.com.opensymphony.oscache=INHERITED
# Log transaction related activity
log4j.logger.org.hibernate.transaction=INHERITED
# Log all JDBC resource acquisition
log4j.logger.org.hibernate.jdbc=INHERITED
# Log all JAAS authorization requests
log4j.logger.org.hibernate.secure=INHERITED


Q:

Space in like in MySQL search AWS python

Trying to query AWS database (newbie to this). Query is as below:
dfHealthData = pd.read_sql("SELECT YearStart, LocationDesc, Topic, Question, DataValue "
                               "FROM HealthData WHERE YearStart = '2018' AND DataValueType = 'Crude Prevalence' AND Question LIKE '%18 years'" , connection_string)

Want to get string which ends in ' 18 years' (or ideally '>=18 years', but the former will do).
Error is as below.
Error retrieving from AWS: unsupported format character ' ' (0x20) at index 161

A:

% has a special meaning in python. Try to escape it:
dfHealthData = pd.read_sql("SELECT YearStart, LocationDesc, Topic, Question, DataValue FROM HealthData WHERE YearStart = '2018' AND DataValueType = 'Crude Prevalence' AND Question LIKE '%%18 years'" , connection_string)


Q:

Sync the zoho crm with sql database using c# code

I am new to ZohoCrm.
Instead of passing the hardcoded data from c# to zoho CRM, I need to pass the data from the database table to Zoho. Then I need to synchronize both the database and update it to CRM
Can any one help me?

A:

From http://www.zoho.com/crm/help/api/

Zoho CRM provides API (Application Programming Interface) for
  integrating CRM modules with third-party applications such as,
  accounting, ERP, e-commerce, self-service portals and others. With the
  Zoho CRM API, you can extract CRM data in XML or JSON format and
  develop new applications or integrate with your existing business
  applications. As the Zoho CRM API is independent of programming
  languages, you can develop applications in any programming language
  (Java, .Net, C, C++, PHP, etc.).

.NET client for interacting with Zoho CRM service https://github.com/deveel/zohocrmsharp.
Your work is the custom logic for "pass the data from data base table to Zoho"


Q:

Missing parenthesis Error when building MATERIALIZED

So I'm trying to build a complex materilized view, but I somehow don't know what I'm writing wrong
But for educational purposes, I'm trying to reverse the query while removing the joins and using intersection instead, even thought the query is working perfectly, but I do need to do it using intersections
It's been few hours I'm working on it and always having this error message

00000 -  "missing right parenthesis"

A:

This query makes no sense. There is ) in having which has no left parenthesis.
INTERSECT is done on queries that return different number of columns.
You use moe1 and moe2 aliases where they are undefined.
Please rather describe your table and tell what you want to query. It is very hard to guess your logic looking on the query.


Q:

If $kx^2-4x+3k+1>0$ for at least one $x>0$ and if $k\in S$, find $S$

Options ; $A)~ (1,\infty)~~ B)~(0,\infty)~~C)~(-1,\infty)~~D)~(-\frac 14 , \infty)$

Obviously
$$16-4(k)(3k+1)<0$$
$$k\in (-\infty, -\frac 43)\cup (1,\infty)$$
And also $k>0$ so the answer should be A)
The answer is, however, A, B, D
I think it has something to do with  ‘ least one $x>0$’ but I don’t know what the question exactly means by that

A:

If $k\ge 0$, then the said condition will always be true, as we get an upward facing parabola. (or a line, for the $k=0$ case)
If $k\lt 0$, then we need the discriminant to be $\gt 0$, for otherwise the quadratic always assumes negative values, i.e. $$16-4k(3k+1) \gt 0 \\ \implies k\in \left(-\frac 43, 1\right ) $$
Now, since the quadratic must be positive for at least one positive $x$, at least one of the roots must be positive (can you see why?), so $$\frac{4+\sqrt{16-4k(3k+1)}}{2k} \gt 0 $$
But this is never true for $k\lt 0$. Although $$\frac{4-\sqrt{16-4k(3k+1)}}{2k} \gt 0 $$ is true for $$k\in \left(-\frac 13,0\right)$$
Taking the union of the two cases, we must have that $$\boxed{k\in \left(-\frac 13, \infty\right)} $$ Only options (A),(B),(D) are subsets of this set.


Q:

Why is the Cotangent Space of Complex Projective Space Not $U(1)$-Equivariant?

I'm looking at the cotangent bundle of $CP^{N}$ at the moment in the context of equivariance. For many reasons, it seems to me that this bundle is not $U(1)$-equivariant, or, in other words, cannot be constructed as from a representation of $U(1)$ in the standard manner (see here for example) where we consider $CP^{N}$ as the base space of the principle bundle $S^{2N}$. However, I cannot find a neat convincing argument for why this should be so.
MY ATTEMPT: I would guess that $U(1)$-equivariance would mean that the bundle could be expressed as a direct sum of line bundles, but I cannot see how to show that this is not the case (even though it seems most probable). Again I would guess that some sort of Chern argument comes in, but I don't know how to caclulate Chern classes without a connection. The only connection here I know is the Grassmannian, and at this point the whole thing just becomes a mess ....

A:

If there were a representation $V$ of $U(1)$ and an isomorphism $TCP^n \cong S^{2n+1} \times_{U(1)} V$, then the tangent bundle of $S^{2n+1}$ would be the direct sum of the trivial bundle $S^{2n+1} \times V$ plus the trivial real line bundle (the vertical tangent bundle to the $S^1$-bundle. In particular, $S^{2n+1}$ is parallelizable, which implies, by a result by Adams, that $n=0,1$ or $3$. If $n=0$, then the question is void, for $n=1$, $TCP^1$ is obviously a complex line bundle.
That leaves the case of $CP^3$. If $TCP^3$ were a sum of three complex line bundles, then the total Chern class would be $(1+ax)(1+by)(1+cy)$ for some integers $a,b,c$ ($x$ is an appropriate generator of $H^2(CP^n)$. On the other hand, we know the total Chern class very well; it is $1+4x+6x^2+4 x^3$. This is discussed, without any reference to a connection, in many sources, e.g. Milnor-Stasheffs book. So you get
$$a+b+c=4, ab+bc+ac=6, abc=4.$$
It is easy that these equation do not have an integral solution (reduce modulo $2$ to conclude that $a,b,c$ have to be even).
Probably it is possible to do the higher dimensional cases in that arithmetical way, instead of nuking it with Adams' result.


Q:

Oracle equivalent of suser_name() used in SQL Server

What is the Oracle equivalent of suser_name() used in SQL Server

A:

Mostly they use SYS_CONTEXT for tracking and auditing purposes like the one below :
SELECT SYS_CONTEXT ('USERENV', 'SESSION_USER')
   FROM DUAL;


Q:

Writing an OS kernel in assembly with NASM

I want to know what is the standard way for writing a -simple- kernel to be compiled on NASM?
To get it clearer:
I was able to define the code block with all the following ways:
[segment code]
[segment .code]
segment code
segment .code

[section code]
[section .code]
section code
section .code

I need to know what is the standard way to do that, And what is the difference between them...
Thanks

A:

Your question is answer in the NASM documentation, as stated above.
The truth is.. the sections do not mean verymuch when you load your code. A kernel to be loaded, needs a complete bootloader, and a bootloader has 512b to load GDTr, , enabling A20, entering protected mode, and jumping to _kmain.
Checkout OSDev.org for more examples, and information.


Q:

Propagate V=s Flage to all sub makefiles

When ever I build kernel modules using make, I get this kind of logs
CC[M] module1
CC[M] module2
CC[M] module3
CC[M] module4

i.e just compilation or linking info about any module currently being processed.
I need to know complete information that which commands actually compiles the modules source code, what are the flags used in those command etc. e.g
gcc -Wall abcd.c

I even checked it by setting V=s , V=1, -n and -d but couldn't get what I want.
Kindly tell me how to make V=s propagate through each and every subsequent makefiles. It could be done by exporting, by how?
Thanks

A:

There are two kinds of methods:

You can build modules with "make V=1" to print verbose messages.
You can also do this by putting "export KBUILD_VERBOSE=1" line into your Makefile.

Here is an example of makefile:

TARGET  :=sysfs-sample

export KBUILD_VERBOSE=1

obj-m += $(TARGET).o

$(TARGET)-objs  := main.o

MODULE_DIR  := "$(PWD)"

all:
    CROSS_COMPILE= ARCH=x86 make -C /lib/modules/$(shell uname -r)/build M=$(MODULE_DIR) modules

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(MODULE_DIR) clean


Q:

How to add text and images statically and dynamically on aspx page in my situation

I am beginner to ASP.NET and its my first application which has view like this : http://prntscr.com/5iaiig
Here you can see that its bit similar to facebook with a difference that i want to simply demonstrate different texts on click to each button like "Home", "About", "TimeLine" and "Photo".
I dont know how to do that ?
My all code for Site.Mater is :
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebApplication1.SiteMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>

    <form runat="server">

                    Shekhar's FaceBuk

                <asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
                    <AnonymousTemplate>
                        [ Log In ]
                    </AnonymousTemplate>
                    <LoggedInTemplate>
                        Welcome <asp:LoginName ID="HeadLoginName" runat="server" />!
                        [ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/"/> ]
                    </LoggedInTemplate>
                </asp:LoginView>

                <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
                    <Items>
                        <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home"/>
                        <asp:MenuItem NavigateUrl="~/About.aspx" Text="About"/>
                        <asp:MenuItem NavigateUrl="~/About.aspx" Text="TimeLine"/>
                        <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Photos"/>
                        <asp:MenuItem Text="testing of shekhar" />
                    </Items>
                </asp:Menu>

            <asp:ContentPlaceHolder ID="MainContent" runat="server"/>

    </form>

Whereas important part is :

                <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
                    <Items>
                        <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home"/>
                        <asp:MenuItem NavigateUrl="~/About.aspx" Text="About"/>
                        <asp:MenuItem NavigateUrl="~/About.aspx" Text="TimeLine"/>
                        <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Photos"/>
                        <asp:MenuItem Text="testing of shekhar" />
                    </Items>
                </asp:Menu>

In my About.aspx the two .cs files are :
About.aspx.cs  and About.aspx.designer.cs they are as follows respectively :
namespace WebApplication1
{
    public partial class About : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get the number of labels to create.

        }
    }
}

and
namespace WebApplication1
{
    public partial class About
    {
    }
}

Now question is how to change these two classes and Site.Maser so that i can display some contents(text, image etc) on click to "About" in the just below (I have to do same for each button click but once i got idea for one i can do for others)? Thanks would be a big helping hand for me.

A:

Generally speaking, you never need to bother with the designer.cs files. And if all you need to do is display contents like text, image, etc, then you don't need to bother with the *.cs files at all. Just put the markup directly in the about.aspx page. Wrap it inside of an asp:Content tag so that it gets included in with your master page, like so:
About.aspx
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="WebApplication1.About" %>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">

About Us

We code in HTML5 and CSS3

</asp:Content>


Q:

How can I make a right angle symbol ⦝?

How can I make the symbol ⦝ (measured right angle with dot, U+299D) with LaTeX?
(I tried Detexify and The Comprehensive LATEX Symbol List)

A:

Picture mode!
\documentclass{article}
\usepackage{amsmath,pict2e}

\newcommand{\measuredrightanglewithdot}{%
  \mathord{%
    \mspace{1mu}%
    \text{\mrawd}%
    \mspace{1mu}%
  }%
}

\newcommand{\mrawd}{%
  \setlength{\unitlength}{1ex}%
  \begin{picture}(1,1)
  \roundcap
  \polyline(0,1)(0,0)(1,0)
  \put(0,0){\arc[0,90]{0.5}}
  \put(0.2,0.2){\circle*{0.1}}
  \end{picture}%
}

\begin{document}

$a\measuredrightanglewithdot_{\measuredrightanglewithdot}$

\end{document}

Alternatively, one can import it from the STIX fonts.
\documentclass{article}
\usepackage{amsmath,pict2e}

% import from STIX
\DeclareFontEncoding{LS1}{}{}
\DeclareFontSubstitution{LS1}{stix}{m}{n}
\DeclareFontFamily{LS1}{stixfrak}{\skewchar\font127 }
\DeclareFontShape{LS1}{stixfrak}{m}{n} {<-> stix-mathfrak}{}
\newcommand{\rightanglemdot}{\text{\usefont{LS1}{stixfrak}{m}{n}\symbol{"3C}}}
%%%

% picture mode
\newcommand{\measuredrightanglewithdot}{\mathord{\mspace{1mu}\text{\mrawd}\mspace{1mu}}}
\newcommand{\mrawd}{%
  \setlength{\unitlength}{1ex}%
  \begin{picture}(1,1)
  \roundcap
  \polyline(0,1)(0,0)(1,0)
  \put(0,0){\arc[0,90]{0.5}}
  \put(0.2,0.2){\circle*{0.1}}
  \end{picture}%
}

\begin{document}

$a\measuredrightanglewithdot_{\measuredrightanglewithdot}$ (picture mode)

$a\rightanglemdot_{\rightanglemdot}$ (STIX)

\end{document}

A:

And a TikZ version:
\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz}

\newcommand\RADot{%
  \mathord{%
    \mspace{1mu}%
    \text{\radot}%
    \mspace{1mu}%
  }%
}

\newcommand\radot{%
    \tikz[line cap=round,x=1ex,y=1ex,line width=0.3pt]
    {\draw (0,1) |- (1,0) (0.55,0) arc(0:90:0.55); \fill (0.23,0.23) circle (0.05);}%
}

\begin{document}

$a\RADot_{\RADot_{\RADot}}$

\end{document}


Q:

C# string Parsing to variable types

I want to parse a string into a type easily, but I don't want to write wrapper code for each type, I just want to be able to do "1234".Parse() or the like and have it return 1234. This should work for any type that has parsing capabilities.

A:

This trick should work. It uses the type of the variable you're assigning to automagically:
public static class StringExtensions {
    public static ParsedString Parse(this string s) {
        return new ParsedString(s);
    }
}
public class ParsedString {
    string str;
    public ParsedString(string s) {
        str = s;
    }
    public static implicit operator int(ParsedString s) {
        return int.Parse(s.str);
    }
    public static implicit operator double(ParsedString s) {
        return double.Parse(s.str);
    }
    public static implicit operator short(ParsedString s) {
        return short.Parse(s.str);
    }
    public static implicit operator byte(ParsedString s) {
        return byte.Parse(s.str);
    }
    // ... add other supported types ...
}

Usage:
int p = "1234".Parse();

I would prefer explicitly parsing using framework provided methods rather than relying on these kind of tricks.

A:

My solution works for any type that implements the static method TryParse(string, out T), whether it's a class or a struct. Also, it will work for nullable structs, e.g.
"1234".Parse<int>() == 1234
"asdf".Parse<int>() == 0 // i.e. default(int)
"1234".Parse<int?>() == 1234
"asdf".Parse<int?>() == null
"2001-02-03".Parse<DateTime?>() == new DateTime(2009, 2, 3)

and since System.Net.IPAddress has TryParse,
"127.0.0.1".Parse<IPAddress>().Equals(new IPAddress(new byte[] { 127, 0, 0, 1 }))

I create the code with the System.Linq.Expressions framework, and then cache the created lambda. Since this is done in a generic static class with a specified type, this happens only once per type to parse.
public static class StringExtensions
{
    ///
    /// Parse the <paramref name="target"/> as a <typeparamref name="T"/>. If this cannot be achieved, return the default value of <typeparamref name="T"/>.
    ///
    /// <typeparam name="T">The type to parse into.</typeparam>
    /// <param name="target">The string to parse.</param>
    /// <returns>The resultant <typeparamref name="T"/> or the default of <typeparamref name="T"/>.</returns>
    /// <example>
    ///
    /// "1234".Parse&ltint>() == 1234;
    /// "a".Parse&ltint>() == 0;
    /// "a".Parse&ltint?>() == null;
    /// "2010-01-01".Parse<DateTime?>() == new DateTime(2010, 1, 1)
    /// "2010-01-01a".Parse<DateTime?>() == null
    /// "127.0.0.1".Parse<System.Net.IPAddress>().Equals(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 }))
    /// "".Parse<System.Net.IPAddress>() == null
    ///
    /// </example>
    public static T Parse<T>(this string target)
    {
        return ParseHelper<T>.Parse(target);
    }

    ///
    /// Parse the <paramref name="target"/> as a <typeparamref name="T"/>. If this cannot be achieved, return <paramref name="defaultValue"/>
    ///
    /// <typeparam name="T">The type to parse into.</typeparam>
    /// <param name="target">The string to parse.</param>
    /// <param name="defaultValue">The value to return if <paramref name="target"/> could not be parsed.</param>
    /// <returns>The resultant <typeparamref name="T"/> or <paramref name="defaultValue"/>.</returns>
    /// <example>
    ///
    /// "1234".Parse&ltint>(-1) == 1234;
    /// "a".Parse&ltint>(-1) == -1;
    /// "2010-01-01".Parse<DateTime?>(new DateTime(1900, 1, 1)) == new DateTime(2010, 1, 1)
    /// "2010-01-01a".Parse<DateTime?>(new DateTime(1900, 1, 1)) == new DateTime(1900, 1, 1)
    /// "127.0.0.1".Parse<System.Net.IPAddress>(new System.Net.IPAddress(new byte[] { 0, 0, 0, 0 })).Equals(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 }))
    /// "".Parse<System.Net.IPAddress>(new System.Net.IPAddress(new byte[] { 0, 0, 0, 0 })).Equals(new System.Net.IPAddress(new byte[] { 0, 0, 0, 0 }))
    ///
    /// </example>
    public static T Parse<T>(this string target, T defaultValue)
    {
        return ParseHelper<T>.Parse(target, defaultValue);
    }

    private static class ParseHelper<T>
    {
        private static readonly Func<string, T, T, T> _parser;

        static ParseHelper()
        {
            Type type = typeof(T);
            bool isNullable = false;
            if (type.GetGenericArguments().Length > 0 && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                isNullable = true;
                type = type.GetGenericArguments()[0];
            }

            ParameterExpression target = Expression.Parameter(typeof(string), "target");
            ParameterExpression defaultValue = Expression.Parameter(typeof(T), "defaultValue");
            ParameterExpression result = Expression.Parameter(typeof(T), "result");
            if (isNullable)
            {
                Type helper = typeof(NullableParseHelper<>);
                helper = helper.MakeGenericType(typeof(T), type);
                MethodInfo parseMethod = helper.GetMethod("Parse");
                _parser = Expression.Lambda<Func<string, T, T, T>>(
                    Expression.Call(parseMethod, target, defaultValue),
                    target, defaultValue, result).Compile();
            }
            else
            {
                MethodInfo tryParseMethod = (from m in typeof(T).GetMethods()
                                             where m.Name == "TryParse"
                                             let ps = m.GetParameters()
                                             where ps.Count() == 2
                                                && ps[0].ParameterType == typeof(string)
                                                && ps[1].ParameterType == typeof(T).MakeByRefType()
                                             select m).SingleOrDefault();

                if (tryParseMethod == null)
                {
                    throw new InvalidOperationException(string.Format("Cannot find method {0}.TryParse(string, out {0})", type.FullName));
                }
                _parser = Expression.Lambda<Func<string, T, T, T>>(
                    Expression.Condition(
                        Expression.Call(tryParseMethod, target, result),
                        result,
                        defaultValue),
                    target, defaultValue, result).Compile();
            }
        }

        public static T Parse(string target)
        {
            return _parser.Invoke(target, default(T), default(T));
        }

        public static T Parse(string target, T defaultValue)
        {
            return _parser.Invoke(target, defaultValue, default(T));
        }

        private static class NullableParseHelper<TBase> where TBase : struct
        {
            private static readonly Func<string, TBase?, TBase, TBase?> _parser;

            static NullableParseHelper()
            {
                MethodInfo tryParseMethod = (from m in typeof(TBase).GetMethods()
                                             where m.Name == "TryParse"
                                             let ps = m.GetParameters()
                                             where ps.Count() == 2
                                                && ps[0].ParameterType == typeof(string)
                                                && ps[1].ParameterType == typeof(TBase).MakeByRefType()
                                             select m).SingleOrDefault();

                if (tryParseMethod == null)
                {
                    throw new InvalidOperationException(string.Format("Cannot find method {0}.TryParse(string, out {0})", typeof(TBase).FullName));
                }
                ParameterExpression target = Expression.Parameter(typeof(string), "target");
                ParameterExpression defaultValue = Expression.Parameter(typeof(TBase?), "defaultValue");
                ParameterExpression result = Expression.Parameter(typeof(TBase), "result");
                _parser = Expression.Lambda<Func<string, TBase?, TBase, TBase?>>(
                    Expression.Condition(
                        Expression.Call(tryParseMethod, target, result),
                        Expression.ConvertChecked(result, typeof(TBase?)),
                        defaultValue),
                    target, defaultValue, result).Compile();
            }

            public static TBase? Parse(string target, TBase? defaultValue)
            {
                return _parser.Invoke(target, defaultValue, default(TBase));
            }
        }
    }
}

pants!

A:

Why can't you use the parsing already available?
int.Parse("1234");
decimal.Parse("1234");
double.Parse("1234");

Or use TryParse if you're not sure it will be able to successfully parse.
Or if you wanted to implement it as an extension method, take a look at this article that will show you how to create a Generic String.Parse method.
Edit: I have no idea how that site went down so quickly after I posted my answer. Here is the class that the article created:
using System;
using System.ComponentModel;

public static class Parser {

     public static T Parse<T>(this string value) {
        // Get default value for type so if string
        // is empty then we can return default value.
        T result = default(T);

        if (!string.IsNullOrEmpty(value)) {
          // we are not going to handle exception here
          // if you need SafeParse then you should create
          // another method specially for that.
          TypeConverter tc = TypeDescriptor.GetConverter(typeof(T));
          result = (T)tc.ConvertFrom(value);
        }

        return result;
    }
}

Examples:
// regular parsing
int i = "123".Parse<int>();
int? inull = "123".Parse<int?>();
DateTime d = "01/12/2008".Parse<DateTime>();
DateTime? dn = "01/12/2008".Parse<DateTime?>();

// null values
string sample = null;
int? k = sample.Parse<int?>(); // returns null
int l = sample.Parse<int>();   // returns 0
DateTime dd = sample.Parse<DateTime>(); // returns 01/01/0001
DateTime? ddn = sample.Parse<DateTime?>(); // returns null


Q:

Algorithm to check availability with two time frames

What would be the best algorithm to check the availability of a device for rental with two time frames?
I have the timeframe of the device and the existing rental (start & end date) and the timeframe of the "new" rental.
Example:
New rental: 18 April 2013 - 25 April 2013

In this cases I'd like to return false:
a) Existing rental: 20 April 2013 - 24 April 2013
b) Existing rental: 16 April 2013 - 24 April 2013
c) Existing rental: 20 April 2013 - 28 April 2013
d) Existing rental: 16 April 2013 - 28 April 2013

There could be even more cases but I think it's clear what I want.

A:

I think what you need is a good Data Structure or some logics. Hope the logic below can filter out all overlapping time frames.
 var overlappingIntervals = intervals
                    .Where(r =>
                        (r.Start <= toCheck.Start && r.End >= toCheck.End) //inside a timeframe
                    || (r.Start >= toCheck.Start && r.End <= toCheck.End) //other is inside our timeframe
                    || (r.Start >= toCheck.Start && r.End >= toCheck.End && r.Start <=toCheck.End) //end overlap
                    || (r.Start <= toCheck.Start && r.End <= toCheck.End && r.End >= toCheck.Start)// start overlap

                    ).ToList();

I have also placed commnets to detect conditions.
class Program
    {
        static void Main(string[] args)
        {
            List<DateInterval> intervals = new List<DateInterval>();
            intervals.Add(new DateInterval(Convert.ToDateTime("26 April 2013"), Convert.ToDateTime("27 April 2013")));
            intervals.Add(new DateInterval(Convert.ToDateTime("16 April 2013"), Convert.ToDateTime("24 April 2013")));
            intervals.Add(new DateInterval(Convert.ToDateTime("20 April 2013"), Convert.ToDateTime("28 April 2013")));
            intervals.Add(new DateInterval(Convert.ToDateTime("16 April 2013"), Convert.ToDateTime("28 April 2013")));

            DateInterval toCheck = new DateInterval(Convert.ToDateTime("16 April 2013"),
                                                    Convert.ToDateTime("25 April 2013"));

            var overlappingIntervals = intervals
                .Where(r =>
                    (r.Start <= toCheck.Start && r.End >= toCheck.End) //inside a timeframe
                || (r.Start >= toCheck.Start && r.End <= toCheck.End) //other is inside our timeframe
                || (r.Start >= toCheck.Start && r.End >= toCheck.End && r.Start <=toCheck.End) //end overlap
                || (r.Start <= toCheck.Start && r.End <= toCheck.End && r.End >= toCheck.Start)// start overlap

                ).ToList();
            Console.Write(overlappingIntervals.Count);

        }
    }

    public class DateInterval
    {

        public DateInterval(DateTime Start, DateTime End)
        {
            this.Start = Start;
            this.End = End;
        }
        public DateTime Start { get; set; }
        public DateTime End { get; set; }
    }


Q:

Tag merge request: [webstart] and [java-web-start]

There are two Java Web Start tags:
webstart: x 239
java-web-start: x 320

Both tags refer to the same technology
webstart's wiki refers to java-web-start's wiki
both wiki point to this page
all questions tagged with webstart clearly relate to Java Web Start

I suggest they be merged into java-web-start (which appears in the auto-complete list if one types "webstart" in the Tags box when asking a new question).

A:

I deleted the suggested jnlp ← java-web-start synonym. At minimum, if the two really are that related, that synonym should be reversed.
I also added the requested java-web-start ← webstart synonym and approved the suggested javaws synonym. Should be all good to go now.


Q:

How to stop alert box press enter loop?

When the user presses enter on the document, I show an alert box with alert().
The default behaviour the browser (Chrome 27 on Mac OS X 10.8.4) has is when you press enter when focused on the alert box, it will close it. That will trigger the enter on the document, showing the alert box again. You can see how it can loop.
Note that when I use my mouse to click OK in the alert box, the loop does not happen.
How can I prevent this looping?
An example (the real way I use this is a lot more complicated):
$(document).keyup(function(e) {
    e.preventDefault();

    var keyCode = e.keyCode || e.which;

    if (keyCode == 13) {
        alert('Hello world!');
    }

    return false;
});

A:

you can delegate the keydown event and use stopPropagation() to prevent the event from bubbling up to the document when it is triggered on the alert dialog, like so: http://jsfiddle.net/KNyzc/
$(document).on( "keydown", function(e) {
    e.stopPropagation();
    var keyCode = e.keyCode || e.which;

    if (keyCode == 13) {
        alert('Hello world!');
    }
});

( actually, you don't need to use stopPropagation at all. Just use the keydown event. )


Q:

I'm trying to setup my 401k with 5% match from my employer

I am newbie and I need help setting up my 401k. Basically, I just want to avail my employer's maximum match, and 5% is the minimum needed to reach it. But I'm not sure if I am doing it right. Here's the screenshot of my current setting:

A:

Based on the numbers on the screen, it looks like your income is in the range of $9,325 to $37,950 per year. This puts you in the 15% tax bracket. I personally would recommend you move the slider all the way to the right and put your entire contribution into the 401K Roth (so you'll have 0% pre tax and 100% post tax.) The reasoning here is that you'll pay the 15% tax now which is on the low side, but you'll never pay tax on the money's growth for the rest of your life, including when you take it out at retirement. If you do this your take home will be approximately $9 less per paycheck (or a little higher depending on your state income tax).
Note that the company match will go into a traditional 401K so you'll likely see two separate accounts on your 401K statements.
The choice to go with traditional vs roth 401k is complicated and there are many variables. As a rule of thumb, the lower your current tax rate, the more likely you should be to lean towards the roth. Some exceptions might be if you are close to retirement age and you don't have much saved for retirement, or if you live in a state with a high income tax rate and you don't think you'll still live there when you retire, or if you are living paycheck to paycheck and the slight difference in take home pay would make a difference to you.


Q:

Как вывести блок за пределы родительского. CSS

Привет!
Есть вопрос.
Например имеем родительского блок.
В нем есть дочерний.
Как вывести этот блок за пределы?
Код:

#blok1 {
    margin: 100px 100px;
  width:200px;
    height:200px;
    background:green;
}
#blok2 {
  width:100px;
    height:100px;
    background:red;
}

A:

Абсолютное позиционирование либо относительно родителя, либо относительно документа.
Пример смещения относительно родителя:
http://jsfiddle.net/QrWSX/22/

#blok1 {
    position: relative;
    margin: 100px 100px;
  width:200px;
    height:200px;
    background:green;
}
#blok2 {
    position: absolute;
    top: -100px;
    left: -100px;
  width:100px;
    height:100px;
    background:red;
}


Q:

WP8 LongListSelector: Add new item without scrolling to top

When I add items to the ItemsSource of a LongListSelector, the LongListSelector automatically scrolls to the top. Is there anyway to disable this?
I tried to use the ScrollTo function after loading, but that is not good enough since I want to stay at the exact same scroll position (meaning I don't want the LostListSelector to scroll at all, when I add a new item to its ItemsSource).

A:

The problem was that I used a List instead of ObservableCollection as the ItemsSource for the LongListSelector and that I used the Lists set function, which implements NotifyPropertyChanged, to assign images to the LongListSelector. This NotifyPropertyChanged event causes the LongListSelector to scroll to index 0 of the ItemsSource.
So I solved it by changing the ItemsSource to an ObservableCollection and use Add instead of the setter for the ObservableCollection.


Q:

How to stop "Floppy Disk" icon from appearing in 13.04 launcher?

Whenever I remove external hard drive or USB flash drive, a Floppy Disk icon appears in launcher. If I unlock it, it goes away but only until I use a USB device again.
How to stop this?
BTW I don't have an actual floppy disk drive installed. However, in Nautilus "Floppy Disk" is listed among devices. Is this normal?

A:

You can try creating an udev rule to hide the floppy from the unity launcher and nautilus.
For Ubuntu 12.10 & 13.04

Create the udev rule.

sudo nano /etc/udev/rules.d/99-hide-floppy.rules
Match the KERNEL key with your device (floppy=fd)* and assign the UDISKS
variable.
The content of the 99-hide-floppy.rules file would be:
KERNEL=="fd*", ENV{UDISKS_IGNORE}="1"

To save the changes in nano... Ctrl+O, then Enter and finally Ctrl+X.

Finally refresh the udev rules with:

sudo udevadm trigger

For Ubuntu 12.04

The only difference is the name of the UDISKS variable.
It should be ENV{UDISKS_PRESENTATION_HIDE} instead ENV{UDISKS_IGNORE}
KERNEL=="fd*", ENV{UDISKS_PRESENTATION_HIDE}="1"

Hope this helps.


Q:

set Message Subject for MFMailComposeViewController but don't show it in the navigation bar

How can i set a subject to a MFMailComposeViewController but do not show the title in the navigation bar?
The thing is that i have a background image and the text overlays on the image and it doesn't look good.. Any ideas?

A:

You should not be customizing the interface of the mail composer vc:
From the docs:

Important: The mail composition interface itself is not customizable and must not be modified by your application. In addition, after presenting the interface, your application is not allowed to make further changes to the email content. The user may still edit the content using the interface, but programmatic changes are ignored. Thus, you must set the values of content fields before presenting the interface.


Q:

Copying atribute table for new shp file

i already copied the selected layer from layer 1 to layer 2.But the atribute in layer 2 only contain id.How can i get the field just like the second images for my selected feature in layer 2 ??

A:

The shapefile into which you are pasting the features must have the same attribute schema.  Then, they should automatically fill in the right fields when pasting.
If you are just trying to make a new shapefile that is just a subset of an existing shapefile, it would probably be easier to select the desired features, then right click on the layer in the table of contents and save the layer as a new shapefile.  Make sure to check the "Save only selected features" checkbox.


Q:

Applying a filter of unknown elements using array. Or hiding select records from user

Using a split database, everyone gets a front end with a local table I use as a 'cart' like in online shopping.
I'm copying records to a local table from stock. I don't want the record I copied across to be allowed to be transferred over again making duplicates. I also don't want to delete the original record, just modify it.
So I want them to edit the records copy locally then hit a button that will update the record on the database back end. If they don't hit the button and close the front end, no changes are made. Assume the temp table is wiped on start up.
To stop duplicate records I want to hide select records from the particular user of the front end database only. So if the Access app crashes the record isn't hidden for all users.
Idea: What If I add a Stock_ID (hidden) field to the local table? Then I can poll the column and if any Stock_ID matches the ID of the record I want to copy a message box says Error, record already exists and cancels the record copy?

A:

I think you're saying you want to show the front end user only those stock records whose Stock_ID values are not present in the local table.
If that is correct, you can use an "unmatched query" to display those stock records.
SELECT s.*
FROM
    stock AS s
    LEFT JOIN [local] AS l
    ON s.Stock_ID = l.Stock_ID
WHERE l.Stock_ID Is Null;

The Access query designer has a query wizard for this task. It should be worth a look.


Q:

pandas: updating column values when merging DataFrames

Is there an elegant way to merge the values of two columns with identical names in two different dataframes by updating the values in the first dataframe with the values of the column in the second dataframe if values are available (i.e. not null) in the second dataframe?
So if the two dataframes are:
df1 = pd.DataFrame([ 1,    2,    None, 3], columns=["a"], index=[0,1,2,3])
df2 = pd.DataFrame([ None, None, 4,    5], columns=["a"], index=[0,1,2,3])

then the desired output would be:
df3 = pd.DataFrame([ 1,    2,    4,    5], columns=["a"], index=[0,1,2,3])

While I can conceive of a way doing this by performing first a merge() and then using 'apply()' with a custom function to merge the values of the resulting columns together, this seems overly complex. Moreover, I need to do this for multiple columns. Is there a more elegant way to do this?
The function I am looking for would behave as if performing a left merge with 'overwrite_values=True', except for the fact that the latter parameter does not exist of course.
A slightly more complex example with two columns:
df1 = pd.DataFrame([ [1, 'a'],    [2, 'b'],    [None, None], [3, None] ],
                   columns=["a", "b"], index=[0,1,2,3])
df2 = pd.DataFrame([ [None, None],[None, 'x'],[4, 'c'], [5, 'd'] ],
                   columns=["a", "b"], index=[0,1,2,3])

then the desired output would be:
df3 = pd.DataFrame([ [1, 'a'],    [2, 'x'],    [4, 'c'], [5, 'd']],
                   columns=["a", "b"], index=[0,1,2,3])

Many thanks!

A:

You want combine_first:
In [19]:
df1 = pd.DataFrame([ [1, 'a'],    [2, 'b'],    [None, None], [3, None] ],
                   columns=["a", "b"], index=[0,1,2,3])
df2 = pd.DataFrame([ [None, None],[None, 'x'],[4, 'c'], [5, 'd'] ],
                   columns=["a", "b"], index=[0,1,2,3])
df1.combine_first(df2)

Out[19]:
     a  b
0  1.0  a
1  2.0  b
2  4.0  c
3  3.0  d


Q:

What is better solution for online/offline user feature firestore or realtime?

I got a database of users. Need to implement list which shows only online users. Unfortunately realtime does not filter by key. So it is possible only in Firestore. But Firestore charge for each write/read/update operation so it might be very expensive to use that feature since users are going offline/online all the time and there will be a lot of write/read/update operations. As a solution, I did separate tables in realtime which saves only online users and here I don't need to pay for write/read/update. But at the same time, it is duplicating the database which is also not good practice.
Could you please share your thought on which solution is better from "price" and "clean" point of view. To pay for Firestore and use one db, or use two db but not to pay for each operation?

A:

What is better solution for online/offline user feature Firestore or realtime?

It depends on what your requirements are, but you should not consider using one or the other. There is nothing wrong with using both.

Unfortunately realtime does not filter by key.

If you check the docs, there is a section named sorting and filtering data, where you'll find a method named orderByKey():

Order results by child keys.

So actually it is possible to filter the results of a query and order them in the same time.

As a solution I did the separate tables in realtime which saves only online users and here I don't need to pay for write/read/update.

That's a good solution you can go ahead with. Actually, both Cloud Firestore and Firebase Realtime Database work very well together.

But at the same time, it is duplicating the database which is also not good practice.

Oh, it is. This practice is called denormalization and is a common practice when it comes to Firebase. For a better understanding, I recommend you see this video, Denormalization is normal with the Firebase Database and check my answer from the following post:

What is denormalization in Firebase Cloud Firestore?

So you can denormalize the data to obtain queries that are actually not possible or to save some write operation when it comes to Cloud Firestore.

Could you please share your thought on which solution is better from "price" and "clean" point of view. To pay for Firestore and use one db, or use two db but not to pay for each operation?

Use them both.


Q:

Immutable JS - Creating an OrderedMap from a List

I have a List
const results = [94, 88, 121, 17];

and also a Map
const posts = {
   94: { title: 'Foo bar', content: 'Blah blah blah...' },
   88: { title: 'Bar Foo', content: 'Blah blah blah...' },
   121: { title: 'Bing bang', content: 'Blah blah blah...' },
   17: { title: 'Ning nang', content: 'Blah blah blah...' },
};

The List actually holds the order of the items in the Map as maps/objects can not guarantee order.
Whats the most efficient way to create an OrderedMap using both the List and the Map above?

A:

There's no built-in constructor in Immutable.js that will handle this, so you'll have to do the mapping yourself:
const orderedPosts = new OrderedMap(results.map(key => [key, posts[key]]))


Q:

Send build status from Travis to Sauce Labs

I have my testing up and running with Travis/SauceLabs. Now I would like to add a SauceLabs test badge to my repo.
I added the badge markdown to my Readme file but how can I send the build pass/fail to SauceLabs? I found this instructions for Selenium,

Key:   passed
Value type: bool
Example:    "passed": true

but how/where do I add info in my files for my Grunt-Karma/Travis/SauceLabs testing?

A:

The Karma-Sauce-Launcher was using the wrong id, and this was fixed on Github by this PR and released in NPM as version 0.2.5
Aditionally the saucelabs reporter has to be added to the gruntfile options, besides the existing ones or the default progress.
So the bugfix I added to my package.json:
"karma-sauce-launcher": "~0.2.5"

and added this:
reporters: ['progress', 'saucelabs'],

in the Karma options.


Q:

C# - Check file size while writing - Change file in middle

I am looping through directories and getting the files within
While looping, I am writing the file's fullpath name to a file using a StreamWriter
My problem is that I have to control the size of the file - it cant exceed 60K
How can I accomplish this?
I tried changing the streamwriter in the middle of the loop like this:
if (myPaths.Length >= 60000)
{
    outFile = "c:\\tag\\GS_dirData_" + (FileCounter += 1).ToString() + ".txt";
    StreamWriter myStream = new StreamWriter(outFile);
}

But I am getting an error warning that I cant do this
Here is my full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using Microsoft.Win32;
using System.Globalization;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo di = new DirectoryInfo("c:/myDir/");
        string outputFile = "c:\\dirA\\PathsFile.txt";
        StreamWriter sw = new StreamWriter(outputFile);

        string doneFile = "c:\\dirA\\ConfirmComplete.txt";
        if (File.Exists(doneFile)) File.Delete(doneFile);

        int ct = 0;

        ct = getAllFiles(di, "*.i", sw, outputFile);

        StreamWriter myDoneFile = new StreamWriter(doneFile);
        myDoneFile.AutoFlush = true;
        myDoneFile.WriteLine("Done");
        myDoneFile.WriteLine("Processed " + ct.ToString() + " files");
        myDoneFile.WriteLine("File Size = "+outputFile.Length.ToString());
    }

    static int getAllFiles(DirectoryInfo dir, string searchPattern, StreamWriter myStream, string outFile)
    {
        var directories = dir.GetFiles(searchPattern, SearchOption.AllDirectories);
        int counter = 0;
        int FileCounter = 1;
        foreach (var file in directories)
        {
            if (file.FullName.Contains("\\BAK\\")) continue;
            myStream.WriteLine(file.FullName);
            counter += 1;
            FileInfo myPaths = new FileInfo(outFile);
            if (myPaths.Length >= 60000)
            {
                myStream.Close();
                outFile = "c:\\dirA\\GS_dirData_" + (FileCounter += 1).ToString() + ".txt";
                StreamWriter myStream = new StreamWriter(outFile);
            }
        }
        return counter;
    }
}

}
Any help would be appreciated
I would gladly accept any enhancement ideas
Thanks
David

A:

Try changing your code to this:
        if (myPaths.Length >= 60000)
        {
            myStream.Close();
            outFile = "c:\\dirA\\GS_dirData_" + (FileCounter += 1).ToString() + ".txt";
            myStream = new StreamWriter(outFile);
        }

You are creating a locally scoped variable inside of the if statement.  You need to set the new StreamWriter to the function scoped myStream.


Q:

Given the Dirichlet generating function for the divisor sum case, what is the Dirichlet generating function for the Möbius function case?

From a search in the OEIS I found from the comment by Antonio G. Astudillo that:
$$\sum _{n=1}^{\infty} \frac{\left(\sum\limits_{d|n}d^{c}\right) \left(\sum\limits_{d|n}d^{z}\right)}{n^{\text{s}}}=\frac{\zeta (s) \zeta (s-c) \zeta (s-z) \zeta (-c+s-z)}{\zeta (-c+2 s-z)}$$
What is then the Dirichlet generating function for:
$$\sum _{n=1}^{\infty} \frac{\left(\sum\limits_{d|n}\mu(d) d^{c}\right) \left(\sum\limits_{d|n}\mu(d)d^{z}\right)}{n^{\text{s}}}=?$$
where $\mu(d)$ is the Möbius function of a divisor $d$. Above $\zeta(s)$ is of course the Riemann zeta function.

A:

First let us try to evaluate
$$L_1(s) = \sum_{n\ge 1} \frac{1}{n^s} q_{a,b}(n) =
\sum_{n\ge 1} \frac{1}{n^s}
\left(\sum_{d|n} d^a\right) \left(\sum_{d|n} d^b\right).$$
With  the prime factorization of $n$ being
$$n = \prod_p p^v$$
we get for
$$q_{a,b}(n) =
\prod_p \frac{p^{av+a}-1}{p^a-1}
\frac{p^{bv+b}-1}{p^b-1}.$$
This yields for the Euler product
$$L_1(s) = \prod_p
\left(1 + \sum_{v\ge 1} \frac{1}{p^{vs}}
\frac{p^{av+a}-1}{p^a-1}
\frac{p^{bv+b}-1}{p^b-1}\right)
\\ = \prod_p
\left(1 + \frac{1}{p^a-1} \frac{1}{p^b-1}
\sum_{v\ge 1} \frac{1}{p^{vs}}
(p^{(a+b)v+a+b} - p^{av+a} - p^{bv+b} + 1)\right)
\\ = \prod_p
\left(\frac{1}{p^a-1} \frac{1}{p^b-1}
\sum_{v\ge 0} \frac{1}{p^{vs}}
(p^{(a+b)v+a+b} - p^{av+a} - p^{bv+b} + 1)\right)
\\ = \prod_p
\left(\frac{1}{p^a-1} \frac{1}{p^b-1}
\\ \times
\left(\frac{p^{a+b}}{1-1/p^{s-(a+b)}}
- \frac{p^{a}}{1-1/p^{s-a}}
- \frac{p^{b}}{1-1/p^{s-b}}
+ \frac{1}{1-1/p^s}
\right)\right)
\\ = \prod_p
\left(\frac{1}{p^a-1} \frac{1}{p^b-1}
\frac{1}{1-1/p^{s-(a+b)}}
\frac{1}{1-1/p^{s-a}}
\frac{1}{1-1/p^{s-b}}
\frac{1}{1-1/p^s}
\\ \times \left(p^{a+b}-p^a-p^b+1
- (p^{2a+2b} - p^{2a+b} - p^{a+2b} + p^{a+b})/p^{2s}
\right)\right)
\\ = \prod_p
\left(
\frac{1}{1-1/p^{s-(a+b)}}
\frac{1}{1-1/p^{s-a}}
\frac{1}{1-1/p^{s-b}}
\frac{1}{1-1/p^s}
\left(1-p^{a+b}/p^{2s}\right)\right).$$
We now obtain by inspection that
$$L_1(s) = \frac{\zeta(s-(a+b))\zeta(s-a)\zeta(s-b)\zeta(s)}
{\zeta(2s-(a+b))}$$
as claimed. Continuing we introduce
$$L_2(s) = \sum_{n\ge 1} \frac{1}{n^s} r_{a,b}(n) =
\sum_{n\ge 1} \frac{1}{n^s}
\left(\sum_{d|n} \mu(d) d^a\right)
\left(\sum_{d|n} \mu(d) d^b\right).$$
This time we have
$$r_{a,b}(n) =
\prod_p (1-p^a) (1-p^b).$$
We get the Euler product
$$L_2(s) = \prod_p
\left(1 + \sum_{v\ge 1} \frac{1}{p^{vs}}
(1-p^a)(1-p^b)\right)
\\= \prod_p
\left(1 + (1-p^a)(1-p^b) \frac{1/p^s}{1-1/p^s}\right)
\\ = \zeta(s)
\prod_p (1 - 1/p^s +
1/p^s - 1/p^{s-a} - 1/p^{s-b} + 1/p^{s-(a+b)})
\\ = \zeta(s)
\prod_p \left(1 + \frac{p^{a+b}-p^a-p^b}{p^s}\right)
\\ = \zeta(s)
\sum_{n\ge 1} \frac{1}{n^s} \mu(n)^2
\prod_{p|n} (p^{a+b}-p^a-p^b).$$
The inner product runs  over genuine prime divisors excluding one.
This seems to be the best we  can do at this point. What we have shown
here is that
$$\sum_{d|n} \mu(d)^2 \prod_{p|d} (p^{a+b}-p^a-p^b)
= \left(\sum_{d|n} \mu(d) d^a\right)
\left(\sum_{d|n} \mu(d) d^b\right).$$


Q:

Trying to access videos using Google Photos API always returns 403

When trying to access video-mediaItems from Google Photos using the format baseUrl+"=dv" (specified in the docs here), I always get a 403 error. Images, on the other hand work just fine (Including thumbails for the videos).
I recall some videos worked yesterday, but today none of them work. I have checked my API Quotas and they are nowhere near full.
A basic google 403 page is returned along with the request:
Link to screenshot

A:

i am getting same issue, i think it become from google server, and they are will fix soon on our serverside