text:
Q: @DSLMarker not limiting the scope of DSL i'm building a Kotlin DSL for HTML that caters for very specific requirements i have (hence not using kotlinx.html)
        DIV(classes = "div1") {
            +"text1"
            a(href = "#0") {
                +"text2"
                div(classes = "div2") {
                    +"text3"
                    href = "#1"
                }
                div(classes = "div3") {
                    +"text4"
                    href = "#2"
                }
            }
            hr(classes = "hr1")
            span(classes = "span1") {
                +"text5"
            }
        }

In the example above, i'm able to call href in any of the child elements of a instead of having to do this@a.href = "". How do i limit the scope so that this will only be of type DIV in this example and throw a compiler error when calling href since DIV doesn't have an href property?
Here's a shortened version of the DIV class
https://github.com/persephone-unframework/dsl/blob/master/src/main/kotlin/io/persephone/dsl/element/DIV.kt
@DslMarker
annotation class DivMarker

@DivMarker
class DIV(
    classes: String? = null,
    ....
    init: (DIV.() -> Unit)? = null
) : Tag(
    tagName = "div",
    selfClosing = false
) {

    fun a(
        classes: String? = null,
        ....
        init: (A.() -> Unit)? = null
    ) = A().let {

        this.children.add(it)
        ....
        init?.invoke(it)
        it
    }

    ....

}

Similarly, class A is also marked:
https://github.com/persephone-unframework/dsl/blob/master/src/main/kotlin/io/persephone/dsl/element/A.kt
@DslMarker
annotation class AMarker

@AMarker
class A(
    href: String? = null,
    ...
    init: (A.() -> Unit)? = null
) : Tag(
    tagName = "a",
    selfClosing = false
) {

    fun div(
        classes: String? = null,
        init: (DIV.() -> Unit)? = null
    ) = DIV().let {

        this.children.add(it)

        ....

        init?.invoke(it)
        it
    }

    ....
}

Any idea why the @DslMarker annotation is not limiting the scope in this scenario and how i can fix it?

A: It seems annotating the base class, in this case Tag, does the trick, that probably means all those other annotations serve no purpose?
@DslMarker
annotation class TagMarker

@TagMarker
abstract class Tag(val tagName: String, var selfClosing: Boolean = false): Element {

    val children = arrayListOf<Element>()
    val attributes = hashMapOf<String, String>()


text:
Q: Regex Case Sensitivity Not working for Redux-Forms I'm trying to do a password validation in a React/Redux build using Redux-Forms. Everything is working great except I can't seem to get it to prevent passwords with at least one uppercase letter. Here is my regex:
^(?=[A-Z])(?=.*?[0-9])(?=.*?[^\w\s]).+$

It works fine in a regex validator and in my form validator, it works except for the uppercase letter.
const password = value =>
 value && !/^(?=[A-Z])(?=.*?[0-9])(?=.*?[^\w\s]).+$/i.test(value)
  ? 'Passwords must at least 8 characters, include one capital letter, one number, and one special character:'
  : undefined;

We are also using Wizard-Form but I don't see anything in there that would be messing with the case.
Does anyone have any ideas?

A: Your regex has a case insensitive match due to the /i flag at the end.
Simply remove the /i at the end of your regex to make this work:
> /^(?=[A-Z])(?=.*?[0-9])(?=.*?[^\w\s]).+$/i.test('hello1*')
true
> /^(?=[A-Z])(?=.*?[0-9])(?=.*?[^\w\s]).+$/.test('hello1*')
false

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is webcam freezing after certain time I coded an application that has a webcam which can SCAN QR codes:
VideoCaptureDevice LocalWebCam;
public FilterInfoCollection LoaclWebCamsCollection;

void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
    try
    {
        BitmapImage bi;
        using (var bitmap = (Bitmap)eventArgs.Frame.Clone())
        {
            bi = new BitmapImage();
            bi.BeginInit();
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Bmp);
            bi.StreamSource = ms;
            bi.CacheOption = BitmapCacheOption.OnLoad;
            bi.EndInit();
        }
        bi.Freeze();
        Dispatcher.BeginInvoke(new ThreadStart(delegate { frameHolder.Source = bi; }));
    }
    catch
    {
        //some error
    }

and
void Window2_Loaded(object sender, RoutedEventArgs e)
{
    LoaclWebCamsCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
    LocalWebCam = new VideoCaptureDevice(LoaclWebCamsCollection[0].MonikerString);
    LocalWebCam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
    LocalWebCam.Start();
    timer.Start(); // QR CODE SCANNER
}

It works all fine but when I let the application run for some longer time the webam freezes. Does someone have an idea why?


text:
Q: Referencing UIViewController in NSObject I am trying to access UIViewController's view in a NSObject class. The NSObject class is suppose to programmatically change UIViewController's user interface. I tried accessing NSViewController's view in NSObject by using self.view but was told that "request for member 'view' in something not a structure or union.
After a few inquiries, I was told that I need to reference viewController in my NSObject class. I am unsure of how to do this and would appreciate any help or point in the right direction. Thanks!

A: You should give the NSObject class a property called myController or something in its interface declaration, or pass a ViewController* to any methods that need to access it.
For the property, you can say:
ViewController* myController;

in the NSObject sub-class interface declaration, or for the method way, add an argument to your NSObject sub-class' method:
- (void) someMethodThatTakesAViewController: (ViewController*) theViewController {
    //Do your stuff here
    theViewController.view = [[UIView alloc] init]; // Or whatever you want to do
}

Hope this was what you were looking for.


text:
Q: How to create a buy application prompt on a certain amount of start-up times In my trial application I am implementing a notification which asks the user whether he/she would like to buy it. I would like this message to be displayed say every other time the application in started up.
I am logging the amount of times the application has been launched by increasing the length of a file named "launchCount" in IsolatedStorage like so:
using (StreamWriter writer = new StreamWriter(appStorage.OpenFile("launchCount", FileMode.OpenOrCreate, FileAccess.ReadWrite)))
{
    writer.BaseStream.SetLength(writer.BaseStream.Length + 1);
}

To determin the amount of times the app has been launched I just grab the length of the file in IsolatedStorage.
However how can I determine if this variable has a length of 2,4,6,8,10 etc...
I've tried dividing the retrieved length of the variable by 2, but don't know how to check if it is an integer (whole number).
Any Ideas anyone?
Thanks.

A: If this is true:
writer.BaseStream.Length % 2 == 0

Then you can display the message. Change 2 if you need and other interval.

A: Without beeing 100% sure but I think the following would be more efficient, clear and simple than working with a whole file:
private void CheckAppLaunchStatus()
{
    // Application settings
    readonly IsolatedStorageSettings _settings = IsolatedStorageSettings.ApplicationSettings;

    if (_settings.Contains("AppLunchTimes"))
    {
        value = (int) _settings["AppLunchTimes"];

        if (value % 2 == 0)
            Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show("Would you like to buy the application?", "Trial Version", MessageBoxButton.OKCancel));

        _settings["AppLunchTimes"] = value++;
    }
    else
        _settings.Add(key, 1);
}


text:
Q: jquery pageless ruby on rails : template missing I do in pageless scrolling using jquery pageless. my file are                                                                                In Game Controller
def result
  @game = GameResult.group("game_id").where(@where).order('registered_date desc')
  @results = @game.paginate(:per_page => 3, :page => params[:page])
  if request.xhr?
    sleep(3) # make request a little bit slower to see loader :-)
    render :partial => @results
  end
end

In application.html.erb
It has a div and yield file include in div tag.
In application Helper,
def pageless(total_pages, url=nil, container=nil)
  opts = {
      :totalPages => total_pages,
      :url        => url,
      :loaderMsg  => 'Loading more results',
     # :loaderImage => image_path("load.gif")
    }
  container && opts[:container] ||= container
  javascript_tag("$('#results').pageless(#{opts.to_json});")
end

In route
get '/games' =>'games#result'
get '/games/result' => 'games#result'
rake route in terminal
games GET    /games(.:format)    games#result

In View under games , I have two file - result.html file and _result.html file                       result.html.erb file
<%= render(:partial => 'result', :collection => @results) %>
<%= will_paginate(@results) %>
<%= pageless(@results.total_pages,games_path,"#results") %>

_result.html.erb file

<%= result.level %>

<%= result.game_timing %>

with this code I got the template missing error like this when i scrolling down . " Missing partial game_results/game_result with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip]" .... What wrong with this code.


text:
Q: Clean column in data frame I'm trying to clean one column which contains the ID number which is starting from S and 7 numbers, e.g.: 'S1234567' and save only this number into new column. I started with this column named Remarks, this is an example of the data inside:
         Remarks
0   S0252508 Shippment UK
1   S0255111 Shippment UK
2   S0256352 Shippment UK
3   S0259138 Shippment UK
4   S0260425 Shippment US

I've menaged to separate those rows which has the format S1234567 + text using the code below:
merged_out['Remarks'] = merged_out['Remarks'].replace("\t", "\r")
merged_out['Remarks'] = merged_out['Remarks'].replace("\n", "\r")
s = merged_out['Remarks'].str.split("\r").apply(pd.Series, 1).stack()
s.index = s.index.droplevel(-1)
s.name = 'Remarks'
del merged_out['Remarks']
merged_out = merged_out.join(s)
merged_out[['Number','Remarks']] = merged_out.Remarks.str.split(" ", 1, expand=True)

After creating a data frame I found that there are a lot of mistakes inside of that column because the data are written there manually, so there are some examples of those wrong records:
    Number
0. Pallets:
1. S0246734/S0246735/S0246736
3. delivery
4. S0258780 31  cok
5. S0246732-
6. 2
7. ok
8. nan

And this is only the wrong data which are in the Number column, I will need to clear this and save only those which has the correct number, if there is sth. like that: S0246732/S0246736/S0246738, then I need to have separated row for each number with the same data as it was for this record. For the other one I need to save those which contains the number, the other should have the null value.

A: Here is a regex approach that will do what I think your question asks:
import pandas as pd
merged_out = pd.DataFrame({
'Remarks':[
'S0252508 Shippment UK',
'S0255111 Shippment UK',
'S0256352 Shippment UK',
'S0259138/S0259139 Shippment UK',
'S12345678 Shippment UK',
'S0260425 Shippment US']
})

pat = r'(?:(\bS\d{7})/)*(\bS\d{7}\b)'
df = merged_out.Remarks.str.extractall(pat)
df = ( pd.concat([
    pd.DataFrame(df.unstack().apply(lambda row: row.dropna().tolist(), axis=1), columns=['Number']),
    merged_out],
    axis=1).explode('Number') )
df.Remarks = df.Remarks.str.replace(pat + r'\s*', '', regex=True)

Input:
                          Remarks
