text:
Q: Redirect taxonomy to custom template to list terms in taxonomy I'm trying to adapt some code on calling a custom template via rewrite rule.
I have a custom taxonomy called "state".  I want to create an archive for the taxonomy, that lists all the terms in that taxonomy.
http://www.site.com/state
Would load my custom template where I can query the terms and loop through them.
Alabama
Alaska
Arizone
Arkinsas, etc
I know there is a possibility of some conflict if I had a page named "state" too, but that's a risk I can take.
The code in the tutorial works really well for
http://www.site.com/state/1 or http://www.site.com/state/2 but returns a 404 if there is no number captured.
and that number would be good for pagination if the terms list gets out of control.
Here's the code:
add_action('admin_init', 'handle_taxonomy_route');
function handle_taxonomy_route()
{
    add_rewrite_rule('^state/([^/]+)/?', 'index.php?state_var=$matches[1]', 'top');
}

add_filter('init', 'declare_vars');
function declare_vars()
{
    add_rewrite_tag('%state_var%', '([^&]+)');
}

add_filter('template_include', 'my_template', 1, 1);
function my_template($template)
{
    global $wp_query;

    if (isset($wp_query->query_vars['state_var'])) {
        return dirname(__FILE__) . '/state-list.php';
    }
    return $template;
}

From what I have tried so far, it doesn't appear to conflict with
http://www.site.com/state/alabama
Where Alabama is a term in the state taxonomy, but it should definitely only capture numbers.
A similar question went unanswered last year. How do I list terms of a custom taxonomy at i.e. domain.com/brands/

A: The 404 might be created because your regular expression requires the value after 'state/'. Please try to replace:
function handle_taxonomy_route()
{
    add_rewrite_rule('^state/([^/]+)/?', 'index.php?state_var=$matches[1]', 'top');
}

with:
function handle_taxonomy_route()
{
    add_rewrite_rule('^state/([^/]*)/?', 'index.php?state_var=$matches[1]', 'top');
}

A: I needed a better rewrite rule for proper pagination.
function kia_custom_rewrite() {

    // registers the state_var query variable
    add_rewrite_tag('%state_var%','([^&]+)');

    // handles site.com/state and pagination such as site.com/state/page/2
    add_rewrite_rule(
        'state(/page/([0-9]+)?)?/?$',
        'index.php?state_var=all&paged=$matches[2]',
        'top'
    );

}
// refresh/flush permalinks in the dashboard if this is changed in any way
add_action( 'init', 'kia_custom_rewrite', 99 );

The rewrite rule adds the query_var to check for here:
/*
 * Load custom templates
 * 1. Get a custom template for the /state "page"
 * 2. Get a custom template for the /state/some-state term
 */
function kia_template( $template ){
    global $wp_query;

    if ( 'all' == get_query_var('state_var') ) {
        $template = get_stylesheet_directory() . '/taxonomy-state-list.php';
    }

    return $template;
}
add_filter( 'template_include', 'kia_template' );


text:
Q: Looking for Cover letter template I'm looking for cover letter template which would fit with this CV, PDF here. Can anyone suggest anything similar to that (just a regular cover letter, sender's address on top right, recipients lower on the left, text follows ...).
I'm  newbie to LaTeX, and somewhat short on time, otherwise would have try to compose my own. But as the situation stands, unfortunately, haven't got the time for experimenting :/

A: The newlfm class or the scrlttr2 class (from the KOMA-Script bundle) could be an option.
EDIT: here's a simple example adapted from Matthew J. Miller's template
\documentclass[10pt,stdletter,dateno]{newlfm}
\usepackage{kpfonts}
\usepackage{url}

\widowpenalty=1000
\clubpenalty=1000

\newlfmP{headermarginskip=20pt}
\newlfmP{sigsize=50pt}
\newlfmP{dateskipafter=20pt}
\newlfmP{addrfromphone}
\newlfmP{addrfromemail}
\PhrPhone{Phone}
\PhrEmail{Email}

\namefrom{Matthew J.\ Miller}
\addrfrom{%
    \today\\[10pt]
    439 Coordinated Science Laboratory\\
    1308 West Main Street\\
    Urbana, IL 61801
}
\phonefrom{217-244-6024}
\emailfrom{mjmille2@uiuc.edu}

\addrto{%
Faculty Search Committee\\
Department of Computer Science\\
Clemson University\\
Clemson, SC 29634-0974}

\greetto{To Whom It May Concern,}
\closeline{Sincerely,}
\begin{document}
\begin{newlfm}

I am writing to apply for the position of assistant
professor in Clemson University's Computer Science Department.  I plan to receive my
Ph.D.\ degree from the University of Illinois at
Urbana-Champaign in Summer of 2006.  My adviser is
Prof.\ Nitin H.\ Vaidya, and my general areas of interest
include wireless and sensor network performance and security.
 Having many friends and family in the area, I would be
most enthused to return to the South permanently by accepting
a position at your institution.

In my graduate work, I focus on the design of
energy-efficient protocols and secure key distribution.
More specifically, I have explored various techniques at
multiple layers of the network stack to effectively reduce
the energy consumption of wireless communication.  In security,
my work was the first to propose leveraging channel diversity
for sensor network key distribution.  My research appears in
the \textit{IEEE Transactions on Mobile Computing} journal as
well as \textit{Infocom 2006} and \textit{ICDCS 2005},
prestigious conferences in the areas of networking and distributed
systems, respectively.

Enclosed is my curriculum vitae (including a list of
publications), contact information for my references, a research
statement, and a teaching statement.  All of my publications and
presentations are available at:

\url{http://www.crhc.uiuc.edu/~mjmille2/publications/}

Please let me know if there are any other materials
or information that will assist you in processing my application.

Thank you for your consideration.  I look forward to
hearing from you.

\end{newlfm}
\end{document}

A: In Miktex 2.9 you can choose New File > File From Template > Basic Templates > Letter.
Edit to make this clearer:
I don't know what you are using to write your Latex documents.  I use a free tool called MiKTeX version 2.9 which offers some built-in templates, although you can use document classes for which there are no templates.  As I mentioned it can be downloaded for free.  You could search for "miktex download".
When I go to my start menu and look for Miktex 2.9, I choose Texworks.  That will open an editor.  Using the file menu you choose each of these choices in turn: File > New File from template > Basic Templates > Letter.   This will open a file with some Latex code in it already, a template for a letter.  You can change the code that is there if you want.  Today I had to remove the part that makes a mailing label for the recipient because it showed at the end of my letter which I intend to post online as a cover letter.  I don't need a mailing label.
I don't know about other Latex editors but you might try opening a latex document with:
\documentclass[letterpaper,12pt]{letter}
\begin{document}
\begin{letter}{recipient name and address}

if you are using a different editor that does not have templates.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to list folders in python that contain certain file types So I'm incredibly new to python and am trying to learn it for my work search.  I'm looking at what I can automate on my computer and right now I have a lot of photos, videos, etc of my family, kids, etc that are all over the place on my network drive and I want to organize that.  What I'd ideally like to do is have a script that either hard codes or asks for a list of file types to look for, preferably ask the user as I would intend on using this for multiple different file types.  When done the script lists the folder(s) that contains those files and then moves on to moving the folder to the new location or just the files.  I've looked around on google searches but haven't found what I'm looking for.  Is this even possible in python?
Edit: Here's the original script I made. I hardcoded the jpg file type only as I didn't see how to do multiple file types.
import glob, os, shutil

source_folder = input("Please enter the path and name of the folder you want"
                   " to move. (E.g: C:/Users/myusername/Desktop/myphotos):"
                   "\n")

files = glob.iglob(os.path.join(source_folder, "*.jpg"))
print(source_folder)

move_folder = input("Do you want to move the folder and its contents? (Y/N) ").lower()

print(move_folder)

dest_folder = input("Please enter the destination path (E.g: C:/Users/myusername/folder1):"
                    "\n")

if not os.path.exists(dest_folder): #create folder if it doesn't exist
    os.makedirs(dest_folder)

print(dest_folder)

if move_folder == "y":
    print("Ok. Moving folder now.")
    shutil.move(source_folder, dest_folder)
elif move_folder == "n":
        print("Ok. Only moving files in the folder")
for file in files:
   if os.path.isfile(file):
        shutil.move(file, dest_folder)
        print("Ok work complete")

A: Use wildcards for both file_name and file_type to move multiple file types
import glob, os, shutil

def _list_files(source_folder):
file_list = []
for path, subdirs, files in os.walk(source_folder):
    for name in files:
        file_list.append(os.path.join(path, name))

count_dict = {}
for i in file_list:
    format_ = i.split(".")[-1]
    if format_ in count_dict.keys():
        count_dict[format_] += 1
    else:
        count_dict.update({format_:1})
print("\n\nDirectory and sub-directories contains:")
for key, value in count_dict.items():
    print(f"{value} {key} files.")

return file_list

def copy_files(file_list, source_folder, move_folder):
dest_folder = input("Please enter the destination path (E.g:C:/Users/myusername/folder1):""\n")
if not os.path.exists(dest_folder):
    os.makedirs(dest_folder)
if move_folder == 'y':
    shutil.move(source_folder, dest_folder)
    print("Move Completed!")
elif move_folder == 'n':
    file_types = input("Enter list of file types to copy \n or enter 'all' to copy all files \n Eg: ['jpeg', 'png', 'csv']")
    if isinstance(file_types, list):
        for i in file_types:
            for file in file_list:
                if os.path.isfile(file_path):
                    shutil.move(file, dest_folder)
                    print("Move Completed!")
    elif isinstance(file_types, str) and file_types=='all':
        for file in file_list:
            if os.path.isfile(file):
                shutil.move(file, dest_folder)
                print("Move Completed!")
    else:
        raise ValueError("Unable to determine file type")

source_folder = input("Please enter the path and name of the folder you want to move \n(E.g: C:/Users/myusername/Desktop/myphotos)")
source = _list_files(source_folder)

move_folder = input("Do you want to move the folder and its contents? (Y/N)").lower()
copy_files(source, source_folder, move_folder)


text:
Q: how to read object from servlet in android I am developing a android application that has to talk with the servlet to access the database. I want to pass the object from servlet to my android application.
This my servlet code to send object.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text");

    String id = request.getParameter("id");
    try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        java.sql.Connection con= DriverManager.getConnection("jdbc:odbc:Database");
        Statement statement = con.createStatement();

        PrintWriter p = response.getWriter();

        ResultSet rs = statement.executeQuery("select * from employee where PS="+id);

        while(rs.next()){
            Employee e = new Employee();
            e.setId(rs.getString("ID"));
            e.setPs(String.valueOf(rs.getDouble("PS")));
            e.setName(rs.getString("Emp_name"));
            e.setDept(rs.getString("Dept"));

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(e);

        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

How should i read the object in my android application.
Thanks.

A: Well you can do various things to solve this problem
a)Use DAO practice here Read it to understand it basically it divides the implementation of your code into different segments and classes for your ease.
But if you dont want to go through all that trouble You can do some thing like.
a.) Create a separate java class where you write all the methods to deal with the Db like insert,select etc..
e.g if your loggin in the user.. than the method would be like this..
public int AuthenticateUser(String un, String pw, String phn) {
        System.out.println("I m in this method");
        Connection conn = (Connection) DBConnection.getInstance().getConnection();
        Statement pstmt = null;
        ResultSet rs = null;

        if (conn == null) {
            System.out.println("Connection error");
            check = -1;

        }

        try {
            String authenticatequery = "SELECT * FROM users WHERE uname = '"+un+"' && password =  '"+pw+"' && phoneno = '"+phn+"'";

            System.out.println(authenticatequery);
            pstmt = conn.createStatement();
            rs = pstmt.executeQuery(authenticatequery);
            System.out.println("I m in above try catch");

            // pstmt = conn.prepareStatement(authenticatequery);

            // rs = pstmt.executeQuery(authenticatequery);

            if (rs.next()) {
                System.out.println("I am in rs method");
                UserInfo  info = new UserInfo();
                rs.getString(1);
                rs.getString(2);
                rs.getString(3);
                //info.setUsername(rs.getString(un));
                System.out.println("i have the username" + un);
                //info.setPassword(rs.getString(un));
                System.out.println("I have got the password " + pw);

                System.out.println("I have got the password " + phn);

                System.out.println("User Exist");
                check = 1;
            } else {

                System.out.println("No user found");
                check = 0;
            }

            // rs.close();
            // pstmt.close();
            // conn.close();
        } catch (SQLException e) {
            // TODO: handle exception
            System.out.println("Exception-internal error");
        } finally {

            if (conn != null) {
                try {
                    conn.close();
                    pstmt.close();
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

}
    return check;

}

Notice the int variable "check" if the method runs correctly it will return '1' else '0'.. Now u can use this check for your advantage and send it to your android app via servlet like this..
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        //String username = request.getParameter("username");
    //  String password = request.getParameter("password");
        //UserInfo uinfo = new UserInfo();

    // uinfo.setUsername(username);
    // uinfo.setPassword(password);

        System.out.println("I am in process");

        PrintWriter out = response.getWriter();
          String un, pw,phn;

          un = request.getParameter("Usrnm");
          System.out.println(un);
          pw = request.getParameter("pwd");
          System.out.println(pw);

          phn = request.getParameter("phn");
          System.out.println(phn);

            Authenticate auth = new Authenticate();
            int check = auth.AuthenticateUser(un, pw,phn);
            System.out.println("My result is" + check);
          if (check==1){

              out.print(1);
          }  else{
               out.print(0);
              }
              }
    }