0           S0252508 Shippment UK
1           S0255111 Shippment UK
2           S0256352 Shippment UK
3  S0259138/S0259139 Shippment UK
4          S12345678 Shippment UK
5           S0260425 Shippment US

Output:
     Number                 Remarks
0  S0252508            Shippment UK
1  S0255111            Shippment UK
2  S0256352            Shippment UK
3  S0259138            Shippment UK
3  S0259139            Shippment UK
5  S0260425            Shippment US
4       NaN  S12345678 Shippment UK

Explanation:

*

*with Series.str.extractall(), use a pattern to obtain 0 or more occurrences of word boundary \b followed by S followed by 7 digits and a 1 occurrence of S followed by 7 digits (flanked by word boundaries \b)

*use unstack() to eliminate multiple index levels

*use apply() with dropna() and tolist() to create a new dataframe with a Number column containing a list of numbers for each row

*use explode() to add new rows for lists with more than one Number item

*with Series.str.replace(), filter out the number matches using the previous pattern, plus r'\s*' to match trailing whitespace characters, to obtain the residual Remarks
Notes:

*

*all rows in the sample input contain one valid Number except that one row contains multiple Number values separated by / delimiters, and another row contains no valid Number (it has S followed by 8 digits, more than the 7 that make a valid Number)

A: I think the easiest solution is to use regular expressions and a list comprehension:
import re
import pandas as pd
merged_out['Remarks'] = [re.split('\s', i)[0] for i in merged_out['Remarks']]

Explanation:
This regular expression allows you to split the data when there is a space and makes a list from the i row in the column Remarks. With the 0, I selected the 0 element in this list. In this case, it is the number.
In this case, the list comprehension iterates through all the column in the dataset. In consequence, you will obtain the corresponding number of each row in the new column Remarks.


text:
Q: Mixing Synchronous and A-sync code in Python I'm trying to convert a synchronous flow in Python code which is based on callbacks to an A-syncronious flow using asyncio.
Basically the code interacts a lot with TCP/UNIX sockets. It reads data from the sockets, manipulates it to make decisions and writes stuff back to the other side. This is going on over multiple sockets at once and data is shared between the contexts to make decisions sometimes.
EDIT :: The code currently is mostly based on registering a callback to a central entity for a specific socket, and having that entity run the callback when the relevant socket is readable (something like "call this function when that socket has data to be read"). Once the callback is called - a bunch of stuff happens, and eventually a new callback is registered for when new data is available. The central entity runs a select over all sockets registered to figure out which callbacks should be called.
I'm trying to do this without refactoring my entire code and making this as seamless as possible to the programmer - so I was trying to think about it like so - all code should run the same way as it does today - but whenever the current code does a socket.recv() to get new data - the process would yield execution to other tasks. When the read returns, it should go back to handling the data from the same point using the new data it got.
To do this, I wrote a new class called AsyncSocket - which interacts with the IO streams of asyncIO and placed the Async/await statements almost solely in there - thinking that I would implement the recv method in my class to make it look like a "regular IO socket" to the rest of my code.
So far - this is my understanding of what A-sync programming should allow.
Now to the problem :
My code awaits for clients to connect - when it does, each client's context is allowed to read and write from it's own connection.
I've simplified to flow to the following to clarify the problem:
class AsyncSocket():
    def __init__(self,reader,writer):
        self.reader = reader
        self.writer = writer
    def recv(self,numBytes):
        print("called recv!")
        data = self.read_mitigator(numBytes)
        return data
    async def read_mitigator(self,numBytes):
        print("Awaiting of AsyncSocket.reader.read")
        data = await self.reader.read(numBytes)
        print("Done Awaiting of AsyncSocket.reader.read data is %s " % data)
        return data

def mit2(aSock):
    return mit3(aSock)

def mit3(aSock):
    return aSock.recv(100)

async def echo_server(reader, writer):
    print ("New Connection!")
    aSock = AsyncSocket(reader,writer) # create a new A-sync socket class and pass it on the to regular code

    while True:
        data = await some_func(aSock) # this would eventually read from the socket
        print ("Data read is %s" % (data))
        if not data:
            break
        writer.write(data) # echo everything back

async def main(host, port):
    server = await asyncio.start_server(echo_server, host, port)
    await server.serve_forever()
asyncio.run(main('127.0.0.1', 5000))

mit2() and mit3() are synchronous functions that do stuff with the data on the way back before returning to the main client's loop - but here I'm just using them as empty functions.
The problem starts when I play with the implementation of some_func().
A pass through implementation (edit: kind-of-works) - but still has issues :
def some_func(aSock):
    try:
        return (mit2(aSock)) # works
    except:
        print("Error!!!!")

While an implementation which reads the data and does something with it - like adding a suffix before returning, throws an error:
def some_func(aSock):
    try:
        return (mit2(aSock) + "something") # doesn't work
    except:
        print("Error!!!!")

The error (as far as I understand it) means it's not really doing what it should:
New Connection!
called recv!
/Users/user/scripts/asyncServer.py:36: RuntimeWarning: coroutine 'AsyncSocket.read_mitigator' was never awaited
  return (mit2(aSock) + "something") # doesn't work
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Error!!!!
Data read is None

And the echo server obviously doesn't work.
Obviously my code looks more like option #2 with a lot more stuff in some_func(),mit2() and mit3() - but I can't get this to work. I'm fairly new in using asyncio/async/await - so what (rather basic concept I guess) am I missing?

A: This code won't work as envisioned:
def recv(self,numBytes):
    print("called recv!")
    data = self.read_mitigator(numBytes)
    return data

async def read_mitigator(self,numBytes):
    ...

You cannot call an async function from a sync function and get the result, you must await it, which ensures that you return to the event loop in case the data is not yet ready. This mismatch between async and sync code is sometimes referred to as the issue of function color.
Since your code is already using non-blocking sockets and an event loop, a good approach to porting it to asyncio might be to first switch to the asyncio event loop. You can use event loop methods like sock_recv to request data:
def start():
    loop = asyncio.get_event_loop()
    sock = make_socket()  # make sure it's non-blocking
    future_data = loop.sock_recv(sock, 1024)
    future_data.add_done_callback(continue_read)
    # return to the event loop - when some data is ready
    # continue_read will be invoked

def continue_read(future):
    data = future.result()
    print('got', data)
    # ... do something with data, e.g. process it
    # and call sock_sendall with the response

asyncio.get_event_loop().call_soon(start())
asyncio.get_event_loop().run_forever()

Once you have the program working in that mode, you can start moving to coroutines, which allow the code to look like sync code, but work in exactly the same way:
async def start():
    loop = asyncio.get_event_loop()
    sock = make_socket()  # make sure it's non-blocking
    data = await loop.sock_recv(sock, 1024)
    # data is available "immediately", meaning the coroutine gets
    # automatically suspended when awaiting data that is not yet
    # ready, and automatically re-scheduled when the data is ready
    print('got', data)

asyncio.run(start())

The next step can be eliminating make_socket and switching to asyncio streams.


text:
Q: Import pyaudio to ROS Node Hi I wrote a ROS Node in python which imports pyaudio for processing audio. I am using virtulenv with all python modules installed. I can run my Node in Pycharm however when i use rosrun mic_pkg mic_app.py. I'm getting following error
AttributeError: 'module' object has no attribute 'PyAudio'
Here is my node to run.
#!/usr/bin/env python
import pyaudio
import numpy as np
import struct
import rospy
from std_msgs.msg import Float64

class AudioInterface:

def __init__ (self):
    self.NSAMPLES = 92000
    self.CHUNK = 1024 * 4
    self.FORMAT = 8
    self.CHANNELS = 1
    self.RATE = 92000  # Hz or 152000, 192000 max
    self.RECORD_SECONDS = 3
    self.FRAMES = []

    self.interface = pyaudio.PyAudio ()
    self.stream = self.interface.open (format=self.FORMAT,
                                       channels=self.CHANNELS, rate=self.RATE, input=True,
                                       frames_per_buffer=self.CHUNK)

    self.stream.start_stream ()
    self.set_device_index ()

def __del__ (self):
    self.stream.stop_stream ()
    self.interface.terminate ()

def set_device_index (self):
    for i in range (self.interface.get_device_count ()):
        devinfo = self.interface.get_device_info_by_index (i)
        print ('Device %{}: %{}'.format (i, devinfo['name']))

        for keyword in ['mic', 'input']:
            if keyword in devinfo['name'].lower ():
                print ('Found an input: device {} - {}'.format (i, devinfo['name']))
                self.device_index = i

def get_chunks (self):
    for i in range (0, int (self.RATE / self.CHUNK * self.RECORD_SECONDS)):
        data = np.frombuffer (self.stream.read (self.CHUNK), dtype=np.int16)
        data = data / 1000
        self.FRAMES.append (data)
    return self.FRAMES

def get_audio_block (self):
    data = np.frombuffer (self.stream.read (self.RATE), dtype=np.int16)
    data = data / 1000
    return data

class AudioProcessing:
@staticmethod
def calc_fft (array):
    fftdata = np.abs (np.fft.rfft (array))
    return fftdata

@staticmethod
def calc_rms (array):
    rms = np.sqrt (np.mean (array ** 2))
    return rms

@staticmethod
def calc_mean (array):
    result = np.mean (array)
    return result

@staticmethod
def normalize (array):
    buff = []
    min_value = min (array)
    max_value = max (array)
    for x in array:
        y = (x - min_value) / (max_value - min_value)
        buff.append (y)

    return buff

@staticmethod
def zeros (array):
    for n in range (0, 38000):
        array[n] = 0

    for k in range (42000, len (array)):
        array[k] = 0

    return array

LEAK_TRIGGER = 0.25
is_leaking = False
trigger = False

if __name__ == "__main__":
mic = AudioInterface ()
is_leaking = False

rospy.init_node ('microphone_node', anonymous=False)
pub = rospy.Publisher ('mic_data', Float64, queue_size=10)
rate = rospy.Rate (10)
while not rospy.is_shutdown ():
    audio = mic.get_audio_block ()
    audio_freq = AudioProcessing.calc_fft (audio)
    audio_normalized = AudioProcessing.normalize (audio)
    fft_normalized = AudioProcessing.normalize (audio_freq)
    fft_normalized = AudioProcessing.zeros (fft_normalized)
    max_val = max (fft_normalized)

    hello_str = "hello world %s" % rospy.get_time ()
    pub.publish (max_val)
    rospy.loginfo (max_val)
    rate.sleep ()

I can't tell whether this is not finding package issue or maybe some problem with pyaudio module itself. How do I import python modules (like pyaudio) to ROS Node  Please help. Thanks!
Edit i do catkin_make each time i make some changes to the code and it passes with no errors.