In your android app you can call the the response object using the code below, do add custom http client class for the comunitcation.
response = CustomHttpClient.executeHttpPost("http://192.1..11../HelloWorldServlet/LoginDriverServlet", postParameters);

Now  you can play with the response object and mould it to suit your needs
if (res.equals("1")) {

                        Log.e("CHeck4 response","i m here");
                        Log.e("CHeck response", res);
                        //error.setText("Correct Username or Password");
                        Intent intent = new Intent(getApplicationContext(), SetStatus.class);

                        startActivity(intent);
                        setContentView(R.layout.activity_set_status);
                        Toast.makeText(getApplicationContext(), "Loggin In", Toast.LENGTH_LONG).show();
                    } else if(res.equals("0")) {
                        //error.setText("Sorry!! Incorrect Username or Password");
                        Log.e("CHeck3 response", "i m here");
                        Toast.makeText(getApplicationContext(), "Sorry!! Incorrect Username or Password", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent();

                        //Username or Password",Toast.LENGTH_LONG).show();
                    }

Hope you get it..otherwise coments are welcomed :)


text:
Q: tab in a tab, onActivityResult not called I'm having a problem with the onActivityResult() method not being called. I suspect this is somehow due to the fact that the activity calling startActivityForResult() is in a tab which in turn is in another tab. Most of the code is in fact identical to a previous version in which the calling activity was just a tab (rather than a tab in a tab), and that version works just fine. Are there special considerations to keep in mind in this kind of circumstance?
Manu

A: This may not be a "proper" answer, but I've had several commercial products start using Tabs with TabActivity, and before the end, we had ripped them out and simulated tabs with buttons.  For anything non-trivial, TabActivity turns out to be a mess.  I can't imagine nested tabs.
My 2 cents.


text:
Q: NiFI: Execute a long-running process and have the results while the process still runs Hello I have a NiFi simple process group consisting on a GetTwitter connected to a ExecuteStreamCommand
GetTwitter Process ---> ExecuteStreamCommand
The executeStreamCommand reads the flowfile and do some analytics. Since the models that brings in memory are quite heavy, I was wondering if there was a way to keep the command alive and having the resulting flowfile without closing the execution of this one.
Thank you in advance


text:
Q: change window title with python on script start I put together a simple script to encode movies, now while the script works just fine I am having difficulties on changing the window title on script start instead on when its terminated. since is kind of useless to mark each window after it finished. can I use subprocess to perform such task? so change the title while the script runs?
I am using this in a bash script to change the title:
PS1="\e]2;$1\a\[$1 \W]\$"

A: if you are running the sub process without invoking any new terminal , you can rename the windows with below code
# your subprocess code here
import sys
sys.stdout.write(b'\33]0;title you want\a')


text:
Q: Auto set filter based on another filter in Tableau I have a dashboard with 2 date filters for fiscal month, each reading from different columns.  The primary filter runs most of the charts.  The secondary filter runs only on one table.
I want the secondary filter to automatically match what the user selects in the Primary filter at runtime.
You would think this would be pretty straightforward.  But I cannot find any sort of reasonable answer for this.  The ones I've seen span 4 years and still don't answer the question.
So, to summarize...  If the user chooses (for example) May-2018, and June-2018 in the Primary filter, I want the secondary filter to update with those same selections.


text:
Q: how to get text from combobox like item [1] when i use this code  "var z = comboBox.Items[1].ToString();" and then show z in                         "MessageBox" i get this message "DataMdellayer.custumer" but i want text of item 1
 <ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="57,63,0,0" VerticalAlignment="Top" Width="120"/>

and
comboBox.ItemsSource = database.Customers.ToList();
comboBox.DisplayMemberPath = "CustomerSay";
comboBox.SelectedValuePath = "CustomerID ";

A: You are using CustomerSay property of Customers to show the value.
When you say:
var z = comboBox.Items[1].ToString();

You are converting a Costumer to string
But, considering that you want that costumer's CostumerSay property, you have to look for it.
So you must cast your ComboBoxItem to Costumer
(Customer)comboBox.Items[1]

And then look for the property
var z = ((Customer)comboBox.Items[1]).CustomerSay

A: 1- You can cast your item to the data source object (customer) as @Marko said.
2- Use MVVM and bind your combobox to a ViewModel property. WPF has strong binding system to implement MVVM.
3- You can override ToString method of Customer class:
public class Customer
{
  public override string ToString()
  {
    return CustomerSay;
  }
}

I prefer the second solution, but if you don't want to use MVVM pattern @Marko's solution is better.

A: The index of item one starts at zero in c# so change your code like below to get the item one
var z = comboBox.Items[0].ToString();


text:
Q: YouCompleteMe and C++ diagnostics inappropriate errors I'm trying to get YCM working in Vim for C++ development. I'm using the JUCE framework. Ctags and autocompletion are working great. However, I'm getting lots of wrong errors come up in the 'gutter' as red arrows.
E.g.
no matching member function for call to 'addAndMakeVisible'

when addAndMakeVisible is a function of an inherited class Component and even comes up in the autocomplete.
Also getting lots of errors like the following:
cannot initialize object parameter of type 'juce::Component' with an expression of type 'MyComponent'

My .ycm_extra_conf.py: https://gist.github.com/adamski/a793a24b026f68a1074e
I am adding the JUCE libraries with absolute path as well as the local project version, and copied suggestion from @ladislas example.
Output of :YCMDebugInfo
https://gist.github.com/adamski/2e7dd79b45d0fb6f5010#file-ycmdebuginfo
Current output of :YCMDiags https://gist.github.com/adamski/8fad8e0724a03854912b
example repository that recreates the problem: https://github.com/adamski/juce-chapter02-07
My .vimrc looks like:
"" YouCompleteMe options
"
let g:ycm_register_as_syntastic_checker = 0 "default 1
"let g:Show_diagnostics_ui = 1 "default 1
"
""will put icons in Vim's gutter on lines that have a diagnostic set.
"Turning this off will also turn off the YcmErrorLine and YcmWarningLine
""highlighting
set tags=./tags,tags;
set autochdir
let g:ycm_enable_diagnostic_signs = 1
let g:ycm_enable_diagnostic_highlighting = 1
let g:ycm_always_populate_location_list = 1 "default 0
let g:ycm_open_loclist_on_ycm_diags = 1 "default 1
let g:ycm_seed_identifiers_with_syntax = 1

let g:ycm_complete_in_strings = 1 "default 1
let g:ycm_collect_identifiers_from_tags_files = 1 "default 0
let g:ycm_path_to_python_interpreter = '' "default ''

let g:ycm_server_use_vim_stdout = 0 "default 0 (logging to console)
let g:ycm_server_log_level = 'info' "default info

let g:ycm_global_ycm_extra_conf = '~/.ycm_extra_conf.py'  "where to search for .ycm_extra_conf.py if not found

let g:ycm_confirm_extra_conf = 1

let g:ycm_goto_buffer_command = 'same-buffer' "[ 'same-buffer', 'horizontal-split', 'vertical-split', 'new-tab' ]
let g:ycm_filetype_whitelist = { '*': 1 }
let g:ycm_key_invoke_completion = '<C-Space>'

nnoremap <F11> :YcmForceCompileAndDiagnostics <CR>

A: As @FDinoff pointed out, every .ycm_extra_conf.py needs to be tailored for its own project.
To give you an example that might help you, here is mine : .ycm_extra_conf.py
Because I put all my libs inside a ./lib directory at the root of my projects, I've made a little script to automatically scan the directories and add the libraries as flags.
You can read it line 57:
  for path, dirs, files in os.walk(libDir):
    for d in dirs:
      flag = '-I' + os.path.join(path, d)
      flags.append(flag)

libDir is defined line 4
And here is the original project: Moti
EDIT - 12/02/2014 -
I don't see the .ycm_extra_conf.py in your tree output. This file should be at the root of your project.
Also you can try using absolute path for your flags.
The output of :YcmDebugInfo should look like that : http://pastebin.com/WARSUiML
You can check my .vimrc where I configure YCM : Link to YCM Conf. Try using mine without yours to see what happens.

A: For me YouCompleteMe works great in conjunction with JUCE without the false errors you're describing.
I have copied the .ycm_extra_conf.py from my current project to the opensource predecessor for you where YCM also works as expected.
Get it from https://github.com/klangfreund/LUFSMeter . Either YCM works as expected (Somthing is wrong with your project) or it doesn't (Something is wrong with you installation of YCM).

A: I installed the XCode update to 6.11, and it now seems to be working as expected.
Thanks to @ladislas and @Samuel Gaehwiler for the help and pointers.


text:
Q: How to Check in and Check Out Power Builder Code How to Check in and Check Out Power Builder Code.
I generally see they will do by exporting and checking in the code. But i am getting some dependency error when i am trying to import objects one by one.
Could someone please help me how to do this entire process of checking in and out of power builder code.
Do we have to use any other third party software for this purpose?

A: In your comments above you say you're using PB 11.5 and SVN.
I'm the author of the Agent SVN plug-in and it integrates PowerBuilder with Subversion.
It does this using the MS-SCCI interface, meaning you integrate with SVN using the source control menus found inside PowerBuilder itself.
Because it uses MS-SCCI that means PowerBuilder itself will decide what needs to be done when-ever objects are checked in or out.
NOTE: Agent SVN is shareware.

A: When adding objects to source control you need to bring in the base classes (ancestors) first.  Once these are successfully brought into the .pbl/target you can then add any descendant classes.


text:
Q: How to retrieve each item in a ListBox C# I am new to C#, although I did take a quarter of Java last year. I have an assignment due tomorrow, so here is my question. I made a sample little program just so I can hopefully get what I'm looking for. I am wondering, how the heck do I look at the listBox and say, for example, if the item soccer is selected, do one thing, but if anything else is selected, do another thing? I will upload a piece of code that doesn't do what its supposed to do, and you all can call me stupid, and then give me the answer.
    private void submitButton_Click(object sender, EventArgs e)
    {
        string best;
        best = namesListBox.SelectedItem.ToString();

        if ((string)namesListBox.SelectedItem == "Soccer")
        {
            MessageBox.Show("Fried chicken, don't let that bird die in vain.");
        }
        else
        {
            MessageBox.Show("Long long ago, in the land of the Hobbit...");
        }
    }

    private void exitButton_Click(object sender, EventArgs e)
    {
        Close();
    }
}

}
Every time this code runs, I always get Long, long ago.... That is not what I want to see. Any help would be appreciated, I'm about to give up on this program. This is not the actual program, that one is alot more complicated, I just made this one to demonstrate my question... Thanks in advance

A: I am assuming you are using WPF, and you are using ListBox like this :
<ListBox x:Name="lstGames">
        <ListBoxItem Content="Soccor"/>
        <ListBoxItem Content="Cricket"/>
    </ListBox>

Replace this best = namesListBox.SelectedItem.ToString(); with
best = ((ListBoxItem)namesListBox.SelectedItem).Content.ToString();

and accordingly others too.
Because if you are using itemssource property of ListBox and binding say list of only strings, then your present code will work for you surely, if you have checked UpperCase/LowerCase.
If you are using some item like a Game object with multiple properties then your code won't work and more can be said if you tell how you are binding your listbox to a collection object.

A: Yuriy,
It looks like you are casing the selected item to a string. I have a feeling this may be the problem.
What exactly are you using the string 'best' for? you defined it, but it is not used in your example.
Is this what you are looking for? Try using the ToString() method, and trim it so that whitespace will not throw your code off:
string selectedItem = namesListBox.SelectedItem.ToString().Trim();

if (selectedItem == "Soccer")
    MessageBox.Show("Soccer is selected.");
else
    MessageBox.Show("NOT SELECTED");

Maybe it is a casing error? If you don't want to worry about uppercase or lowercase, try appending .ToLower() to your string:
string selectedItem = namesListBox.SelectedItem.ToString().Trim().ToLower();

if (selectedItem == "Soccer".ToLower())
    // Handle code accordingly.
else
    // Handle accordingly.

You can also search your ListBox for a string and find out where it is. Then determine whether the user has selected that particular item:
int selIndex = namesListBox.FindString("Soccer");

This will return a zero-based index of the location of the first item containing the word "Soccer" in it.
Now handle the selected index:
if (namesListBox.SelectedIndex != -1 &&
    namesListBox.SelectedIndex == selIndex)
    MessageBox.Show("First item containing \"Soccer\" is selected.");
else
    MessageBox.Show("First item containing \"Soccer\" is not selected.");

It is also quite possible that you are using a ListView object rather than an actual ListBox. If this is the case, you will have to take a different approach. This example still uses your ListBox name:
// This assumes that you cannot select multiple items, and that you
// only have one column in your ListView.
string selectedItem = namesListBox.SelectedItems[0].SubItems[0].Text;

if (selectedItem.Trim() == "Soccer") // Continue as before...

Does this work with your project?
EDIT:
Wait. Are you trying to change the selected item to "best" before evaluating?
If so, do it like this:
int selIndex = namesListBox.SelectedIndex;

namesListBox.Items.RemoveAt(selIndex);
namesListBox.Items.Insert(selIndex, "best");

EDIT:
Be sure to include code that handles no selection:
// Will not execute block of code if nothing is selected.
if (namesListBox.SelectedIndex == -1)
{
    MessageBox.Show("No item is selected.");
    return;
}

A: The only thing I was looking for was how to write an if statement and this part of the code you wrote worked perfectly. I guess I had whitespace throwing it off, or I was just overthinking it. But anyhow, my issue is resolved. Thank you very much.
string selectedItem = namesListBox.SelectedItem.ToString().Trim();

if (selectedItem == "Soccer")
    MessageBox.Show("Soccer is selected.");
else
    MessageBox.Show("NOT SELECTED");


text:
Q: IE 7/8 not appending elements generated in an .each loop In my markup I have this empty
 to hold my thumbnails: ...

... and I'm using jQuery to loop through a bunch of .slide divs and generate the thumbnails: ...
// GENERATE THE SLIDE SELECTORS [THUMBNAILS]
$('.slides .slide').each(function() {
    var ID = $(this).attr('id');
    var imgTag  = $(this).find('img').parent().html().split('meta"  -->')[1];
    var listItem = '
'+imgTag+'
';
    //$('.slideSelectors').html(listItem); // loads only last list item, since .html() replaces all previous LIs
    //$('.slideSelectors').add(listItem); // NG in IE7, IE8
    $('.slideSelectors').append(listItem); // NG in IE7, IE8
});

... and here's the trigger business:
$('.slideSelectors').on('click', 'li a', function(){
    var selectorIx = parseInt($(this).closest('li').index(), 10);
    newSlide(selectorIx);
});

... all of which works a charm in FF, Safari.
IE7/8 however, can't seem to vibe with .append(): the thumbnail images are rendered (unclickable) but there's no
 tags and no anchor tags, making the thumbnails useless as selectors. I've alerted both the imgTag and listItem variables, which look right (though the image tag is improperly closed, despite being correct in my .slide divs). Same results using .prepend(), and .html() is no good (as I've seen suggested in related questions) because I'm in an .each() loop and it renders only the last thumbnail. (I've also read elsewhere on SO that this could be related to bad HTML but my code is valid)
This seems to be a known bug but I've yet to see a fix. Other than adding another trigger selector, I'm out of ideas. Can anyone point me in the direction of a solution?
Many thanks in advance,
Shecky

A: In your code
var listItem = '
'+imgTag+'
';

should be
var listItem = '
'+imgTag+'
';

You missed the closing  tag, other browsers are smarter than IE so it's working but IE is not so smart to do that so your thumbnail images are not clickable in IE.


text:
Q: Complexity of inbuilt function used in Python3 to compute pow(a,b) Will the function that uses iteration and the fact that
an = (axa)n/2 when n is even & [(axa)(n-1)/2]xa when n is odd
yield better results than the inbuilt function in python 3.

A: No, you will not be able to out perform Python built-in operations. The reason is fairly simple, those built-in operations run C code, in the case of CPython. You will not beat C code by writing Python code.
If we think about your case specifically, your solution would require to instantiate multiple integer or float objects, do comparions, multiply, all that in Python! This is something the built-in power operator does not do, as Python has an instruction that computes the power in C and only instantiate one object, which is the value that you want.
We can see that by using dis to see python bytecode.
>>> import dis
>>> dis.dis('a**b')
1         0 LOAD_NAME                0 (a)
          2 LOAD_NAME                1 (b)
          4 BINARY_POWER
          6 RETURN_VALUE

>>> dis.dis("""
r = 1
while b > 1:
    if b % 2:
        b = (b - 1) / 2
        a *= a
        r *= a
    else:
        b /= 2
        a *= a
r *= a""")

2         0 LOAD_CONST               0 (1)
          2 STORE_NAME               0 (r)

3         4 SETUP_LOOP              66 (to 72)
          6 LOAD_NAME                1 (b)
          8 LOAD_CONST               0 (1)
         10 COMPARE_OP               4 (>)
         12 POP_JUMP_IF_FALSE       70

4        14 LOAD_NAME                1 (b)
         16 LOAD_CONST               1 (2)
         18 BINARY_MODULO
         20 POP_JUMP_IF_FALSE       52

5        22 LOAD_NAME                1 (b)
         24 LOAD_CONST               0 (1)
         26 BINARY_SUBTRACT
         28 LOAD_CONST               1 (2)
         30 BINARY_TRUE_DIVIDE
         32 STORE_NAME               1 (b)

6        34 LOAD_NAME                2 (a)
         36 LOAD_NAME                2 (a)
         38 INPLACE_MULTIPLY
         40 STORE_NAME               2 (a)

7          42 LOAD_NAME                0 (r)
         44 LOAD_NAME                2 (a)
         46 INPLACE_MULTIPLY
         48 STORE_NAME               0 (r)
         50 JUMP_ABSOLUTE            6

9        52 LOAD_NAME                1 (b)
         54 LOAD_CONST               1 (2)
         56 INPLACE_TRUE_DIVIDE
         58 STORE_NAME               1 (b)

10       60 LOAD_NAME                2 (a)
         62 LOAD_NAME                2 (a)
         64 INPLACE_MULTIPLY
         66 STORE_NAME               2 (a)
         68 JUMP_ABSOLUTE            6
         70 POP_BLOCK

 11      72 LOAD_NAME                0 (r)
         74 LOAD_NAME                2 (a)
         76 INPLACE_MULTIPLY
         78 STORE_NAME               0 (r)
         80 LOAD_CONST               2 (None)
         82 RETURN_VALUE

I'll let you guess how disproportionately more efficient the built-in is.


text:
Q: Problem with finding the degree between two clock hands question (Python) Hi I seem to have a problem with my answer in returning the smallest angle between the big hand and small hand of a clock. The code I have is written below
def time_question(n):

    h = int(n[:2])
    m = int(n[2:])

    hours = (360/12)*h+((m/60)*(360/60))
    minutes = (360/60)*m

    diff = abs(hours-minutes)

    print(min(diff,360-diff)) time_question('1201')

Jupyter Notebook and Pycharm returns the value (5.8999999997)
while repl.it returns (5.5). I had an interview with this question and the interviewer had 5.5 as an answer as well. I was just wondering why my results are different? Any help would be greatly appreciated.


text:
Q: Should I have private members referencing the views of my activity? I have a simple activity consisting in 4 views defined in an xml file. For the sake of performance, is it better to access my views by their id or to have member referencing them in my activity ? Is it notably different ?
Thanks

A: You should call findViewById() just once for each view that you need to reference in your app. Make this call in onCreate() and save the returned view instances in private member variables. Then you can reference them directly later.
findViewById() is expensive, especially if you have a lot of views.
This is pretty much standard Android practice.