text:
Q: Is there a way for animating letters inside a TextView? Is there a way for animating letters inside a TextView?
For example I have the TextView below
<TextView
        android:id="@+id/txtLogo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/SSA0Logo"
        android:textColor="@color/SSA0LogoText"
        android:textSize="50sp"/>

This TextView Has this String "Hi" , Can I set animation for letters for example:
H (alpha animation show startOffset 500ms)
i (alpha animation show startOffset 1s)


text:
Q: R - glm() formula exclude variable with conditions R newbie here.
Suppose that I want to exclude categorical variable with the factor level of 4 and 5. How can I do it in glm() only using formula?
Examples:
setNames(levels(factor(df$category)), seq_along(levels(factor(df$category))))
#     1         2         3         4          5
# hardline  softline  foodline  softgoods  hardgoods

# Convert to categorical codes
df$category <- factor(as.numeric(factor(df$category)))

# Remove category with the factor level of 4 and 5
glm(resolution_time ~ division + category, data = df)

My objective here is to calculate the vif.

A: If you want to remove factor levels based on the number you can do :
df$category <- factor(df$category)

glm(resolution_time ~ division + category, data = df,
    subset = !category %in% levels(category)[4:5])


text:
Q: Sistema de login com PHP Olá, preciso fazer uma área administrativa, e obviamente preciso de um sistema de login e senha. Sei que já existem aqui, perguntas sobre este assunto, mas temo que elas estejam desatualizadas. Quero um jeito dentro do possível simples e seguro. Também não quero que ninguém faça nada pra mim, até por que estou aprendendo e óbviamente quero dominar isso, quero apenas que me dêem dicas de como fazer, links de referência e etc. Obrigado desde já.
O que eu tenho até agora:
<form action="submit" method="POST">

LOGIN:

    <input type="text" name="login">

SENHA:

    <input type="password" name="password">
    <button type="submit">ENTRAR</button>
</form>

A: Algo que eu vejo muito nos tutoriais que encontro na internet é que eles separam a configuração da apresentação, mas não usam mvc como a gente vê na maior parte dos sites que o pessoal cria hoje em dia, eles simplesmente separam esses ficheiros através de diretórios, aí você pode programar sem usar oop e deixar o site simples.
\- root
 + - configuracao
    - includes
    - conexão
 + site
    - css
    - imagens
    - javascript
    - index.php
    - login.php
    + administração
      - css
      - imagens
      - javascript
      - index.php
      - login.php
      - apagar.php
      - cadastrar.php

Você poderia optar por uma estrutura semelhante e deixar sua aplicação simples e segura. Separando o login de administrador dos logins de usuários normais, e separando também as tabelas de usuários com a dos administradores no banco de dados.
Você  deve restringir os privilégios para os usuários dessas tabelas, sanitizar os dados antes de serem gravados no banco de dados, e também os dados que os usuários e administradores digitam para fazer o login no sistema ou alterar dados no banco de dados.
Você pode usar essas funções de hash pra criptografar as senhas antes de gravar no banco de dados.
Se você quiser mais dicas, existem também esses posts aqui:
Como fazer hash de senhas de forma segura?
Qual a melhor maneira de criar um sistema de login com PHP
Lembrar usuário com segurança

A: Esqueça SHA1 e MD5
Antes de começar, é bom deixar claro. Não use nenhum desses métodos de criptografia. Você vai entender o porque no decorrer desta resposta.
Informações importantes
Recomendo que leia esta resposta, depois leia esse artigo do Thiago Belem, depois esse artigo da própria documentação do PHP.
Os links acima irão mostrar porque você não deve utilizar sha1 ou MD5.
No caso do segundo link que passei, não só leia, mas execute o que foi ensinado e execute novamente até que você saiba o que está sendo feito. Depois disso, recomendo que também o processo utilizando as instruções do terceiro link, o password_hash
Não vou reinventar a roda aqui, até porque o primeiro link já tem tudo que você precisa saber e os demais são os exercícios de criptografia.
Vou lhe dar um exemplo de solução para o seu caso, simples e comentado para que você entenda. No exemplo irei utilizar o password_hash, que é o método mais seguro atualmente.
Exemplo de uso
No HTML
<form action="" method="post">
    Login
    <input type="text" name="login" id="login">
    Senha
    <input type="password" name="password" id="password">
    <button type="submit">Fazer login</button>
    <input type="hidden" name="hidden" <?php echo "value='" . $_SESSION['formKey'] . "'" ?>>
</form>

No action não precisa colocar nada, já que vamos usar a mesma página do formulário para validar os dados.
Se você leu o primeiro link que te passei, deve saber que o campo input do tipo hidden serve para dificultar ataques do tipo CSRF (Cross-site Request Forgery), onde o formulário só será validado se o valor do hidden for igual ao valor da $_SESSION['formKey']. Lembrando que essa $_SESSION deverá ser alterada a cada vez que a página for atualizada, depois de passar pela validação do método $_POST, claro. No código PHP você vai entender.
Recomendo que leia esse artigo sobre ataques CSRF.
A questão dos labels, é apenas um aspecto de UX design, onde você permite que o usuário clique no label, e o foco seja direcionado ao input.
No PHP
<?php

    //Possibilita que trabalhemos com sessões, vai ser útil para validar o campo
    //hidden, e também para manter o usuário logado no sistema.
    //mas isso é outro ponto e não vou abordá-lo aqui.
    session_start();

    //Dados do banco
    $hostname = 'localhost';
    $username = 'root';
    $password = '123456';
    $database = 'meusite';

    //Se conecta ao banco de dados
    $mysql = mysqli_connect($hostname, $username, $password, $database);
    mysqli_set_charset($mysql, 'utf8');

    //Se o usuário clicar em submit, ele faz uma requisição POST e aciona
    //essa condição
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        //Verifica se o valor do campo hidden bate com o valor da session.
        if (isset($_POST['hidden']) && $_POST['hidden'] == $_SESSION['formKey']) {

            //Verifica se existe um POST chamado login e senha respectivamente e,
            //se existir, remove os espaços no começo e final da string usando a função
            //trim() e atribui o valor deles as respectivas variáveis.
            //Se não existir, define o valor da variável como null.

            //Se não entendeu como funciona, pesquise sobre OPERADOR TERNÁRIO e função TRIM
            $login      = (isset($_POST['login'])) ? trim($_POST['login']) : null;
            $password   = (isset($_POST['password'])) ? trim($_POST['password']) : null;

            if (empty($login)) {
                //Se a variável $login estiver vazia, faça:
                echo 'Por favor, preencha o campo de login';
                exit;
            }
            if (empty($password)) {
                //Se a variável $password estiver vazia, faça:
                echo 'Por favor, preencha o campo de senha';
                exit;
            }

            //Antes de comparar qualquer dado com o banco, fazemos escape para dificultar
            //SQL injections.
            $login      = mysqli_real_escape_string($mysql, $login);
            $password   = mysqli_real_escape_string($mysql, $password);

            //Seleciona os campos login e password na tabela usuarios, cujo login seja
            //igual ao login informado no formulário.
            //Lembre-se de marcar a coluna login no banco de dados como UNIQUE ID
            //para que não seja possível existir mais de um login igual.
            $result = mysqli_query($mysql,
            "SELECT `login`, `password` FROM `usuarios` WHERE `login` = '" . $login . "'");

            if(!mysqli_num_rows($result)) {
                echo "Usuário não encontrado";
                exit;
            } else {
                //Coloca os dados retornados pelo banco em um array chamado $data
                while ($r = mysqli_fetch_assoc($result)) {
                    $data[] = $r;
                }
            }

            //Chegando neste ponto, entede-se que o login informado existe, agora temos que
            //validar a senha.

            //Vamos supor que você usou password_hash para criptografar a senha no
            //momento do cadastro do usuário.

            if (password_verify($password, $data[0]['password'])) {
                echo "Logado com sucesso!";
            } else {
                echo "Senha incorreta!";
                exit;
            }

            //Fazendo isso, estamos dizendo pro PHP verificar se a senha informada
            //corresponde ao hash (senha criptografada) que estava no banco.
        }
    }

    //Toda vez que ele atualizar a página, o value do campo hidden será alterado
    //Abaixo fizemos o sha1 de um número randomico usando a função rand().
    $_SESSION['formKey'] = sha1(rand());

    //Eu usei sha1, porque? Simples. O valor do campo hidden não tem importancia
    //pra gente. Ele não precisa ser seguro, até porque ele será visível caso
    //o usuário clique em visualiar o código fonte, ele só precisa mudar e ser
    //impossível de se acertar num "chute".
?>

A receita do bolo está aí, basta usá-la.

A: Dê uma olhada nesse blog:
login - OO.
Um exemplo orientado a objeto usando PHP.
Para senha use SHA1: Senhas

A: Recomendo dar uma estudada também em MD5 (ou SHA1 como nossa amiga @Bia mencionou).
Também olhe sobre Validação de Login por Sessions.
E, se quiseres, dê uma olhada em SQL Inject para aprender um pouco mais das falhas de segurança que AINDA existem em muitos sites.
Bons estudos!
PS: já existe um tópico similar: Melhor jeito de fazer um sistema de login e senha com PHP

A: Resumidamente:
Como você está começando agora, o primeiro passo que posso sugerir para estudar, antes de fazer um sistema de login e senha, é seguir a normalização das PSRs, afinal, não queremos mais códigos mal feitos por aí.
O segundo passo é, sempre que possível, consultar a Documentação Oficial do PHP.
Este site tem bastante informação para quem precisa aprender a desenvolver com PHP.
Para fazer um sistema de login, você vai precisar basicamente de:

*

*Conexão com banco de dados

*Configuração de sessão