text:
Q: How to create custom skill in azure-search? how to integrate the custom skill(Azure function) with azure search, is it mandatory to create the index, indexer and data Source. If it is so, then how to create it.
After going through Microsoft doc i did not get much help. it only create the custom skill for Bing search.

A: I'd recommend you go through this Azure Cognitive Search knowledge mining workshop, modules 0 to 4 (or more if you are interested!). It will show you how all the pieces work together, and walk you through an example where you will create everything including a custom skill (also in an Azure Function) that's integrated with the ingestion flow.
If you're looking for something more specific on how to integrate a custom skill inside a skillset, as part of the enrichment pipeline, this document should help as well.


text:
Q: Triggering click event from URL I am building a FAQ page, and am needing help with the second part of my jquery function.
When you click on a question, it shows the answer.
What I am also wanting to do is when i link to an anchor, to also show the answer to the question.
Script:
jQuery(function($) {
    $('.faq-title').click(function () {
        $(this).siblings('.faq-content').slideToggle('fast');
    })
var hash = window.location.hash;
    $('.faq-title').find('a[href*='+ hash + ']').closest('h4').trigger('click');
})

Html:

1. Question

Answer

2. Question

Answer

3. Question

Answer

A: Change your javascript:
.find(hash)

Check fiddle.

A: I added CSS to clean up the HTML. Basically, just check whether there is a hash (e.g., #q3), and, if there is, trigger the event handler attached to it. In this case, click #q3.
fiddle
HTML:

        1. Question

Answer

        2. Question

Answer

        3. Question

Answer

CSS:
h4.faq-title {
    cursor: points;
    padding: 0 0 6px 0;
}
span {
    text-decoration: underline;
}
p {
    color: #808080;
}
div.faq-content {
    display: none;
}

JavaScript:
jQuery(function ($) {
    var hash = window.location.hash;
    if (hash) {
        $(hash).closest("h4").trigger("click");
    }
    $('.faq-title').click(function () {
        $(this).siblings('.faq-content').slideToggle('fast');
    })
})


text:
Q: Need a working example for apache POI createDateConstraint not using formulas the poi.apache.org website gives the following definition
public static DVConstraint createDateConstraint(int comparisonOperator,
                                java.lang.String expr1,
                                java.lang.String expr2,
                                java.lang.String dateFormat)
I want an example where expr1 and expr2 are formatted date values.

A: This code worked for me for setting cell style as date and adding date validation on it:
Cell cel= rowx.createCell(i);
cel.setCellStyle(style);
 XSSFCreationHelper createHelper =
 workbook.getCreationHelper();
 short dateFormat =
 createHelper.createDataFormat().getFormat("MM/dd/yyyy");
 style.setDataFormat(dateFormat);

 DataValidationHelper dvHelper =
 sheet.getDataValidationHelper();
 DataValidationConstraint dvConstraint =
      dvHelper.createDateConstraint(

 org.apache.poi.ss.usermodel.
 DataValidationConstraint.OperatorType.BETWEEN,
            "Date(1900, 1, 1)",
            "Date(9999, 12, 31)",
            "MM/dd/yyyy");
 CellRangeAddressList addressList = new CellRangeAddressList(
            2, pendingRowCount, columnNumber, columnNumber);
 DataValidation validation =
 dvHelper.createValidation(dvConstraint, addressList);
 if (validation instanceof XSSFDataValidation) {
   validation.setSuppressDropDownArrow(true);
   validation.setShowErrorBox(true);
} else {
  validation.setSuppressDropDownArrow(false);
}
sheet.addValidationData(validation);

A: The key I found was using the Date(Year, Month, Day) function. I also needed my code to work for an entire column except for the header so the cell range is from 1 to the last row excel has for one sheet. I am unsure why but just a date on its own didn't seem to work because the formula is automatically converted to have a '=' sign in front which confuses excel I think.
Also an error style and message are always a good idea to give people an idea on what they are doing wrong.
DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = dataValidationHelper.createDateConstraint(OperatorType.BETWEEN,
            "Date(1990, 1, 1)", "Date(9999, 12, 31)", "mm/dd/yyyy");
CellRangeAddressList addressList = new CellRangeAddressList(1, 1048575, 0, 0);
DataValidation validation = dataValidationHelper.createValidation(constraint, addressList);
validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
validation.createErrorBox("Invalid date", "Please Insert Valid Date");
validation.setSuppressDropDownArrow(dropDownArrow);
sheet.addValidationData(validation);

A: There is an example in the cunningly named TestDataValidation junit test that ships with Apache POI, which shows using createDateConstraint:
DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = dataValidationHelper.createDateConstraint(OperatorType.EQUAL,
            "2014/10/25", null, null);
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
DataValidation validation = dataValidationHelper.createValidation(constraint, addressList);
sheet.addValidationData(validation);

That includes setting a date on the constraint, which shows the format needed

A: Even if the question is for JAVA, some C# developers like me coming to this page after searching in Google, hence, posting the C# version of the answer below.
private void AddDateTypeValidation(IWorkbook workbook, ISheet sheet, int[] regions)
    {
        int _startRow = 1, _endRow = Int16.MaxValue, // Start from first row & continue upto end of Excel.
            _startColumn = regions[0], _endColumn = regions[1]; // start column, end column

        XSSFDataValidation dataValidation;
        XSSFDataValidationConstraint dvConstraint;
        XSSFDataValidationHelper validationHelper = new XSSFDataValidationHelper((XSSFSheet)sheet);

        XSSFCellStyle dateCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
        dateCellStyle.SetDataFormat(HSSFDataFormat.GetBuiltinFormat("m/d/yy"));

        CellRangeAddressList _regions = new CellRangeAddressList(_startRow, _endRow, _startColumn, _endColumn);
        dvConstraint = (XSSFDataValidationConstraint)validationHelper.CreateDateConstraint(
                                                    OperatorType.BETWEEN, "Date(2000, 1, 1)", "Date(3000, 12, 31)", "m/d/yy");
        dataValidation = (XSSFDataValidation)validationHelper.CreateValidation(dvConstraint, _regions);

        dataValidation.ShowErrorBox = true;
        dataValidation.SuppressDropDownArrow = true;
        dataValidation.ErrorStyle = 0;
        dataValidation.CreateErrorBox("Invalid Input Provided", "Please enter a valid date in format 'm/d/yy'.");
        dataValidation.ShowErrorBox = true;
        dataValidation.CreatePromptBox("Date Validation", "Enter a Valid Date in format 'm/d/yy'.");
        dataValidation.ShowPromptBox = true;
        sheet.AddValidationData(dataValidation);
        sheet.SetDefaultColumnStyle(_startColumn, dateCellStyle);

        sheet.AddValidationData(dataValidation);
    }

A: I need a BETWEEN constraint and I could not find any working solution. Finally I found out that it is relatively simple: you should provide expr1 (from) and expr2 (to) using the format defined in the fourth parameter dateFormat:
dataValidationHelper.createDateConstraint(OperatorType.BETWEEN,
  "1900-01-01", "2100-10-10", "yyyy-MM-dd");


text:
Q: how to download all media files into my computer How do I "download" all my photos from my media library to my local computer?
I can do this one at a time, but is there a way to grab them all at one time? Sort of like a "download all" process.

A: Your best way of doing that would be downloading the wp-content/uploads directory, by ftp access.

A: i found this plugin:

downML - Download Media Library.
Helps admins to backup the media files available in the media library of the wordpress site.

it doesn't provide any options, just spits out a zip file for download. no ftp needed, works in the dashboard.

A: for anyone else who is interested:
find yourself a php script that creates a zip from a list of files provided.
after that, use the script provided on this site: Get All Images in Media Gallery?, to create the list for the archiver script.
i hope this helps, at least this is the way i did it.

A: Instead of ftp go to your cpanel and login. Open File Manager > Public HTML > wp_content > uploads....there will be folders with dates. Open them. You'll see your images. You can download them each or all at one time directly to your computer. Voila! I just did it myself. Hope that helps. By the way, ftp id faster. I use filezilla but it was having some inconvenient glitch at the moment so i did this 2nd option!


text:
Q: Terraform: Invalid value for string parameter - Variable Validation Syntax I have the following terraform code for creating an Azure resource group using a map(object). I was attempting to also put in some validation conditions to the variable, but it errors out saying
│ Error: Invalid function argument
│
│   on variables.tf line 11, in variable "resource_groups":
│   11:     condition     = length(var.resource_groups["name"]) >= 1 && length(var.resource_groups["name"]) <= 90 && length(regexall("[^\\w()-.]", var.resource_groups["name"])) == 0
│     ├────────────────
│     │ var.resource_groups["name"] is a object, known only after apply
│
│ Invalid value for "string" parameter: string required.
╵
╷
│ Error: Invalid function argument
│
│   on variables.tf line 16, in variable "resource_groups":
│   16:     condition     = substr(var.resource_groups["name"], 0, 3) == "rg-"
│     ├────────────────
│     │ var.resource_groups["name"] is a object, known only after apply
│
│ Invalid value for "str" parameter: string required.

CODE
variable "resource_groups" {
  description = "A map of Resource groups and their properties."
  type = map(object({
    name     = string
    location = string
    tags     = map(string)
  }))

  validation {
    condition     = length(var.resource_groups["name"]) >= 1 && length(var.resource_groups["name"]) <= 90 && length(regexall("[^\\w()-.]", var.resource_groups["name"])) == 0
    error_message = "The resource group name must be betweem 1 and 90 characters, using alphanumerics, underscores, parentheses, hyphens, periods."
  }

  validation {
    condition     = substr(var.resource_groups["name"], 0, 3) == "rg-"
    error_message = "The resource group name must start with \rg-\"."
  }
}

Can we not use validation when using map(object)?

A: A map(object) is enumerable/iterable and contains an arbitrary key, so you must likewise validate on the iterated values, and ignore the unknown key:
validation {
  condition     = alltrue([for rg in var.resource_groups : length(rg.name) >= 1 && length(rg.name) <= 90 && length(regexall("[^\\w()-.]", rg.name)) == 0])
  error_message = "The resource group name must be betweem 1 and 90 characters, using alphanumerics, underscores, parentheses, hyphens, periods."
}

validation {
  condition     = alltrue([for rg in var.resource_groups : substr(rg.name, 0, 3) == "rg-"])
  error_message = "The resource group name must start with \rg-\"."
}


text:
Q: Sound effect on Android live wallpaper Can Android live wallpaper create sound effects based on the touch of users?
I don't see alot of live wallpaper with sound effects out on the market. Is there a reason for it? For e.g, battery drain or other programming issues?

A: You can use a MediaPlayer in your WallpaperServiceClass.
You need to put the .mp3 or whatever sound resource you
want to use in your /res/raw folder.
public class MyWallpaperService extends WallpaperService {

    private MediaPlayer mediaPlayer;

    @Override
    public void onCreate() {
        super.onCreate();

     mediaPlayer =
         MediaPlayer.create(getApplicationContext(),
             R.raw.your_sound);
    }

// and in your WallpaperEngine SubClass start the sound on touch :
    class MyWallpaperEngine extends Engine {

        @Override
        public void onCreate(SurfaceHolder surfaceHolder) {
            super.onCreate(surfaceHolder);

        // touch is not activated on default so do it here :
            setTouchEventsEnabled(true);
        }

        @Override
        public void onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                mediaPlayer.start();

        }
    }
}