*Criar usuário, senha e um hash
Para as páginas que você tiver restrição de acesso, você deverá criar níveis de acesso para os usuários, uma maneira de fazer isso é dando peso ao usuário, no exemplo abaixo, irei dar 3 pesos, 0 - bloqueado, 1 - editor, 2 - administrador.
Tabela usuário:
CREATE TABLE `User` (
  `id_user` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(45) NOT NULL,
  `password` varchar(255) NOT NULL,
  `createdAt` TIMESTAMP NOT NULL DEFAULT current_timestamp,
  `salt` varchar(255) NOT NULL,
  PRIMARY KEY (`id_user`),
  KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='Dados do Usuário';

Tabela do perfil do usuário:
  CREATE TABLE `Roles` (
  `id_role` int(11) NOT NULL AUTO_INCREMENT,
  `fk_user` int(11) NOT NULL,
  `level` int(9) NOT NULL DEFAULT '0',
  `name` varchar(45) NOT NULL,
  PRIMARY KEY (`id_role`),
  KEY `fk_Roles_1_idx` (`fk_user`),
  CONSTRAINT `fk_Roles_1` FOREIGN KEY (`fk_user`) REFERENCES `User` (`id_user`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Níveis de acesso do Usuário';

Agora, para verificar os níveis de acesso, você faria uma consulta desse tipo, pegando todos os usuários que não estão bloqueados (0):
function createPassword($pass)
{
 //salve isso no User.password
  return password_hash($pass, PASSWORD_DEFAULT);
}

function checkLogin($user, $pass, $dbh)
{

$sth = $dbh->prepare("SELECT Users.password as pass_hash AND Users.username :=user");
$sth->bindParam(':user', $user, PDO::PARAM_STR);
$sth->execute();
$resultHash = $sth->fetch(PDO::FETCH_OBJ);
if (validPassword($pass, $resultHash->pass_hash)) {

   $sth = $dbh->prepare("SELECT  Users.id_user as 'ID',
                                 Users.username,
                                 Roles.name,
                                 Roles.level
                         FROM    Users
                         INNER JOIN Roles ON
                                 (User.id_user=Roles.fk_user
                                  AND  Roles.level != 0)
                         WHERE   Users.username :=user
                      ");
   $sth->bindParam(':user', $user, PDO::PARAM_STR);
   $sth->execute();
   $result = $sth->fetch(PDO::FETCH_OBJ);
   createSession($result);
 }
}

function validPassword($pass, $hash)
{
  return password_verify($pass, $hash);
}

Então basicamente, você irá verificar o login. E assim que confirmar, você cria a sessão:
function createSession($dados)
{
    session_start();
    $_SESSION['level_user'] = $dados['level'];
    $_SESSION['ip_user'] = $_SERVER['REMOTE_ADDR'];
    $_SESSION['tipo_user'] = $dados['name'];
    $_SESSION['username'] = $dados['username'];
}

E depois verifica se o usuário está logado e o nível dele:
 function checkSession($nivel)
 {
    session_start();
    if ($_SESSION['level_user'] == $nivel && $_SESSION['ip_user'] == $_SERVER['REMOTE_DDR'] &&  isset($_SESSION['username'])) {
           //permitido
    } else {
          //não permitido
    }
 }


text:
Q: Animated Fractal Screen Saver Recently i got intrigued by the math of Fractals and now I am looking for a good quality (mandelbrot) fractal sceensaver. I thought that would be easy, but alas: looked around at the web, but could not find a decent one.
Hoping that one of the superusers can help me out.

A: Fractals Screensaver ? Works fine of Windows 7 64-bit.


text:
Q: What are good ways to architect a custom "ClaimsAuthorizationManager" Windows Identity Foundation class? I am working on the very first project at my office where we will be using "Windows Identity Foundation" with Claims-Based-Authorization.  To this end, Microsoft .net provides the ClaimsAuthorizationManager abstract class.  In order to use this class, you override two methods: the constructor and CheckAccess(context as ClaimsAuthorizationContext).
The constructor sets everything up; then when the user accesses something, such as a web page, CheckAccess gets called with a parameter which indicates the user, the resource to be accessed, and the action to be taken on the resource.  For example, CheckAccess could be called to see if the user Bob should be given access to the resource http://www.mysite.com/SecretPage.aspx to perform action GET.  CheckAccess simply returns true or false.  Windows Identity Foundation gives us the flexibility to implement CheckAccess almost any way imaginable!
In the code samples that Microsoft provides, CheckAccess is configured to allow access to a user only if he has a birthday claim that indicates age 21 or older.  This policy is given in plain-text in the web.config and read in the ClaimsAuthorizationManager constructor.
In my office, we use SQL to keep track of almost all of our data, so in my case. I believe that it makes sense to program the ClaimsAuthorizationManager to read data from SQL to determine if a user may or may not access a resource.  However, there is a myriad of different possible policies.  I want to create a ClaimsAuthorizationManager that will be useful in the current project and that I can build upon and improve in the future without having to rip and replace the project I create today.
What are the most important things to bear in mind as I proceed with this project?
UPDATE: I have been working on a system of representing required-claim policies as strings.  I use binary-tree logic to group together policies.  I maintain a database of claims associated with "resources" and "actions".
Has anyone else here built a ClaimsAuthorizationManager class?

A: I think it is encouraging that you are looking forward trying not to write dead code BUT I think you are getting ahead of yourself.
You need to produce one or more spikes that ARE treated as throw-away to determine for yourself what makes sense for your particular scenario.
That said, if all of your rules are in the db, create a sproc base CAM that reads the sproc name from the config file. The CheckAccess args are not going to change so the sproc signature can be immutable allowing you to switch them out as needed.


text:
Q: Activemq STOMP: detecting and clearing dead nondurable subscribers I have the following situation that is affecting our ActiveMQ 5.8 broker.
Several Perl scripts on a Windows workstation connected to ActiveMQ using STOMP and subscribed (nondurable) to various topics. The power failed on the Workstation.
Using the Web console, I can see that ActiveMQ still thinks these subscribers are connected, based on the number of consumers shown and on the high temp message store being used. I had set for no producer flow control and set memory limits, so what I believe I am seeing is that ActiveMQ is spooling all messages to disk because it thinks the long dead subscribers are still connected and might eventually read them. It's been 30 days, and ActiveMQ still doesn't realize that these subscribers are no longer connected.
It there a way to configure ActiveMQ so that "undead" subscriber connections like these are eventually cleared automatically?

A: Though Stomp 1.1+ supports Heartbeating, Active MQ currently doesnt support inactive consumer detection for Stomp. (usually achieved with wireFormat.maxInactivityDuration).
Be Careful:
These values are currently not supported but are planned for a later release

ActiveMQ supports it for Openwire though. i,e after the configured duration the consumer would be considered DEAD !

A: While the previous answer is basically correct, ActiveMQ does provide solutions for STOMP transports on the Broker to heart-beat connections, even if the client connects with STOMP v1.0.  I blogged about this some time ago when ActiveMQ v5.6 was released, see the section on STOMP 1.0 default heartbeat configuration.  Another option is to set tcp keepAlive on for the transport and tune your OS to use a shorter default check interval, the default is usually around two hours.


text:
Q: Photoelectric effect stopping potential $q_eV_s = hf - \phi$
My question is... suppose we are testing the photoelectric effect. One plate is illuminated. We have applied the stopping potential. Suppose an electron leaves one plate with $KE = hf - \phi$ Now by the time it reaches the other plate, it should have 0 kinetic energy right?
My question is about current... current should be 0 in this case, but charge has traveled from one plate to the other... so I'm confused as to how current can be 0.
Also, I'm having trouble thinking about the electron barely reaching the other side... vs being pulled back to the first plate before it can... are these situations somehow equivalent current wise?
Appreciate any clarification.

A: You are right - the electron might make it all the way to the other plate. But then it will have zero velocity, and it still feels the electric field. So it will "fall back" to the plate it came from - and the net current is zero.
In reality the velocity distribution of the electrons is continuous (they don't all travel directly to the other plate with the maximum possible velocity) so you will see a drop in current as you increase the retarding potential.

A: Some notes:

*

*this Kinetic Energy that you use is the Maximum amount of kinetic energy among the electrons. it means maybe just a few of them has this amount of energy, other photo electrons with lower kinetic energies (therefor lower Velocity) just accelerate back to the plate that they been shot from.

*the Kinetic energy actually gets to Zero at the next plate. it means the $V=0$ therefor the electron can not enter the circuit. so even the Highest energy photo electron couldn't reach the other plate to enter the circuit and create a current therefor $I=0$ and that voltage is called stoppage Voltage.


text:
Q: How do you prevent names from colliding in C Let's say I have a two files : stack.h and queue.h. Both want to implement the function add(). If I include stack.h and queue.h in the same main.c for example, there will be a collision.
What is the recommended way to implement the add() function in both files?

A: If this is pure C, the simplest common solution is to use do-it-yourself namespacing on the functions relative to the name of the module or data structure that they apply to. e.g.
stack_add(...)
queue_add(...)

You will find examples of this in pretty much all large pure-C projects:
pthread_mutex_lock() // POSIX/UNIX, used for locking a mutex
CGRectMake()         // iOS, used to fill in a CGRect structure
RtlZeroMemory()      // WinNT, "Rtl" indicates the module it belongs to

Your question was about "exported" (public) function names, but note too that when your .c files have private helper functions, you can mark them static which tells the compiler that they are used only from within that file, so your naming can be a little looser for them knowing they won't collide elsewhere.

A: If you already have a queue and a stack implementation tested, and referred to elsewhere.. you can do some preprocessor tricks like this:
#define _STACK
#define _QUEUE

#ifdef _QUEUE
#define add queue_add
  #include "queue.h"
#undef add
#endif

#ifdef _STACK
#define add stack_add
  #include "stack.h"
#undef add
#endif

int main()
{
   stack_add();
   queue_add();
}

My advice is - refactor the code base to use non-clashing naming convention instead of generic function names like add and subtract and the rest.
If you are a fan of object oriented programming style and like the whole "add", "modify" concept then use function pointers inside the queue and stack structure.
#define TYPE int

typedef struct tagStruct{
   TYPE *dataBuffer;
   void (*add)(TYPE data);
   void (*modify)(TYPE data, int index);
   void (*deleteEverything)()
}stack;

and in the init(stack) method, assign add(), modify() and deleteEverything() to different functions that have no name-collision(likewise for queue)
Then you begin to see stack and queue as ENTITIES rather than bunch-of-functions.
You can then do this:
stack stc;
init(stc); /*sets up the function pointers*/
stc.add(10);
stc.modify(30,0);
stc.deleteEverything();


text:
Q: Can't see the code flowing while using chrome://inspect/#devices? I am working on an app,which I have installed in my Smartphone, I wanted to check the flow of code while running the app.
using Android Studio I installed the app via USB Debugger, and open the app project files in

chrome://inspect/#devices

, while running , I have added multiple breakpoints in the code to see the flow, but the code haven't stopped at any breakpoint, yet there is no issue with the running of app, the app ran smoothly.
I am facing the same issue while using emulator as well.
Can someone help me to figure out, what I could do ?
EDIT -
I have followed @KannanSJD instructions as well, by "Attaching Debugger to Android" and selecting "Java Only" but not got any success. , As you can see in the below attachments

A: make sure you attach your debugger to your app process. Use the below icon on top left

if your app package and its process is not showing then make sure you are running in Debug mode and not in release mode using build variants.

Make sure your app is open and you see your process as in screenshot.

Also instead of detect automatically you cna use Java only if you have NDK also used in your project. This will fasten the process of attaching debugger.
Also make sure you find the following log in your debug console.

Please check if you have muted your breakpoints, refer following image. That should NOT be enabled.


text:
Q: Linux + how to know which CPU Cores was active last day recently , we upgrade our redhat server ( version 7 ) from 4 CPU CORE to 32 CPU CORE
is it possible to know which CPU was triggered during last day ?
I mean how to know if the additional CPU that we add are now in process ?

A: top command would be helpful. Use top command to list the utilization of each core.  Press 1 if necessary to split the CPU row into a separate row for each core.
You can also add a column that shows the last-used core for each process.  Press f to bring up the field list, then select column P and press d or <space> to toggle the value. Now, press q or <Esc> to end and see live. In right side you will see a column P which shows cpu core no. used by corresponding processor.


text:
Q: Multiple drop down boxes? I'm trying to get multiple drop down boxes to open when selecting different prompts from an original drop down menu.
So for example the original drop box would say "Continent" then drop down to a list of continents, when you select a continent a new box opens that asks you "Country" then you select a country and a new drop box opens to select a state.
I've been using this template

      <select name="color" onchange='CheckDepartment(this.value);'>
        <option>pick a color</option>
        <option value="red">RED</option>
        <option value="blue">BLUE</option>
        <option value="others">others</option>
      </select>
    <select name="othercolor" id="othercolor" onchange='CheckOption(this.value)' style='display:none;'/>
    <option value=""></option>
    <option value="hi">hi</option>
    <option value="misc" id="misc" >misc</option>
</select>
    <select name="third" style='display:none;'>
        <option value=""></option>
        <option value="first">first</option>
        <option value="second">second</option>

    </select>

but I can't get a third drop box to open when selecting an option from the second drop box.
edit: third box. I think i deleted my last try so this was kinda a recreation of it from what I remembered. I'm also incredibly new at all of this and don't know if anything I tried makes sense.

A: Here's a simplified demo.
(It assumes only a "yes" value should trigger the display of the next dependent dropdown.)

const
  select1 = document.getElementById("select1"),
  select2 = document.getElementById("select2");

document.addEventListener("change", handleDropdownDisplay);

function handleDropdownDisplay(event) {
  let changedElement = event.target;
  if ((changedElement != select1) && (changedElement != select2)) {
    return;
  }
  if (changedElement.value == "yes") {
    changedElement.parentElement.nextElementSibling.classList.remove("hidden");
  } else {
    changedElement.parentElement.nextElementSibling.classList.add("hidden");
  }
}
div {
  margin-bottom: 0.5em;
}

.hidden {
  display: none;
}

  Show level 2?
  <select id="select1">
    <option value="no">No</option>
    <option value="yes">Yes</option>
  </select>

  Show level 3?
  <select id="select2">
    <option value="no">No</option>
    <option value="yes">Yes</option>
  </select>

  Would your rather
  <select id="select3">
    <option value="brains">Eat monkey brains</option>
    <option value="vba">Write code in VBA</option>
  </select>

(Btw, level 3 doesn't automatically become hidden whenever level 2 becomes hidden. This is probably functionality you'll want to add.)


text:
Q: Linux - run android emulator on Nouveau driver Linux (Debian Sid x64), kernel 4.14, Nvidia GPU. I am unable to run Android emulator on open Nouveau drivers. There is no any error message that I can post, jus segmentation fault. When I choose software rendering, it works but unusable (it runs very slow).
Does anybody know any workaround for that, or I am forced to use official Nvidia drivers?


text:
Q: ASP.NET Masterpages and viewstate I am looking to improve the performance of my site, not because it is performing badly but just as a general exercise. The usual suggestion for asp.net sites is to remove viewstate wherever possible. I believe this can be done by each control on a page separately or for the whole page.
My question is if I disable the page viewstate will this stop the viewstate of controls on a masterpage (as I understand it the masterpage is actually a control on the page).

A: There's an easy way to shrink all your viewstate.
Step 1. Create a new class that looks like this:
Imports System
Imports System.Web.UI

Public Class SessionPageStateAdapter
    Inherits System.Web.UI.Adapters.PageAdapter

    Public Overrides Function GetStatePersister() As System.Web.UI.PageStatePersister

        Return New SessionPageStatePersister(Page)

    End Function
End Class

Step 2. Add an App_Browsers folder to your project.
Step 3. In your new App_Browsers folder, add a new default.browser file that looks like this.
<browsers>
    <browser refID="Default">
    <controlAdapters>
    <adapter controlType="System.Web.UI.Page"     adapterType="[YourNamespaceGoesHere].SessionPageStateAdapter" />
    </controlAdapters>
    </browser>
    </browsers>

When you run your pages now, you should find your viewstate size has dropped to a few bytes. The SessionPageStateAdapter class intercepts viewstate before it gets served to the browser and holds it in on the server in Session state. The bit of viewstate that still gets sent to the client is just an identifier that is used to reconstitute the original viewstate when the page gets posted back to the server.

A: Yes, the page is the originator of the page flow. Thus, disabling viewstate for the page takes the viewstate rendering out of the OnInit process. A better question would be why does disabling the viewstate for the master page do the same?

A: Just a quick note on the side before optimising the site, have you optimised the server by making sure all the files are gzipped before being sent.
If not this will get you a nice boost before you even start tinkering with the page.
http://www.codinghorror.com/blog/archives/000059.html


text:
Q: How to set interval after clearing it I can set interval and clear it on click. I want to setInterval again but don't know how to do. What I want is when someone clicks on an icon then setInterval should be clear (best if it waits for few seconds) and then start again. Here is my code
jQuery(document).ready(function() {

    var timer =  setInterval(function(){
    var finding = jQuery('ul.hi-icon-wrap').find( "li.active" );
    var tabcontentActive = jQuery('div.tab-content').find( "div.active" );
    var last = jQuery('ul.hi-icon-wrap li').last();
    var nextItem =  jQuery(finding).next();
    var tabid = jQuery(nextItem).find('a').attr('id');
    if(finding.is(last)) {
     var tabid = jQuery('ul.hi-icon-wrap li:first').find('a').attr('id');
    }
    //alert(tabid);
     jQuery(finding).removeClass('active');
     jQuery(finding).next().addClass('active');
     if(finding.is(last)) {
        jQuery('ul.hi-icon-wrap li:first').addClass('active');
    }
    jQuery(tabcontentActive).removeClass('active');
    jQuery('div.tab-content').find('div#'+tabid).addClass('active');
    }, 3000);
     $("ul.hi-icon-wrap li").click(function () {
          //alert('ok');
          clearInterval(timer); //clear interval
        timer = setInterval(timer, 300); //I am unable to restart here.
      });

});

A: setInterval/setTimeout returns just number indicating process reference, not actual function called. Call same function again.
var fooFunction = function(){
    var finding = jQuery('ul.hi-icon-wrap').find( "li.active" );
    var tabcontentActive = jQuery('div.tab-content').find( "div.active" );
    ...
}

jQuery(document).ready(function() {
     var timer =  setInterval(fooFunction, 3000);

     $("ul.hi-icon-wrap li").click(function () {
        clearInterval(timer); //clear interval
        timer = setInterval(fooFunction, 300); //I am unable to restart here.
     });
});

A: What you can do it put this piece of code in your function as you see below. You are calling clearInterval which clears things out ,if you want to restart it again you must set new interval.

The clearInterval() method of the WindowOrWorkerGlobalScope mixin
  cancels a timed, repeating action which was previously established by
  a call to setInterval().

function interval(){
    var finding = jQuery('ul.hi-icon-wrap').find( "li.active" );
    var tabcontentActive = jQuery('div.tab-content').find( "div.active" );
    var last = jQuery('ul.hi-icon-wrap li').last();
    var nextItem =  jQuery(finding).next();
    var tabid = jQuery(nextItem).find('a').attr('id');
    if(finding.is(last)) {
    var tabid = jQuery('ul.hi-icon-wrap li:first').find('a').attr('id');
}
    jQuery(finding).removeClass('active');
    jQuery(finding).next().addClass('active');
    if(finding.is(last)) {
        jQuery('ul.hi-icon-wrap li:first').addClass('active');
    }
    jQuery(tabcontentActive).removeClass('active');
    jQuery('div.tab-content').find('div#'+tabid).addClass('active');
}

and then
jQuery(document).ready(function() {
    var timer = setInterval(interval,3000);
    // do nothing
    $("ul.hi-icon-wrap li").click(function () {
        clearInterval(timer); //clear interval
        timer = setInterval(interval, 300);
      });
}

A: Add setInterval logic in different function and call that function when button is clicked.

jQuery(document).ready(function() {

    var timer;
    startInterval();

    function startInterval(){
    timer =  setInterval(function(){
    var finding = jQuery('ul.hi-icon-wrap').find( "li.active" );
    var tabcontentActive = jQuery('div.tab-content').find( "div.active" );
    var last = jQuery('ul.hi-icon-wrap li').last();
    var nextItem =  jQuery(finding).next();
    var tabid = jQuery(nextItem).find('a').attr('id');
    if(finding.is(last)) {
     var tabid = jQuery('ul.hi-icon-wrap li:first').find('a').attr('id');
    }
    //alert(tabid);
     jQuery(finding).removeClass('active');
     jQuery(finding).next().addClass('active');
     if(finding.is(last)) {
        jQuery('ul.hi-icon-wrap li:first').addClass('active');
    }
    jQuery(tabcontentActive).removeClass('active');
    jQuery('div.tab-content').find('div#'+tabid).addClass('active');
    }, 3000);
  }

  $("ul.hi-icon-wrap li").click(function () {
          //alert('ok');
          clearInterval(timer); //clear interval
        startInterval(); //I am unable to restart here.
    });

});


text:
Q: Tensorboard profiling a predict call using Cloud TPU Node I've been trying to profile a predict call of a custom NN model using a Cloud TPU v2-8 Node.
It is important to say that my prediction call takes about 2 minutes to finish and I do it using data divided in TFRecord batches.
I followed the official documentation "Profile your model with Cloud TPU Tools" and I tryied to capture a profile:

*

*Using Tensorboard UI and

*The "programatic way" with a tf.profiler.experimental.start() and tf.profilier.experimental.stop() wrapping the predict call, but I had no success in both cases.

# TPU Node connection is done before...

# TPU at this point is already running
logdir_path = "logs/predict"
tf.profiler.experimental.start(logdir_path)
# Tensorflow predict call here
tf.profiler.experimental.stop()

I could generate some data in both cases (Tensorboard UI and profiler call), but when I try to open it in Tensorboard pointing the logdir path, I received a "No dashboard are active for the current data set" message.
Is there any way to profile a Tensorflow/Keras prediction call with a model running in a Cloud TPU Node?

Curious fact - There seems to be an inconsistency in the Tensorflow docs and Cloud TPU docs: in Tensorflow Optimization Docs we can see that tf.profiler.experimental.start/stop calls are not supported by TPU hardware, but in Google Cloud docs this is the recommended method to capture a profile in TPU.
Config:

*

*Tensorflow 2.6.1

*Tensorboard 2.9.1

*Python 3.8

*Cloud TPU Node v2-8

A: *

*Please check the trace files in your logdir. If they are too small, it's likely that you got some issues during tracing.

*Just be sure that you typed the right command. $ tensorboard --logdir logs/predict

*Try another profiling method by using tf.profiler.experimental.client.start(...), as indicated by TF profiler Docs.
Below is the code snippet.

import tensorflow as tf
from threading import Thread

def call_trace(tpu_resolver):  # This should be called asynchronously
  # a profiler service has been started in the TPU worker at port 8466
  service_addr = ":".join(tpu_resolver.get_master().split(":")[:-1] +
                          ["8466"])  # need to change for TPU pod
  tf.profiler.experimental.client.trace(service_addr=service_addr,
                                        logdir="gs://your_logdir",
                                        duration_ms=5000)

tpu_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(...)
# Other initialization codes

thr = Thread(target=call_trace, args=(tpu_resolver,))
thr.start()
# Codes you want to execute on the cloud TPU node
thr.join()

Then open tensorboard for visualization.
$ tensorboard --logdir gs://your_logdir

A: For TPU Node architecture you can also try using cloud-tpu-profiler:
pip3 install --upgrade "cloud-tpu-profiler>=2.3.0"

Then capture the profile using
capture_tpu_profile --tpu=$TPU_NAME --logdir=${MODEL_DIR} --duration_ms=2000 --num_tracing_attempts=10

For details you can refer here.
TPU VM is recommended TPU architecture and you can follow Profile TPU VM guide when using TPU VMs.


text:
Q: Avoiding unecessary recompilation with makefile I'm using makefile with gcc. Every c file has an accompanying header:
main.c main.h
test.c test.h
main.c includes main.h and test.h
test.c includes test.h
I want to avoid recompiling every c file. Makefile is ran without -B argument.
I can write the whole makefile manually and specify every dependency. When editing headers only the necessary c files get recompiled. An edit in test.h will recompile both c files and a change in main.h will only recompile main.c. As it should.
This doesn't work when I switch to the more automated approach:
OBJ = main.o test.o

%.o: %.c %.h
    $(CC) -c -o $@ $<

main: $(OBJ)
    $(CC) -o main $(OBJ)

A change in test.h will only recompile test.c. Leaving main.c in the old with the old version of test.h header. I'm forced to run makefile with -B, if I want to use this approach.
I can specify the headers manually:
DEPS = main.h sort.h

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $<

Then a change in main.h recompiles both main.c and test.c, the latter being unnecessary.
Updating every change in the makefile is unwieldy if I have a lot of files, and using the automated approach will increase compilation times.
Is there a better solution, one that only recompiles the needed files, or is specifying everything manually the only way?

A: You can specify additional dependencies of main.o using another line:
OBJ = main.o test.o

main.o: test.h

A: If you decide to specify manually, though, you're doing it wrong; you don't want to add the dependencies to the pattern where it takes effect for every object file.  You define it separately for each object file so they're only rebuilt when the right ones change:
OBJ = main.o test.o

%.o: %.c
        $(CC) -c -o $@ $<

main: $(OBJ)
        $(CC) -o main $(OBJ)

main.o: main.h test.h
test.o: test.h

Maintaining those last lines is what the automated dependency generation does, if you decide you want to try to use it.


text:
Q: Logstash not forwarding logs to ES via Kafka I'm using ELK 5.0.1 and Kafka 0.10.1.0 . I'm not sure why my logs aren't forwarding I installed Kafkacat and was successfully able to Produce and Consume logs from all the 3 servers where Kafka cluster is installed.
shipper.conf
input {
    file {
            start_position => "beginning"
            path => "/var/log/logstash/logstash-plain.log"
            }
}

 output {
 kafka {
    topic_id => "stash"
    bootstrap_servers  => "<i.p1>:9092,<i.p2>:9092,<i.p3>:9092"
  }
}

receiver.conf
input {
kafka {
        topics => ["stash"]
        group_id => "stashlogs"
        bootstrap_servers  => "<i.p1>:2181,<i,p2>:2181,<i.p3>:2181"

}
}

 output {
    elasticsearch {
       hosts => ["<eip>:9200","<eip>:9200","<eip>:9200"]
       manage_template => false
       index => "logstash-%{+YYYY.MM.dd}"
  }
 }

Logs: Getting the below warnings in logstash-plain.log
[2017-04-17T16:34:28,238][WARN ][org.apache.kafka.common.protocol.Errors] Unexpected error
code: 38.
[2017-04-17T16:34:28,238][WARN ][org.apache.kafka.clients.NetworkClient] Error while fetching
metadata with correlation id 44 : {stash=UNKNOWN}

A: It looks like your bootstrap servers are using zookeeper ports. Try using Kafka ports (default 9092)


text:
Q: How to copy the text on the button into the EditText I have an EditText. Then I make a layout xml with four buttons called button.xml. When the user click, I load the button.xml. Then when the user click one of the buttons, the text on the button will be copied into the EditText. My question is how to copy the text on the button into the EditText?
Thanks

A: Try this
String text= yourbutton.getText().toString();
youredittext.setText(text);

A: Please try the following inside your desired event/function that you want to perform this action for you.
    Button btnTest = (Button) findViewById(R.id.myButton);
    EditText myTextBox = (EditText) findViewById(R.id.myEditBox);

    myTextBox.setText(btnTest.getText().toString());

Hope this helps.

A: First copy the text of the Button to a String Using the code
String btntext= BUTTON_ID.getText().toString();
Then paste the contents of the Edit Text using
EDITTEXTID.setText(text);

A: Button b= (Button) findViewById(R.id.mybutton);
EditText ed= (EditText) findViewById(R.id.edittext);
ed.setText(b.getText().toString());// get text futtonrom button and set text


text:
Q: How do I split up a list into two colums? Say for example I had this list:
list = ["a", "b", "c", "d", "e", "f"]

What would I need to do in order for it to be printed to the shell like this:
a    d
b    e
c    f

Any ideas?

A: Here is an interesting solution that is pretty easy to understand, and has the added benefit of working regardless of the number of list elements (odd or even).
Basically, this will divide the list by 2 to determine the mid-point.  Then begin iterating through the list, printing each element below the mid-point in the first column, and printing any element above the mid-point by adding the mid-point back to the index of the first element that was printed.
For example: in list l below, the mid-point is 3.  So we iterate over l and print index element 0 in the first column, and print index element 0+3 in the second column. And so-on... 1 and 1+3, etc.
import math

l = ['a', 'b', 'c', 'd', 'e', 'f']
l2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

# set our break point to create the columns
bp = math.floor(len(l)/2) # math.floor, incase the list has an odd number of elements

for i,v in enumerate(l):
    # break the loop if we've iterated over half the list so we don't keep printing
    if i > bp:
        break
    # Conditions:
    # 1. Only print v (currently iterated element) if the index is less-than or equal to the break point
    # 2. Only print the second element if its index is found in the list
    print(v if i <= bp-1 else ' ', l[i+bp] if len(l)-1 >= i+bp else ' ')

Just swap the l and l2 list names to test the different lists.  For l, this will output the desired results of:
a   d
b   e
c   f

And for l2 will output the results of:
a   d
b   e
c   f
    g

Hope this helps!

A: Quick answer:
list = ["a", "b", "c", "d", "e", "f"]
newList = []
secList = []
if len(list)%1 == 0: ###will only work is list has even number of elements
    for i in range(len(list)):
        if i < len(list)/2:
            newList.append(list[i])
        else:
            secList.append(list[i])

for i,j in zip(newList, secList):
    print i,j


text:
Q: How to remove green from greenscreen video on python? I am doing a project where I am attempting to take out the green screen on a video on python but I do not know how to go about it.
Thank you!

A: well...I presume you have some kind of RGB image for each frame of video.
I.e an N by 3 array.
(You could use OpenCV to read each frame.)
So it is case of going through the image and locating all the green and replacing it with what you want.
E.g if the array is called arr then for each row, i, you would check whether arr[i] == [0,255,0].
But due to the nature of film, you aren't going to have a perfectly uniform 0,255,0 green. There will be shadows and other slight variations. Perhaps it wasn't even 0,255,0 to start out with.
So you are going to be looking at removing a range of colours. Now for each row we are searching for a range of colours and replacing them with your choice.
We now run the risk of identifying a colour for removal that we don't actually want removing....so how can we check for that...
We still probably won't get a perfect match around the edges (of the objects/people we want to keep in the image), so to make this less obvious, we might want to use a little bit of blur and so on and so forth.
Look at this video: https://www.youtube.com/watch?v=rIWoLCFvjME
Try to think about what logic code is required for each little step the user takes.
Also think about all the decision the user makes that are purely subjective. Obviously these would be nigh-on impossible to automate reliably. So now we are talking about some kind of interactive application that allows the user to select different actions based on their subjective choice.
And we quickly see why green screen is often removed manually, frame by frame using a powerful editing application like photoshop, after effects etc...
OpenCV (http://opencv-python-tutroals.readthedocs.org/en/latest/) will do a lot of the algorithms for you...there is almost enough there to build your interactive greenscreen removal software...


text:
Q: Custom Currency symbol and decimal places using decimal.ToString("C") and CultureInfo I have a problem with decimal.ToString("C") override.
Basically what I wants to do is as follows:
CultureInfo usCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = usCulture;

NumberFormatInfo LocalFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
LocalFormat.CurrencySymbol = "RM";

I wants to make above code a function (override ToString("C")) whereby when the following code get executed:
decimal paid = Convert.ToDecimal(dr["TotalPaids"]);
lblPaids.Text = paid.ToString("C");

The results would be RM4,900.00 instead of $4,900.00
How do I create an override for decimal.ToString("C") that would solve my problem
Thanks in advance.

A: If I understand your question correctly what you want is to replace the $ with RM. If so, you need to pass the custom format...
lblPaids.Text = paid.ToString("C", LocalFormat);

A: use this format string :

#,##0.00 $;#,##0.00'-  $';0 $

decimal paid = Convert.ToDecimal(dr["TotalPaids"]);
lblPaids.Text = paid.ToString("#,##0.00 $;#,##0.00'-  $';0 $");

A: You can use the Double.ToString Method (String, IFormatProvider) https://msdn.microsoft.com/en-us/library/d8ztz0sa(v=vs.110).aspx
double amount = 1234.95;

amount.ToString("C") // whatever the executing computer thinks is the right fomat

amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ie"))    //  €1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("es-es"))    //  1.234,95 €
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-GB"))    //  £1,234.95

amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-au"))    //  $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-us"))    //  $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ca"))    //  $1,234.95

A: To get a format like RM 11,123,456.00 you also need to set the following properties
CurrentCulture modified = new CultureInfo(Thread.CurrentThread.CurrentCulture.Name);
Thread.CurrentThread.CurrentCulture = modified;
var numberFormat = modified.NumberFormat;
numberFormat.CurrencySymbol = "RM";
numberFormat.CurrencyDecimalDigits = 2;
numberFormat.CurrencyDecimalSeparator = ".";
numberFormat.CurrencyGroupSeparator = ",";

If you do that at application startup then that should make ms-MY format like en-US but with the RM currency symbol every time you call the ToString("C") method.

A: lblPaids.Text = paid.ToString("C",usCulture.Name);

Or
lblPaids.Text = paid.ToString("C",LocalFormat.Name);

must Work


text:
Q: Redirect all api's to different url from middleware Laravel I have been trying from long time to redirect all api's to different url.
There are 2 servers , external and internal. i want to redirect all api's from external server to internal server because external server can't connect to database which is on internal server.
i am trying to redirect all api's from middleware in external. but if
   <?php

   namespace App\Http\Middleware;
   use Closure;
   use Illuminate\Http\Request;
   use Redirect;
   use Route;
  class RedirectExternalRequest
 {
  /**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
     $api_route = $request->route()->uri();
     return $redirect = Redirect::to(env('FVG_INTERNAL_SCHEME','').env('FVG_INTERNAL_URL','').$api_route);
}
}

but it changes the URL.
what i want is , send the same request to different URL , get the response and return the response from middleware.
response can be view, file , or JSON.
looking forward for your kind response. Thank You !


text:
Q: Problems with JSON and Memory I'm trying to load a lot of data from the web to my android application and I've been getting this error:
07-18 10:16:00.575: E/AndroidRuntime(30117): java.lang.OutOfMemoryError: [memory exhausted]

and already read a lot about JSON. I've found some solutions but nothing really helped me.
This is my code :
public class HistoricoAdapter extends BaseAdapter {
    private Context ctx;
    JSONArray jsonArray;

    public HistoricoAdapter(Context ctx) {
        this.ctx = ctx;

        String readHttp = readHttp();

        try {
            // transforma a string retornada pela função readHttp() em array
            jsonArray = new JSONArray(readHttp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String readHttp() {

        // Acessa a URL que retorna uma string com  os dados do banco
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("some url");
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();

            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e(this.toString(), "Erro ao ler JSON!");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return builder.toString();
    }

    public int getCount() {
        return jsonArray.length();
    }
    public boolean isEmpty(){

        if(jsonArray.toString().isEmpty()){
            return true;
        }
        else {
            return false;
        }
    }

    public Object getItem(int position) {
        JSONObject ob = null;
        try {
            ob = jsonArray.getJSONObject(position);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return ob;
    }

    public long getItemId(int arg0) {
        return 0;
    }

    public View getView(int position, View view, ViewGroup arg2) {

        LayoutInflater layout = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View v = layout.inflate(R.layout.listar_compromisso, null);

        try {
            JSONObject obj = (JSONObject) getItem(position);

        } catch (Exception ex) {

        }

        return v;
    }
}

Can anyone predict why am I getting this error?

A: If you get this error then your JSON must be too large to be buffered into memory.
The problem is org.json is too basic to handle that.
You need an advanced library to stream responses instead such as GSON or Jackson.

*

*GSON - Streaming

*Jackson - Processing model: Streaming API

A: There are a few issues with this code. First thing I noticed is your not calling your web request inside of an asynctask. You want to use async task for all long running operations and you have to use it for web calls.
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...), and most often will override a second one
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
}

You should also use JSON to build your object object. It has been tested and you can find information about how much objects can handle under there documentation. Here is a little bit of information from there site:
Gson Performance and Scalability
Here are some metrics that we obtained on a desktop (dual opteron, 8GB RAM, 64-bit Ubuntu) running lots of other things along-with the tests. You can rerun these tests by using the class PerformanceTest.
Strings: Deserialized strings of over 25MB without any problems (see disabled_testStringDeserializationPerformance method in PerformanceTest)
Large collections:
Serialized a collection of 1.4 million objects (see disabled_testLargeCollectionSerialization method in PerformanceTest)
Deserialized a collection of 87,000 objects (see disabled_testLargeCollectionDeserialization in PerformanceTest)
Gson 1.4 raised the deserialization limit for byte arrays and collection to over 11MB from 80KB.
Also, build your class objects using Json to Java object convert like there one. There are many more if this link doesnt end of working later on. Do a simple Google search.
Convert from json to Java Objects but you can also convert to your own custom objects.
Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};

(Serialization)
gson.toJson(ints);     ==> prints [1,2,3,4,5]
gson.toJson(strings);  ==> prints ["abc", "def", "ghi"]


text:
Q: Keystone correct an image
Possible Duplicate:
transform a trapezium into a rectangle

I have taken a picture of a piece of paper (standard letter-sized) with a camera.  But I was not able to perfectly position the camera, so the picture of the piece shows up as a trapezoid.  Are there any free or inexpensive tools that can correct this type of error easily.
I do know the full version of photo shop can do this, but this is something I very rarely need, I am not interested in selling a kidney to fix this image.


text:
Q: Multiple IF conditions My code has a textbox called 'answer_textbox'. When the user types in their answer into the textbox and presses enter, some jQuery code is supposed to take place. First of all i don't know how to have multiple if conditions. Are they supposed to be like this?
if($('#answer_textbox').val() == 4 && 'four') {

After that code is executes i have a else if that has a alert box that pops up is the user spells 'for' instead of 'four' for the answer.
if($('#answer_textbox').val() == 'for') {
    alert('FOUR you moron');
}

But this will only work when the user spells 'for' without putting a space after spelling it. Like if they spelled 'for' and put one single space after it it wouldn't work. How do i fix this?

A: You can check the index of the word in the value: check if the word 'for' exists in value:
if($('#answer_textbox').val().indexOf('for') >= 0) {

You also can trim the spaces of the value and then exact match:
if($('#answer_textbox').val().trim() == 'for') {

.... And with case insensitive:
if($('#answer_textbox').val().trim().toLowerCase() == 'for') {

*

*You also can checking the closest match. Read more here: Getting the closest string match
Then about your multiple if's. It doesn't souns very nice. Why do you do it clientside?
if (condition)
{

}
else if (condition)
{

}
else if (condition)
{

}
else
{

}

Not very maintainable. Alternative is using switch:
switch (field)
{
   case: 'for':
      // add your logic
   break;

   case 'other':
      // add your logic
   break;

   default:
      // logic for default
}

A: The short answer is that you can store all of your answers in lowercase then do $(selector).val().toString().toLowerCase().trim(); to get the trimmed lowercase value of the user's input
However, you could make the whole thing a lot simpler than you have it.
I would do something like the below. With this method, adding or removing questions is trivial, just add the question and answer to the array:

// create a multidimensional array of your questions and answers
// answers should be in lowercase to make things easier later
var questions=[
    ['What color is the sky?','blue'],
    ['What color is the ocean?','blue'],
    ['What comes after C?','d'],
    ['What comes after 9?','10']
    ];
// loop through the array and add an input and text for each to the page
$.each(questions,function(index,element){
    $('#container').append('<input type="text" class="answer"> '+ element[0]+'
')
});
// when a user presses enter in one of the inputs, check the answer
$('#container input').on('keydown', function(e){
    if(e.which == 13) { // enter was pressed
       var question = $('.answer').index($(this)); // get the index of the current input
       var answer = $(this).val().toString().toLowerCase().trim(); // get the typed answer
       var correct =  questions[question][1]; // get the correct answer for this question
        if(answer==correct){
            $(this).removeClass('incorrect');
            $(this).addClass('correct'); // mark correct
        }
        else{
            $(this).removeClass('correct');
            $(this).addClass('incorrect'); // mark incorrect
            $('#result').html(correct+' you moron'); // funny message
            setTimeout(function(){ $('#result').html('') }, 2000); // remove message after a few seconds
        }
    }
});
.correct{
    background-color:#99FF99;
}
.incorrect{
    background-color:#FF6666;
}
#result{
    color:#FF0000;
}


text:
Q: Possible mistaken empty statement – compiler is mistaken in this case I feel so silly asking this, but how do I instruct the compiler that it is not a mistake? I really intend to have an "empty" branch in my if statement, with a clear else at the end catching the bad values.
I can of course restructure the whole if around this, but it'll be less clear as a result, and working around a silly compiler warning seems weird. Also I'd prefer if I didn't have to disable the entire warning, just for this specific statement.

A: #pragma warning disable xxxx
if (condition)
{
  // north of the wall, nada, nothing
}
else
{
  // code
}
#pragma warning restore xxxx

A: why not just putting a bang in front of your if condition so you can avoid using the else entirely?
if(!condition){
  //just work here
}

edit: updating answer based on question author comment (its multiple conditions)
if(condition1){
  // code here
}
else if(condition2){
  // code here
}
else if(!condition3){
  //error case here
}

A: Well I knew it was something silly, simply using an empty block gets rid of it:
if(condition1)
  // code here
else if(condition2)
  // code here
else if(condition3)
{
    //nothing to do
}
else
  // error case here

A: To suppress compiler warnings, VS2010 has compiler options and #pragma options. Compiler options affect the whole program. #pragma options can affect the whole program. #pragma options can also locally turn specific warning(s) off just before targeted code, and then turn then back on just after. #pragma warning disable 0642 will hide this warning. #pragma warning restore 0642 will restore it. This is just ugly. Other IDEs that I have seen allow single-line overrides of warnings (specific text in a comment immediately after the provoking code), but VS2010 seems not to have done this. (I could be wrong. Anyone know?)
The only fix is worse than your "problem". Local #pragma directives will make your code uglier than it is, while removing the warning. Ultimately you are better off doing what the smart people suggested. (They sometimes miss the boat.) Getting your way is not necessarily winning. You have to admit that possibility in order to deserve answers on how to do it regardless of whether it is an improvement.
Basically this question is a PREFERENCE thing. You should have said that from the get-go, by showing (with code) what you are talking about, instead of abusing helpful people by making them guess and guess again.
The compiler warning suggests that you probably should NOT write this:
if (expression)
    ;  // Do nothing, because blah blah blah.
else
{
    code that;
    does something;
}

, but instead pick one of:
if (expression)
{
   // Do nothing, because blah blah blah.
}
else
{
    code that;
    does something;
}

or
if (expression)
{ }  // Do nothing, because blah blah blah.
else
{
    code that;
    does something;
}

You DID NOT "specifically mention this" (someone else's rewrite of code you never provided) "as a possible solution ...". Also you did not say whether you reject Riad's change of ; to { ... } or his surrounding #pragmas (which, by the way, are only necessary if you do NOT change ; to { ... }).
IN NO WAY do these variations amount to "restructur[ing] the whole if [statement] around [removing] this [warning]". (That would be if (!expression) { code that; does something; }.)
IN NO WAY are these variations ANY "less clear" than the original.
I wouldn't mind knowing an override that isn't ugly. I might want to write something like the following, because I like to omit all those silly surrounding braces-on-empty-lines that would make sections like this twice as tall:
if (condition1)
  action1;
else if (condition2)
  ;  // (do nothing)
else if (condition3)
  action3;
else if (condition4)
  ;  // (do nothing)
else if (condition5)
  action5;
else
  action99;

Apparently I have to use one of the uglier options to avoid those annoying "Possible mistaken empty statement" warnings.

A: If you replace
;

with
((Action)(() => { }))();

, the warning should go away.
(Drawback: This might take time to execute at runtime, a waste. If so, it should only be used for tracing (if it works for that), and it should be removed or replaced before shipping.)
from: Simple C# Noop Statement


text:
Q: Docker, database copied to a volume has 0kb size I created docker image using following Dockerfile:
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
COPY . .
ENTRYPOINT ["dotnet", "RPDemo.dll"]

The project's database is located in this location ./database/db_demo.db
Docker image build without issue:
docker build -t rpdemo-docker:1.0.0 .

I would like to persist database outside of the container. I specified volume mounting with this command:
docker run --name rpdemo-container -v /mnt/cache/dev/database:/app/database -p 8383:80 rpdemo-docker:1.0.0

It seems that folder inside container is mounted to external folder. The database is copied, but it has 0kb size.
Without -v flag, application is running and database resides inside container and it is usable. Database and other files needs to be persisted to external folder.
UPDATE: I created container again with -v flag. /database folder was mounted to external folder /mnt/cache/dev/database, but /database folder inside container was empty. One of the app pages pulls data from database. Once I clicked on this page, db file was created with 0kb length. This is were connection string expects database to be located. It seems that -v /mnt/cache/dev/database:/app/database overwrites folders content.

A: As David say in a comment, when you mount a volume, it replace the current directory with the volume.
If your volume is new, it will be an empty directory.
Actually, you add the database in the image, but when you start the container, you replace the database directory with a new one, and your application may create the database file if it doesn't exists. It's why you found an empty sqlite database.
If you want to have your database inside your volume, you have 2 choices:
- Copy manually it in your volume
- Have an init script that copy the database from somewhere into your database directory if it doesn't exists
For the second choice, you may do it in the entrypoint script and you may have a directory with a different name for your database like /app/init-database and the script will check if /app/database/db_demo.db exists, if not, do cp /app/init-database/db_demo.db /app/database/db_demo.db


text:
Q: ¿ Como generar una identificación de usuario única para cada usuario en un python app? Estoy desarrollando un chatbot desde este repositorio y quiero que él pueda identifiar el usuario. ¿Entonces sabe cómo obtener algo en línea que puede generar una identificación de usuario única para cada usuario (los ID de usuario para la investigación deben tener la capacidad de almacenarse de forma anónima) ? Por el momento solo se interconecta con Slack
from rasa_core.channels import HttpInputChannel
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
from rasa_slack_connector import SlackInput

nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/weathernlu')
agent = Agent.load('./models/dialogue',interpreter = nlu_interpreter)

# https://api.slack.com/apps/AASPDV196/oauth?
input_channel = SlackInput('OAuth Access Token','Bot User OAuth Access Token',
'Verification Token',True)

agent.handle_channel(HttpInputChannel(5004,'/',input_channel))

Y utilisar uuid.uuid4() pero no estoy seguro. También estoy pensando en crear una página real que registre usuarios, pero no estoy seguro de que permita a Slack. Slack no es obligatorio pero, aparte de la terminal, no tengo ninguna otra interfaz de comunicación Chatbox por el momento.


text:
Q: how to write airflow error logs into s3 bucket using python when my airflow dag fails i get the errors in the path
"/home/ec2-user/software/airflow/logs/dagtest_dag/trigger_load/2019-10-10T06:01:33.342433+00:00/1.log
"
how to take these log to s3 bucket?

A: Configure this as a cron job.
import boto3

s3 = boto3.client('s3')
# Make sure your client is authenticated
with open('path/to/your/logs.log', 'rb') as data:
    s3.upload_fileobj(data, 'bucketname', 'path/to/your/logs/in/s3.log')


text:
Q: Python 2.7 MySQL-python Link Error I know that this has been asked a few times on here, but I have tried every solution given on each question this was asked. I've been trying to solve this for about 5 hours now, I even went to the extent of reinstalling windows to hope it magically would fix it. With that being said:
I'm running windows 10 64bit and using Python 2.7. I'm trying to do 'pip install MySQL-python' and I keep getting this:
LINK : error LNK2001: unresolved external symbol _DllMainCRTStartup
fatal error LNK1120: 56 unresolved externals
error: command '"C:\Users\Nick\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\link.exe"' failed with exit status 1120

Here is my entire CMD:

I apologize if any of the formatting is wrong here, I don't post much.


text:
Q: Callback function and do while loop issue var game = {
    setPlayerNum: function(){
        var num = parseInt(prompt("Enter Number of Players"));
        this.setPlayerName();
    },

    setPlayerName: function(){
        if (num == 2){
            do {
                var playerOne = prompt("Enter Your Name");
                } while(true){
                var playerTwo = prompt("Enter Your Name");
                break;
            }
        }

    },

    boardInitialize: function(){

    },

    boardInitializeView: function(){

    },

}

I have two functions with an object. First function runs fine, but the callback function isn't running. I am not sure why

A: A couple of things. A scope issue, and an unnecessary and badly formatted while loop. Try this:

var game = {

    num: 0,
    playerOne: '',
    playerTwo: '',

    setPlayerNum: function(){
        this.num = parseInt(prompt("Enter Number of Players"));
        this.setPlayerName();
    },

    setPlayerName: function(){

        this.playerOne = prompt("Enter Your Name");

        if (this.num == 2){

            this.playerTwo = prompt("Enter Your Name");

        }
    }
}

game.setPlayerNum();

To explain the scope issue a bit more: the num variable that you originally declared in your setPlayerNum method, was not available to the other methods outside of that scope. By declaring the num variable first, as part of the object, you can reference it. I have done the same to your playerOne and playerTwo variables.
But you might find it a bit nicer to re-arrange the script so that you can have any number of players:

var game = {

  playerNames: [],

  setPlayerNum: function(){

    var num = parseInt(prompt("Enter Number of Players"));

    for (var i = 0; i < num; i++) {

      this.setPlayerName(i + 1);

    }
  },

  setPlayerName: function(num){

    this.playerNames.push( prompt("Enter Your Name For Player " + num) );

  }
}

game.setPlayerNum();

A: That's not the syntax of the do/while statament. You can't open a scope after the while, you should end the do/while statement there with a ";".
Check this
http://www.w3schools.com/jsref/jsref_dowhile.asp.
I don't understand what you are trying to do, but I'm guessing that the do/while is not necesary. You could do something like this:
function() {
    var playerOne = prompt("Enter Your Name");
    if (this.num == 2){
        var playerTwo = prompt("Enter Your Name");
    }
}


text:
Q: Using delimited rowkey in hbase Can i have  a combination of 3 Strings as the row key in HBase? For instance, a combination of X , Y and Z values identify one unique record.
I will be connecting to Hbase using Java
Could you please let me know if this is possible?
Thanks in advance.

A: With the risk of being trivial, concatenate your strings with a separator, to produce something like "x|y|z" for instance.

A: you can use delimiter such as '|' or length prefixed strings for rowkeys.
you could also refer to OpenTSDB for schema design.

A: HBase doesn't stop you from doing that. Although you could use any character as a separator, try using something uncommon, say "~" or "^". Reason being, characters like "|" or "," are highly likely to appear as a part of the data.
A couple of suggestions though :

*

*Try to keep the length of rowkey as less as possible.

*Try to use numeric keys instead of strings if possible.

HTH
P.S. : The best way to get answers to these type of queries is to try it. This is something which should not take more than a few minutes.

You can make use of PrefixFilter to achieve that. Given a prefix, specified when you instantiate the filter instance, all rows that match this prefix are returned to the client. The constructor is:
public PrefixFilter(byte[] prefix)
Example :
Filter filter = new PrefixFilter(Bytes.toBytes("9874541235^MOBILEDEVICE^MOBILESOURCE"));
This will give you all the rows which are starting with 9874541235^MOBILEDEVICE^MOBILESOURCE.


text:
Q: Validation Through a View Model Graph/Tree My problem requires that I validate various fields across a view model according to some dependencies.  I'm using Silverlight, Prism and MVVM.
As an example (changed from my real world scenario):

Each ship can have many containers, a container can have many items.
Each one of the classes inherits from NotificationObject and calls RaisePropertyChanged whenever a property is changed.
My business rules are to to ensure that Item.Colour, Item.Name and Item.Size are not empty when the property Ship.TypeId is equal to 1.  If Ship.TypeId is equal to anything else, I do not need to validate the properties in Item.
At the moment validation is being carried out in the view model in the OnPropertyChanged event.
The problem I face is that if I add validation in the Item class, then the object has no knowledge of the Ship.TypeId.  If I subscribe to the PropertyChanged events thrown out by Item and Container, I can detect property changes from within Ship but can only get the property name (relative to the child class, i.e. Name) but no old or new values.
What I want to be able to do is validate the child items whilst knowing that the Ship.TypeId is and also be aware of which Name, Colour or Size property has changed and be able to raise an error against the correct field on the UI.
Many thanks,
Adrian

A: As you point out, since Item does not know anything about a Ship, it should not be doing validation that involves Ships. It might be possible to add a property to Item that does make it possible to validate locally (eg CanBeEmpty), but without knowing more I can't say if that would make sense.
You do not specify what format the editing takes, so it's difficult to comment. If both ships and items can be edited live on the same screen, then the validation be made to fail by editing an item, or editing a ship. In this case I usually defer validation until all edits are committed by clicking OK or whatever. It gets really frustrating editing multiple things when you're forced to keep things valid at all times.
If you can only edit items in isolation from ships, and the extra property on Item itself does not make sense, then I would suggest wrapping your Items in an ItemEditViewModel that does know about ships. This seems reasonable since creating valid item edits requires knowledge of ships, so ViewModels in such an edit screen also need knowledge of ships.