To stop the sound use :
mediaPlayer.pause()

or when you're done kill the mediaPlayer with :
mediaPlayer.release();

Shouldn't drain unnecessary resources then since its only reacting on touch.


text:
Q: libgfortran not found when installing scipy using enthought canopy I am trying to install scipy using enpkg in Enthought Canopy but I am getting this error:
(canopy_env) server 17:10:33 ~ $ enpkg scipy
prefix: /home/user/apps/canopy_env
Traceback (most recent call last):
  File "/home/user/apps/canopy_env/bin/enpkg", line 10, in <module>
    sys.exit(main())
  File "/home/user/apps/Canopy/appdata/canopy-1.1.0.1371.rh5-x86_64/lib/python2.7/site-packages/enstaller/main.py", line 746, in main
    install_req(enpkg, req, args)             # install (default)
  File "/home/user/apps/Canopy/appdata/canopy-1.1.0.1371.rh5-x86_64/lib/python2.7/site-packages/enstaller/main.py", line 395, in install_req
    _perform_install()
  File "/home/user/apps/Canopy/appdata/canopy-1.1.0.1371.rh5-x86_64/lib/python2.7/site-packages/enstaller/main.py", line 311, in _perform_install
    enpkg.execute(actions)
  File "/home/user/apps/Canopy/appdata/canopy-1.1.0.1371.rh5-x86_64/lib/python2.7/site-packages/enstaller/enpkg.py", line 279, in execute
    self.fetch(egg, force=int(opcode[-1]))
  File "/home/user/apps/Canopy/appdata/canopy-1.1.0.1371.rh5-x86_64/lib/python2.7/site-packages/enstaller/enpkg.py", line 455, in fetch
    f.fetch_egg(egg, force, self._execution_aborted)
  File "/home/user/apps/Canopy/appdata/canopy-1.1.0.1371.rh5-x86_64/lib/python2.7/site-packages/enstaller/fetch.py", line 147, in fetch_egg
    self.fetch(egg, execution_aborted)
  File "/home/user/apps/Canopy/appdata/canopy-1.1.0.1371.rh5-x86_64/lib/python2.7/site-packages/enstaller/fetch.py", line 30, in fetch
    fi, info = self.remote.get(key)
  File "/home/user/apps/Canopy/appdata/canopy-1.1.0.1371.rh5-x86_64/lib/python2.7/site-packages/enstaller/store/indexed.py", line 47, in get
    return self.get_data(key), self.get_metadata(key)
  File "/home/user/apps/Canopy/appdata/canopy-1.1.0.1371.rh5-x86_64/lib/python2.7/site-packages/enstaller/store/indexed.py", line 136, in get_data
    raise KeyError("%s: %s" % (e, url))
KeyError: u'HTTP Error 404: NOT FOUND: https://api.enthought.com/eggs/rh5-64/libgfortran-3.0.0-1.egg'

I am using Canopy Express and this package is provided (see this)..
I have tried to install it from pip but, since I have not administration permissions, I am unable to install it..
Edit: the same happens with Pygments package when installing ipython:
appinst-2.1.2-1.egg                                                [fetching]
    55 KB [.................................................................]
MarkupSafe-0.18-2.egg                                              [fetching]
    26 KB [.................................................................]
...
KeyError: u'HTTP Error 404: NOT FOUND: https://api.enthought.com/eggs/rh5-64/Pygments-1.6.0-1.egg'

Thanks

A: a few of our free packages had been flagged as "commercial" by mistake. We fixed the problem and you should be able to install them now.
Sorry about the trouble!


text:
Q: How make responsive images in Ckeditor using Responsive Filemananger I'm using Ckeditor and Responsive filemanager. I want that uploaded images were responsive. But when I upload an image, and see it on the article page, it isn't responsive. Even the image goes beyond div. How can I make it responsive?

A: I find the solution. When adding image to ckeditor just need in ckeditor property window. Instead of pixels use percent.
Screenshot


text:
Q: SQLite insert is adding the same entry multiple times I'm not sure why but each item in my database is duplicated about 30 times even though i only insert each item once. I thought perhaps it might be as a result of a walkdir() method that inserts into the database for each file with a .mp3 extension within a specified root folder or perhaps as a result of my naivety regarding ListView recycling.
public class SQLHelper extends SQLiteOpenHelper{
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "MusicDatabase.db";
    private static final String SQL_CREATE_TABLE =
            "CREATE TABLE "+
                    FeedEntry.TABLE_NAME+" ("+
                    FeedEntry._ID+" INTEGER PRIMARY KEY,"+
                    FeedEntry.KEY_FILENAME+" TEXT UNIQUE,"+
                    FeedEntry.KEY_SONGNAME+" TEXT )";
    private static final String SQL_DELETE_TABLE = "DROP TABLE IF EXISTS "+ SQLContract.FeedEntry.TABLE_NAME;

    public SQLHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_TABLE);
    }
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_DELETE_TABLE);
        onCreate(db);
    }
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }/*
    public List<Song> getAllSongs(){
        List<Song> songs = new LinkedList<Song>();
        String query = "SELECT * FROM "+FeedEntry.TABLE_NAME;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(query,null);
        Song song = null;
        if(cursor.moveToFirst()){
            do {
                song = new Song();
                song.setId(Integer.parseInt(cursor.getString(0)));
                song.setFileName(cursor.getString(1));
                song.setSongName(cursor.getString(2));
                songs.add(song);
            }while(cursor.moveToNext());
        }
        return songs;
    }*/
    public void addSong(File file){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(FeedEntry.KEY_FILENAME, file.getPath());
        values.put(FeedEntry.KEY_SONGNAME, file.getName());
        db.insert(FeedEntry.TABLE_NAME,null,values);
    }
    public Cursor read(String sort, String direction){
        SQLiteDatabase db = this.getReadableDatabase();
        String[] projection = {
            FeedEntry._ID,
            FeedEntry.KEY_FILENAME,
            FeedEntry.KEY_SONGNAME,
        };
        String sortOrder = sort+direction;
        Cursor c = db.query(
                FeedEntry.TABLE_NAME,
                projection,null,null,null,null,
                sortOrder
        );
        return c;
    }
}

A: I think the problem doesn't happen on your database code.
I feel, your problem is quite similar to How ListView's recycling mechanism works
Dealing with ListView correctly requires quite amount of work.

A: After much trial and failure i discovered that the error in my code lies here:
public static final String DATABASE_NAME = "MusicDatabase.db";

Should be:
public static final String DATABASE_NAME = "MusicDatabase";

I have no idea why i thought the database extension was necessary.


text:
Q: .htaccess conflict in Wordpress directory I have a htaccess file in the root of my public files on my web server:
Header set Content-Security-Policy: upgrade-insecure-requests

DirectoryIndex index.html index.php parking-page.html

RewriteEngine on
# Force www
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Force SSL
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,NE]

Options -Indexes

ErrorDocument 404 https://%{HTTP_HOST}/index.php

# for JWT auth
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
# end for JWT auth

I installed a Wordpress blog on /blog , and Wordpress creates a .htaccess file in that folder:
# BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>

# END WordPress

I notice that, when I visit http://example.com/blog , it redirects me to https://www.example.com/index.php , while it should go to https://www.example.com/blog .
Other pages, for example http://example.com/contact-us, successfully redirects to https://www.example.com/contact-us
Update:

*

*https://example.com/blog works fine (redirects to https://www.example.com/blog).

*http://www.example.com/blog is broken (redirects to https://www.example.com/index.php).

A: You might have an error in your Rewrite Rule for the redirect from non-www to www. I don't know where you got that code but I've never seen it attempted like that before.
You can replace the separate rules for forcing www and SSL with just the one, as follows:
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=302]

Important: Note the use of 302 redirect - you should only use a temporary redirect until you have confirmed it works. Only when you know it is working should you change it to 301.
As you have used a 301 redirect in your current rule, it will be cached and might take a while to clear.
Note that for WP installed in a subfolder, you need to add this Rewrite rule in the .htaccess file in the subfolder.

Note that your Rewrite Rules are not being triggered... it only looks like it works because you have https and www as the site URL in your WP Settings.
Therefore it's possible that the reason http://example.com/blog is going to https://www.example.com/index.php is not because of the rewrites but because the following line in your .htaccess is getting triggered:
ErrorDocument 404 https://%{HTTP_HOST}/index.php

If making the changes above doesn't work, you could look into that as a possible cause.


text:
Q: How to detect any keyboard button pressed in Ada language I am a beginner in Ada programming. I am trying to make a "2048" game using Ada. I did "2048" in C++, and I used "kbhit()" to detect that is there any keyboard button pressed. I want to know that is there any similar function available like "kbhit()" in Ada, or how to write a function to detect is there any keyboard button pressed, or should I just use the function by interface in C++.

A: Yes, you can use any of several overloaded versions of Ada.Text_IO.Get_Immediate. The declarations are (copied from the 2012 edition of the Ada standard):
procedure Get_Immediate(File : in File_Type;
                        Item : out Character);
procedure Get_Immediate(Item : out Character);

Reads the next character, either control or graphic, from the
  specified File or the default input file. Mode_Error is propagated if
  the mode of the file is not In_File. End_Error is propagated if at the
  end of the file. The current column, line and page numbers for the
  file are not affected.

procedure Get_Immediate(File : in File_Type;
                        Item : out Character;
                        Available : out Boolean);
procedure Get_Immediate(Item : out Character;
                        Available : out Boolean);

If a character, either control or graphic, is available from the
  specified File or the default input file, then the character is read;
  Available is True and Item contains the value of this character. If a
  character is not available, then Available is False and the value of
  Item is not specified. Mode_Error is propagated if the mode of the
  file is not In_File. End_Error is propagated if at the end of the
  file. The current column, line and page numbers for the file are not
  affected.


text:
Q: SQL - How to multiple join I have 4 tables: table1, table2, table3, table4. table1 contains id values related to all other tables (2,3,4) and I would like to connect all of them to have all data in one set, I think it's simple relation.
I tried this, but I don't know why it doesn't work:
SELECT * FROM 'table1'
JOIN 'table2' ON 'table1.id_forT2'='table2.id'
JOIN 'table3' ON 'table1.id_forT3'='table3.id'
JOIN 'table4' ON 'table1.id_forT4'='table4.id'
WHERE 'table1.id' = 30

When I left only one join it works fine, with 2 or 3 joins it returns an error. How to do that? Thanks in advance

A: I think it's just that your ticks aren't in the right place.   And is this MySQL?  Because then you want back-ticks instead of single quotes.
SELECT * FROM `table1`
JOIN `table2` ON `table1`.id_forT2=`table2`.id
JOIN `table3` ON `table1`.id_forT3=`table3`.id
JOIN `table4` ON `table1`.id_forT4=`table4`.id
WHERE `table1`.id = 30

A: It might be because of two reassons:

*

*Quotes/Backtips: Maybe you aren't using this properly

*Use LEFT JOIN instead of JOIN: Perhaps one table has no data for the relation

You should specify if you're using mySQL, postgreSQL or other.


text:
Q: Question about reading properties of a class at run time in c# (.NET 2.0)? Let's say I have a class that has 3 properties. I don't know which property I want to read until runtime. Is there a way to do this without a switch/if-else statement?
If a DataTable is treated as a class, then the columns can be treated dynamically which would work, but I'm not able to change my class into a DataTable (long story).
For a DataTable, the code would be:
string columnName = "Age";
int age = dataRow[columnName];

How is this possible in a class?
string propertyName = "Baka";
int age = item.getProperty(propertyName)  // ???

A: The easiest way to do this kind of runtime evaluation is with Reflection.
Depending on the version of .NET you're using, you could add methods to your class or use extension methods.

A: EDIT:  I just read your comment about not using a switch, but I'll keep this here anyway, just in case...  skip to my second answer.
Maybe something like this:
public enum Property { Name, Age, DateOfBirth};

public T GetProperty<T>(Property property)
{
    switch (property)
    {
       case Property.Name:
          return this.Name;
       // etc.
    }
}

I'm not too strong in Genetics, so maybe someone can help me with the return cast.

Alternatively, you could add a field to your class of type DataRow and use an indexer to access it:
public class MyClass
{
   DataTable myRow = null;
   MyClass(DataRow row)
   {
      myRow = row;
   }

   public object this[string name]
   {
      get
      {
         return this.myRow[name];
      }
      set
      {
         this.myRow[name] = value;
      }
   }
}

Usage:
MyClass c = new MyClass(table.Rows[0]);
string name = c["Name"].ToString();

A: Answered a similar question earlier.  Here's a code sample, and link to the other question.
Hiding Public Functions
You're going to be most interested in the GetValue method of the System.Reflection.PropertyInfo class.
C# Code Sample
public bool SetProperty(object obj, string PropertyName, object val)
{
    object property_value = null;
    System.Reflection.PropertyInfo[] properties_info = obj.GetType.GetProperties;
    System.Reflection.PropertyInfo property_info = default(System.Reflection.PropertyInfo);

    foreach (System.Reflection.PropertyInfo prop in properties_info) {
        if (prop.Name == PropertyName) property_info = prop;
    }

    if (property_info != null) {
        try {
            property_info.SetValue(obj, val, null);
            return true;
        }
        catch (Exception ex) {
            return false;
        }
    }
    else {
        return false;
    }
}

public object GetProperty(object obj, string PropertyName)
{
    object property_value = null;
    System.Reflection.PropertyInfo[] properties_info = obj.GetType.GetProperties;
    System.Reflection.PropertyInfo property_info = default(System.Reflection.PropertyInfo);

    foreach (System.Reflection.PropertyInfo prop in properties_info) {
        if (prop.Name == PropertyName) property_info = prop;
    }

    if (property_info != null) {
        try {
            property_value = property_info.GetValue(obj, null);
            return property_value;
        }
        catch (Exception ex) {
            return null;
        }
    }
    else {
        return null;
    }
}

VB Code Sample
Public Function SetProperty(ByVal obj As Object, ByVal PropertyName As String, ByVal val As Object) As Boolean
    Dim property_value As Object
    Dim properties_info As System.Reflection.PropertyInfo() = obj.GetType.GetProperties
    Dim property_info As System.Reflection.PropertyInfo

    For Each prop As System.Reflection.PropertyInfo In properties_info
        If prop.Name = PropertyName Then property_info = prop
    Next

    If property_info IsNot Nothing Then
        Try
            property_info.SetValue(obj, val, Nothing)
            Return True
        Catch ex As Exception
            Return False
        End Try
    Else
        Return False
    End If
End Function

Public Function GetProperty(ByVal obj As Object, ByVal PropertyName As String) As Object
    Dim property_value As Object
    Dim properties_info As System.Reflection.PropertyInfo() = obj.GetType.GetProperties
    Dim property_info As System.Reflection.PropertyInfo

    For Each prop As System.Reflection.PropertyInfo In properties_info
        If prop.Name = PropertyName Then property_info = prop
    Next

    If property_info IsNot Nothing Then
        Try
            property_value = property_info.GetValue(obj, Nothing)
            Return property_value
        Catch ex As Exception
            Return Nothing
        End Try
    Else
        Return Nothing
    End If
End Function

A: If you know the type of object you can get all the properties, and then your requested property, using reflection.
MyClass o;

PropertyInfo[] properties = o.GetType().GetProperties(
    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

Each PropertyInfo has a Name which you can match up to your String.

A: item.GetProperties() would return a PropertyInfo[] containing all properties (public only I think)
A PropertyInfo Object has a property Name which is the name of the property, so you can iterate over the array searching for a PropertyInfo object with your search name.

A: string propertyToGet = "SomeProperty";
SomeClass anObject = new SomeClass();

string propertyValue =
    (string)typeof(SomeClass)
    .GetProperty("SomeProperty")
    .GetValue(anObject, null);

A: Example using indexers:
public class MyItem
{
    public object this[string name]
    {
        switch (name)
        {
            case "Name":
                return "Wikipetan";
            case "Age":
                return 8;
            case "DateOfBirth":
                return new DateTime(2001, 01, 15);
            case "Baka":
                return false;
            default:
                throw new ArgumentException();
        }
    }
}

Usage:
MyItem item = ...;
string propertyName = "Age";
int age = (int)item[propertyName];


text:
Q: Process Stream with inner stream with fs2 I have 2 csv files with sorted data:
File 1: numbers sorted (~1GB)
File 2: numbers sorted + extra data (~20GB)
I need to lookup all numbers from file 1 in file 2 and do some processing (numbers in file 2 that are not present in file 1 are skipped).
So far I have:
object MainQueue extends IOApp {

  override def run(args: List[String]): IO[ExitCode] =
    program[IO].compile.drain.as(ExitCode.Success)

  def program[F[_]: Sync: ContextShift](): Stream[F, Unit] =
    for {
      number <- numberStream
      record <- records
                       .through(parser())
                       .through(findRecord(number))
      _ <- Stream.emit(println(s"$number <-> $record"))
    } yield ()

  def findRecord[F[_]](phone: Long): Pipe[F, Long, Long] =
    _.dropWhile(r => {
      println(s"Reading $r")
      r < phone
    }).head //halts the stream

  def numberStream[F[_]](): Stream[F, Long] =
    Stream(100L, 120L)

  //TODO: make stream continue and not halt and restart
  def records[F[_]: Sync: ContextShift](): Stream[F, String] =
    Stream
      .resource(Blocker[F])
      .flatMap { bec =>
        readAll[F](Paths.get("small.csv"), bec, 4096)
      }
      .through(text.utf8Decode)
      .through(text.lines)

  def parser[F[_]](): Pipe[F, String, Long] = ??? //parse

  def writer[F[_]](): Pipe[F, Long, Unit] =
    _.map(v => {
      println(s"Found: $v")
    })

}

Which prints:
Reading 50
Reading 100
100 <-> 100
Reading 50
Reading 100
Reading 120
120 <-> 120

Which means the 2nd stream restarts for each value in File 1, how do I keep the position last read and go from there? Numbers are sorted so no point started over.
I am super new to scala and fs2 so an explanation of what I am misunderstanding would be much appreciated.
Thanks!

A: First of all you need to know, that
    for {
      number <- numberStream
      record <- records
                       .through(parser())
                       .through(findRecord(number))
      _ <- Stream.emit(println(s"$number <-> $record"))
    } yield ()

is just a syntax-suger for
    numberStream()
      .flatMap(number => records
        .through(parser())
        .through(findRecord(number)).map(x => (x, number)))
      .flatMap { case (record, number) => Stream.emit(println(s"$number <-> $record")) }

which means you evaluate an effect, in this case
records
        .through(parser())
        .through(findRecord(number)).map(x => (x, number))

, on each element of numberStream.
To keep the last position of a pointer from File2 you can count consumed bytes, but you would still need to reopen connection to File2 for each number from File1.
Operation which you're trying to achieve is conditional zipping, so you should take a look at methods like fs2.Stream#zip, fs2.Stream#zipAll etc, it would help you to zip these records opening files only once.

Zip-like methods don't do exactly what you're looking for, but it's quite easy to implement requested functionality with fs2.Pull, here is an example:
 def zipToLeft[F[_] : RaiseThrowable, O1, O2](in1: Stream[F, O1], in2: Stream[F, O2])
                             (condition: (O1, O2) => Boolean): Stream[F, (O1, O2)] = {
    def go(s1: Stream[F, O1], s2: Stream[F, O2]): Pull[F, (O1, O2), Unit] =
      s1.pull.uncons1.flatMap {
        case Some((hd1, tl1)) => s2.pull.uncons1.flatMap {
          case Some((hd2, tl2)) => if (condition(hd1, hd2)) Pull.output1((hd1, hd2)) >> go(tl1, tl2)
              else go(s1, tl2)
          case None => Pull.raiseError[F](new RuntimeException)
        }
        case None =>Pull.done
      }

    go(in1, in2).stream
}

And you can use it this way:
    result <- program[IO].compile.toList
    _ <- IO(println(result))
  } yield ExitCode.Success

  def program[F[_] : Sync : ContextShift]() = zipToLeft(numberStream(), records()) { case (v1, v2) => v1 == v2._1 }

  def numberStream[F[_]](): Stream[F, Long] =
    Stream.emits(Vector(1, 3, 6, 7, 9))

  def records[F[_] : Sync : ContextShift](): Stream[F, (Int, String)] =
    Stream.emits(Vector.range(1, 10).map(i => (i, i.toString)))

Output: List((1,(1,1)), (3,(3,3)), (6,(6,6)), (7,(7,7)), (9,(9,9)))


text:
Q: Remove surrounding single quotes from a string in VBA I wrote a simple code below which process string values "words", if the word has a leading single quote (example: 'em ) or a trailing one (example: tryin') or both (example: 'this' ) then it removes them , if there are more than one instance of the mark it gets removed too. but if the quote mark is in the middle leave it alone, examples (America's, aren't, can't)

How do I achieve the same function differently and efficiently? And I don't want to use a recursive procedure to do it.
Sub RemoveSurroundingSingleQuotes()
    Dim arr(), wrd$
    arr = Array("'wrd1'", "''wrd3''")
    For i = 0 To UBound(arr)
        wrd = arr(i)
        Debug.Print "word before: " & wrd
RemoveLeft:
        If Left(wrd, 1) = "'" Then wrd = Mid(wrd, 2)
        'check the left side again
        If Left(wrd, 1) = "'" Then GoTo RemoveLeft:
RemoveRight:
        If Right(wrd, 1) = "'" Then wrd = Mid(wrd, 1, Len(wrd) - 1)
        'check the Right side again
        If Right(wrd, 1) = "'" Then GoTo RemoveRight:
        Debug.Print "word after: " & wrd & vbCr & "--------------"
    Next
End Sub

A: Here's some code that uses While loops to find the start and end positions, so it only does the string reassignment once, after it knows the start and end positions.
Sub RemoveSurroundingSingleQuotes()
    Dim arr() As Variant
    Dim wrd As String
    Dim iStart As Long
    Dim iEnd As Long

    arr = Array("'wrd1'", "''wrd3''")

    For i = LBound(arr) To UBound(arr)
        wrd = arr(i)
        Debug.Print "word before: " & wrd

        iStart = 1
        iEnd = Len(wrd)
        Do While Mid(wrd, iStart, 1) = "'" And iStart < iEnd
          iStart = iStart + 1
        Loop

        Do While Mid(wrd, iEnd, 1) = "'" And iEnd > iStart
          iEnd = iEnd - 1
        Loop

        wrd = Mid(wrd, iStart, iEnd - iStart + 1)
        Debug.Print "word after: " & wrd & vbCr & "--------------"
    Next
End Sub

A: Private Function Dequoted(S As String) As String
If Left(S, 1) = """" And Right(S, 1) = """" Then Dequoted = Mid(S, 2, Len(S) - 2) Else Dequoted = S
End Function


text:
Q: Change datetime-local to DD-MM-YYYY hh:mm in HTML Hi im stucking change value on datetime-local format to DD-MM-YYYY hh:mm
I'm read and trial many similar question on here but still not work
Tried manipulating input or output value from datetime-local or text still same
Here is my goal:
Input Form => Text Value from Input => Copy Text Value Button
It's complete, but I need change date format from text to datetime-local for easy fill
OUTPUT NEED: DD-MM-YYYY hh:mm

  <form name="values" action="" method=POST onsubmit="javascript: return checkValues(this);">

          Start Date
          :
          <input type="datetime-local" name="start_date" onchange=showData()>

          End Date
          :
          <input type="datetime-local" name="end_date" id="dt" onchange=showData();>

          <textarea id="KIP" name="freetext" placeholder="KIP CRM" rows="8" cols="100" /></textarea>

            <button onclick="myFunction()" onmouseout="outFunc()">
      Copy
      </button>
          </button>

enter image description here
Thanks for helping


text:
Q: Left Ellipsis Overflow on IE/Edge

.left-ellipsis {
  text-align: left;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  direction: rtl;
}

.left-ellipsis span {}

/* Media query for IE only. */

@media screen and (-ms-high-contrast: active),
(-ms-high-contrast: none) {
  .left-ellipsis span {}
}
With overflowing content

Expected to see 1 0002 0003 0004 0005 end

    123 456 789 0001 0002 0003 0004 0005 end

Without overflowing content

Expected to see 0002 0003 0004 0005 end without ...

    0002 0003 0004 0005 end

Issue: We want to show an ellipsis on our overflowing text on the left side of the div.
Problem: The solution works well in Chrome and Firefox, but doesn't work correctly in IE or Edge.  The ellipsis is shown on the left side correctly, but the data is chopped from the right, not from the left.

Attempts:

*

*I have tried to add a 'float:right' to the span, which then makes
IE/Edge show the correct data, but the ellipsis goes away entirely.

*We have gotten to this point by scouring SO for the 'direction' solution. It works with good browsers it seems.

Any help is greatly appreciated. This has been quite the challenge.
Edit: Here's a plunker where people can try things:
https://plnkr.co/edit/AWyzZLhnLbt4DStnU5hW?p=preview
Attempting to use the code provided by the article that @ovokuro posted, we get chrome to display this, which is no good either.:

A: Here's something to try that uses JS.  I don't have IE to test on, but hopefully it'll give you some logic to go on either way.  The basic idea is to test the widths of the content and its container, while removing one character at a time to see when it fits. (I used jQuery just because it's faster for me, but you certainly don't need it.)

$('.left-ellipsis').each(function() {
 var $span = $(this).find('span');
 if ($span.width() > $(this).width()) {
  $span.addClass('ellipsis');
  while ($span.width() > $(this).width()) {
   $span.text($span.text().substr(1));
  }
 }
});
.left-ellipsis {
  overflow: hidden;
}

.left-ellipsis span {
 white-space:nowrap;
}

.left-ellipsis span.ellipsis {
 float:right;
}

.left-ellipsis span.ellipsis:before {
 content:"...";
}

With overflowing content

Expected to see 1 0002 0003 0004 0005 end

 123 456 789 0001 0002 0003 0004 0005 end

Without overflowing content

Expected to see 0002 0003 0004 0005 end without ...

 0002 0003 0004 0005 end


text:
Q: Surface extraction a fluid . At a given time-step I have a sampled a lot points from a  fluid , and I want to extract the
points which lie at the surface of the fluid. Does any one know a good algorithm
and any available codes to do this?
I am aware of surface reconstruction, but the assumption there is that the sampled points
are on/near the surface. So I guess that would not be too useful here.

A: Is finding the convex hull of the points adequate? How many points do you have?
Maybe start with a convex hull and then modify it to allow a certian amount of concavity where there are large parts of the surface without any points nearby.
Otherwise try fitting a spline or similar polynomial function to the points. You need some sort of cost metric to measure how good your fit is so that you don't bend your surface too much to reach the inner points. (Unless sharp high curvature sections are allowed for breaking waves etc?)
Is this a tank that get's moved about causing sloshing or something similar - if so there may be some physics model you can used to suggest the shape of surfaces likely to be found. The pattern of motion and speed of waves in the fluid may tell you how many waves etc you'd see.


text:
Q: Workflow for restarting a HTTP server from Clojure REPL A Clojure-based project of mine uses the netty (required by aleph) web server. I start the server, along with other components, in a web.clj file like this:
(ns myproject.web)

(def server (atom nil))

(defn initialize []
  (if @server
    (println "Warning: already initialized")
    (let [port 8001]
      (println (format "Starting http://localhost:%s/" port))
      (swap! server (fn [_] (start-http-server
                             (wrap-ring-handler app-routes)
                             {:port port}))))))

(defn shutdown []
  (when @server
    (do
      (println "Shutting down web server")
      (@server)
      (swap! server (fn [_] nil)))))

(defn reinitialize []
  "Run this on the REPL to reload web.clj and restart the web server"
  (myproject.web/shutdown)
  (use :reload-all 'myproject.web)
  (myproject.web/initialize))

The server instance is stored in a Clojure atom, so that it can be stopped later.
I use Emacs and Swank to directly launch the server on the REPL like this (after compiling web.clj with C-c C-k):
user> (myproject.web/initialize)

Whenever web.clj or other dependent modules are edited, I must

*

*remember NOT to recompile web.clj using C-c C-k because the atom holding the running instance would vanish (due to the atom from a newly compiled module) from the REPL.

*Run (myproject.web/reinitialize) which stops the server and then reloads the module before starting it again.
There are two problems with this:

*

*Often I forget point #1 and press C-c C-k anyway. This causes the loss of server atom in REPL, leading to having to kill swank (or restart emacs) so that I can start the server at the same port number.

*:reload-all doesn't report compile errors as friendly as C-c C-k (ugly traceback vs concise clickable errors).
How can I best address these two problems in this edit-compile-restart workflow?

A: You can replace
(def server (atom nil))

with
(defonce server (atom nil))

that way when you evaluate the buffer it will not redefine server.

A: for your first problem you can store the atom in a different namespace and on load only overwrite it if it is not yet defined. putting it in it's own namepspace will prevent it from being erased by the reload-all


text:
Q: Как использовать window.onload в React? Изучаю react. Хочу вывести комментарии, хранящиеся в localStorage при загрузке страницы, но не соображу, как это сделать. Пробовал скопировать массив из состояния и закинуть в него всё, что есть в сторожке так:
window.onload = function() {
        const initialItems = [...items]

        for (let i = 0; i < localStorage.length; i++) {
            initialItems.push(JSON.parse(localStorage.getItem(items.itemId)));
        }

        setItems(items);
    };

Код компонента:
import CommentForm from './CommentForm'
import CommentList from './CommentList'
import CommentatorsTop from "./CommentatorsTop";
import {useState} from 'react';

function CommentWidget() {
    const [items, setItems] = useState([]);

    window.onload = function() {
        const initialItems = [...items]

        for (let i = 0; i < localStorage.length; i++) {
            initialItems.push(JSON.parse(localStorage.getItem(items.itemId)));
        }

        setItems(items);
    };

    function addItem(item) {
        const newItems = [...items]

        newItems.push(item)

        setItems(newItems);

        const storageNewItems = JSON.stringify(newItems);

        localStorage.setItem(item.itemId, storageNewItems);
    }

    function removeCommentItem(position, itemId) {
        if (window.confirm('Удалить?')) {
            const newListItem = [...items]

            newListItem.splice(position, 1);

            localStorage.removeItem(itemId);

            setItems(newListItem);
        }
    }

    return (

                <CommentForm addNewItem={addItem}/>

                <CommentList comments={items} removeCommentItem={removeCommentItem} />

            <CommentatorsTop names={items}/>

    )
}

export default CommentWidget;

Весь код здесь
Что я тут делаю не так?

A: https://ru.reactjs.org/docs/hooks-effect.html
Вам нужен хук UseEffect. Он отслеживает перерендеринг компонента и вызывает функцию, которая выполняется, когда компонент рендерится. Если у этой функции будет return, то во время уничтожения компонента выполнится код из этого return.
Так вот, первым параметром UseEffet принимает функцию, вторым - массив зависимостей. Если второй параметр не будет передан, то функция переданная UseEffect будет вызываться при каждом перерендеринге. Если в качестве параметра будет передан пустой массив, то функция отработает лишь один раз, при первом рендеринге компонента. В качестве элемента этого массива может быть какое-нибудь состояние, например, или любая другая зависимость. Суть в том, что когда это, например, состояние будет изменено, тогда вызовится функция из UseEffect. Аналагом window.onload будет UseEffect со вторым параметром пустым массивов (выполнить при первом рендеринге компонента). Замените блок с
 window.onload = function() {

на что-то следующее
import React, { useState, useEffect } from 'react';
......
useEffect(() => {
const initialItems = [...items]

        for (let i = 0; i < localStorage.length; i++) {
            initialItems.push(JSON.parse(localStorage.getItem(items.itemId)));
        }

        setItems(items);

}, []);

A: *

*Нашёл ошибку в функции addItem: отправлять в localStorage здесь следует элемент item, а не массив, конечно.

*Однозначно, здесь можно использовать, хук useEffect. Однако, поскольку вопрос касался именно window.onload оставлю здесь решение. При перезагрузке страницы копировать массив items не нужно и бессмысленно. Необходимо объявить пустой массив
const storageItems = [] и добавить в него всё, что есть в localStorage так: for (let i = 0; i < localStorage.length; i++) { storageItems.push(JSON.parse(localStorage.getItem(localStorage.key(i)))); } и затем передать массив в state: setItems(items);
В итоге компонент выглядит так:
import CommentForm from './CommentForm'
import CommentList from './CommentList'
import CommentatorsTop from "./CommentatorsTop";
import React, {useState} from 'react';

function CommentWidget() {
    const [items, setItems] = useState([]);

    window.onload = function () {
        const storageItems = []

        for (let i = 0; i < localStorage.length; i++) {
            storageItems.push(JSON.parse(localStorage.getItem(localStorage.key(i))));
        }

        setItems(storageItems);
    };

    function addItem(item) {
        const newItems = [...items]

        newItems.push(item)

        setItems(newItems);

        const storageNewItems = JSON.stringify(item);

        localStorage.setItem(item.itemId, storageNewItems);
    }

    function removeCommentItem(position, itemId) {
        if (window.confirm('Удалить?')) {
            const newListItem = [...items]

            newListItem.splice(position, 1);

            localStorage.removeItem(itemId);

            setItems(newListItem);
        }
    }

    return (

                <CommentForm addNewItem={addItem}/>

                <CommentList comments={items} removeCommentItem={removeCommentItem}/>

            <CommentatorsTop names={items}/>

    )
}

export default CommentWidget;


text:
Q: How to populate a heroku postgresql database with a sql file First of, I want to say, that I am not a DB expert and I have no experience with the heroku service.
I want to deploy a play framework application to the heroku service. And I need a database to do so. So I created a postgresql database with this command, since it's supported by heroku:
Users-MacBook-Air:~ user$ heroku addons:create heroku-postgresql -a name_of_app

And I got this as response
Creating heroku-postgresql on ⬢ benchmarkingsoccerclubs... free
Database has been created and is available
! This database is empty. If upgrading, you can transfer
! data from another database with pg:copy

So the DB is now existing but empty of course. For development I worked with a local H2 Database.
Now I would want to populate the DB on heroku using a sql file, since it's quite a lot of data. But I couldn't find how to do that. Is there a command for the heroku CLI, where I can hand over the sql file as an argument and it populates the database? The File basically consists of a few tables which get created and around 10000 Insert commands.
EDIT: I also have CSV files from all the tables. So if there is a way how I can populate the Postgres DB with those would be also great

A: First, run the following to get your database's name
heroku pg:info --app <name_of_app>

In the output, note the value of "Add-on", which should look something like this:
Add-on:                postgresql-angular-12345

Then, issue the following command:
heroku pg:psql <Add-on> --app <name_of_app> < my_sql_file.sql

For example (assuming your sql commands are in file test.sql):
heroku pg:psql postgresql-angular-12345 --app my_cool_app < test.sql


text:
Q: selecting groups with zero values by action column in R I have next data
    mydat=structure(list(group = c(111L, 111L, 111L, 111L, 111L, 111L,
111L, 333L, 333L, 333L, 333L, 333L, 333L, 333L, 555L, 555L, 555L,
555L, 555L, 555L, 555L), group2 = c(222L, 222L, 222L, 222L, 222L,
222L, 222L, 444L, 444L, 444L, 444L, 444L, 444L, 444L, 666L, 666L,
666L, 666L, 666L, 666L, 666L), action = c(0L, 0L, 0L, 1L, 1L,
0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L
), x1 = c(1L, 2L, 3L, 0L, 0L, 1L, 2L, 1L, 2L, 3L, 0L, 0L, 1L,
2L, 1L, 2L, 3L, 10L, 20L, 1L, 2L)), .Names = c("group", "group2",
"action", "x1"), class = "data.frame", row.names = c(NA, -21L
))

Here two group variables(group and group2) .
there are three group
111 222
333 444
555 666

action column can take value only 0 and 1.
So i need find these groups where for 1 category of action they have only zero values by x1.
in our case it is
111 222
333 444

because for all 1 category  of action they have zeros by x1.
So i can work only with 555    666 group.
because it has at least one non-zero value of  first category of action by x1 variable.
The desired output
Mydat1 here groups with at least one non-zero value of  first category of action by x1 variable.
group   group2  action  x1
555      666    0   1
555      666    0   2
555      666    0   3
555      666    1   **10**
555      666    1   **20**
555      666    0   1
555      666    0   2

mydat2 groups  which for all 1 category  of action they have zeros by x1
group   group2  action  x1
111      222    0   1
111      222    0   2
111      222    0   3
111      222    1   **0**
111      222    1   **0**
111      222    0   1
111      222    0   2
333      444    0   1
333      444    0   2
333      444    0   3
333      444    1   **0**
333      444    1   **0**
333      444    0   1
333      444    0   2

A: If i correctly you, then understand your question is:

i need find these groups where for 1 category of action they have
  only zero values by x1.

so here is the response:
library(tidyverse)
mydat  %>%
  group_by( action ) %>%
  filter( action==1 & x1==0 )

and the response is:
  group group2 action    x1
  <int>  <int>  <int> <int>
1   111    222      1     0
2   111    222      1     0
3   333    444      1     0
4   333    444      1     0

What does this code do?
it looks at action feature, and consider 2 main categories for all rows(0,and 1). Then it filters out the observations which pass action==1 & x1==0. So, it means, among those rows who have action==1 the x1==0 is true as well.

can script return all values of 555+666 group?

No. it does not return these 2 groups. And it should not do that. Let's write a code which filters 555,and 666
library(tidyverse)
mydat  %>%
  group_by( action ) %>%
  filter( group==555 | group2==666 )

and the result is:
group group2 action    x1
  <int>  <int>  <int> <int>
1   555    666      0     1
2   555    666      0     2
3   555    666      0     3
4   555    666      1    10
5   555    666      1    20
6   555    666      0     1
7   555    666      0     2

so, as you can see, none of these observation fulfills the condition action==1 & x1==0 . Therefore, they are not among the valid response.


text:
Q: How to create a function, returning a vector, that uses a custom pool allocator if provided, but defaults to the std::allocator? In the code below is the function make_vector(). It creates a vector and returns it to the caller. I want to be able to specify an allocator for the vector to use, but use the default std::allocator by default. This is because under some circumstances the default allocator is all I need, but other times I need to allocate from some pre-defined memory pools.
The closest I've come is the make_vector2() function template. It works with the std::allocator, but I don't know how to pass the 'arena' argument into my custom allocator.
Hopefull this working c++11 example will explain it better:
#include <malloc.h>
#include <cinttypes>
#include <cstddef>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>

namespace mem
{
    // Memory arena to allocate from.
    enum class ARENA
    {
        TEXTURES,
        FONTS,
        SCRIPTS
    };

    // Allocate block from specific arena.
    void *malloc( const std::size_t size, const ARENA arena )
    {
        return std::malloc( size /*, arena */ );
    }

    // Free block from specific arena.
    void free( void *ptr, const ARENA arena )
    {
        std::free( ptr /*, arena */ );
    }

    // The allocator - forward declaration.
    // Not derived from std::allocator - should it be?
    // Based on code from here:
    // http://drdobbs.com/184403759?pgno=2
    template<typename T> class allocator;

    // Specialised for void.
    template<> class allocator<void>
    {
        public:
            typedef std::size_t size_type;
            typedef ptrdiff_t difference_type;
            typedef void* pointer;
            typedef const void* const_pointer;
            typedef void value_type;

            template<typename U> struct rebind
            {
                typedef allocator<U> other;
            };
    };

    template<typename T> class allocator
    {
        public:
            typedef std::size_t size_type;
            typedef std::ptrdiff_t difference_type;
            typedef T* pointer;
            typedef const T* const_pointer;
            typedef T& reference;
            typedef const T& const_reference;
            typedef T value_type;

            template<typename U> struct rebind
            {
                 typedef allocator<U> other;
            };

            allocator( ARENA arena ) noexcept :
                arena_( arena )
            {}

            ~allocator() noexcept
            {}

            pointer address( reference x ) const
            {
                    return &x;
            }

            const_pointer address( const_reference x ) const
            {
                return &x;
            }

            pointer allocate( size_type n, allocator<void>::const_pointer hint = 0 )
            {
                void *p = mem::malloc( n * sizeof( T ), arena_ );
                if ( p == nullptr )
                {
                        throw std::bad_alloc();
                }
                return static_cast<pointer>( p );
            }

            void deallocate( pointer p, size_type n )
            {
                mem::free( p, arena_ );
            }

            size_type max_size() const noexcept
            {
                return std::numeric_limits<std::size_t>::max() / sizeof( T );
            }

            void construct( pointer p, const T& val )
            {
                new (p) T(val);
            }

            void destroy( pointer p )
            {
                p->~T();
            }

            allocator( const allocator& src ) noexcept
            {
                arena_ = src.arena_;
            }

            ARENA arena_;
    };
} // namespace mem

template<class T1, class T2> bool operator==( const mem::allocator<T1> &alloc1, const mem::allocator<T2> &alloc2 ) noexcept
{
    return alloc1.arena_ == alloc2.arena_;
}

template<class T1, class T2> bool operator!=( const mem::allocator<T1> &alloc1, const mem::allocator<T2> &alloc2 ) noexcept
{
    if alloc1.arena_ != alloc2.arena_;
}

// How do I allow the custom allocator to be passed? Function parameter? Template?
std::vector<uint8_t> make_vector()
{
    std::vector<uint8_t> vec;
    // Do stuff with the vector
    return vec;
}

// This template function seems to work with std::allocator
template< typename T > std::vector<uint8_t,T> make_vector2()
{
    std::vector<uint8_t,T> vec;
    // Do stuff with the vector.
    return vec;
}

int main( int argc, char **argv )
{
    // vec1 - Allocates from TEXTURES arena
    // See the C++11 FAQ by  Bjarne Stroustrup here:
    // http://www2.research.att.com/~bs/C++0xFAQ.html#scoped-allocator
    std::vector<uint8_t, mem::allocator<uint8_t>> vec1( mem::allocator<uint8_t>{mem::ARENA::TEXTURES} );

    // vec2 - Make the vector using the default allocator.
    auto vec2 = make_vector2< std::allocator<uint8_t> >();

    return 0;
}

In main() vec1 is created to use the TEXTURES arena for allocation. The arena to use is passed into the constructor of the allocator. Vec2 is created by the make_vector2() templated function and uses the std::allocator.
Q: How can I define the make_vector() function so it can create a vector that uses the std::allocator or the custom pool allocator above?

A: In C++11, function templates can have default template arguments:
template<class T, class Alloc = std::allocator<T>>
std::vector<T, Alloc> make_vector(Alloc const& al = Alloc()){
  std::vector<T, Alloc> v(al);
  // ...
  return v;
}

Live example on Ideone.
In C++03 (or with compilers that don't support that feature), it's a bit more cumbersome, but you can overload based on the template parameters:
template<class T>
std::vector<T> make_vector(){
  std::vector<T> v;
  // ...
  return v;
}

template<class T, class Alloc>
std::vector<T, Alloc> make_vector(Alloc const& al = Alloc()){
  std::vector<T, Alloc> v(al);
  // ...
  return v;
}

Live example on Ideone.

A: You can provide two different function overloads:
template<typename T, typename Alloc>
std::vector<T, Alloc> func(Alloc a)
{
    return std::vector<T, Alloc>();
}

template<typename T>
std::vector<T, std::allocator<T> > func()
{
    return func<T>(std::allocator<T>());
}

A: The problem is that the type of allocator is part of the type of the vector, so you are basically asking for a function whose return value type depends on an argument.  You can do this by returning a boost::variant, but I'm not sure this is a good idea.  The client code still needs to know the type in order to use the vector.