Programs & Examples On #Sys refcursor

A predefined Oracle cursor variable type.

How can I use Oracle SQL developer to run stored procedures?

Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).

I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number).

I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:

DECLARE
  DNO NUMBER;
  MAXSAL NUMBER;
BEGIN
  DNO := NULL;

  GET_MAXSAL_BY_DEPT(
    DNO => DNO,
    MAXSAL => MAXSAL
  );
  DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;

I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:

Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc. 

To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor.

DECLARE
  DNO NUMBER;
  v_Return sys_refcursor;
BEGIN
  DNO := 50;

  v_Return := GET_EMPS_BY_DEPT(
    DNO => DNO
  );
  -- Modify the code to output the variable
  -- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;

However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...

DECLARE
  DNO NUMBER;
  v_Return sys_refcursor;
  v_rec emp%rowtype;
BEGIN
  DNO := 50;

  v_Return := GET_EMPS_BY_DEPT(
    DNO => DNO
  );

  loop
    fetch v_Return into v_rec;
    exit when v_Return%notfound;
    DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
  end loop;
END;

The output from the same location:

Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc. 

Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:

var rc refcursor 
exec :rc := get_emps_by_dept(30) 
print rc

In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).

The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.


"When I type just var rc refcursor; and select it and run it, I get this error (GUI):"

There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor and click Execute Statement (or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script (or F5 ), even for a single line of SQL*Plus.


"I am so close ... please help."

You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:

exec :rc := get_account(1)

What you need is something like the following. I have used the named notation for clarity.

var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor

exec :tran_cnt := 0
exec :msg_cnt := 123

exec get_account (Vret_val => :ret1, 
                  Vtran_count => :tran_cnt, 
                  Vmessage_count => :msg_cnt, 
                  Vaccount_id   => 1,
                  rc1 => :rc )

print tran_count 
print rc

That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.

Changing the space between each item in Bootstrap navbar

As of Bootstrap 4, you can use the spacing utilities.

Add for instance px-2 in the classes of the nav-item to increase the padding.

insert datetime value in sql database with c#

The following should work and is my recommendation (parameterized query):

DateTime dateTimeVariable = //some DateTime value, e.g. DateTime.Now;
SqlCommand cmd = new SqlCommand("INSERT INTO <table> (<column>) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", dateTimeVariable);

cmd.ExecuteNonQuery();

Bootstrap 4 Center Vertical and Horizontal Alignment

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
    <div class="col-12 border border-info">_x000D_
          <div class="d-flex justify-content-center align-items-center" style="height: 100px">_x000D_
              <a href="#" class="btn btn-dark">Transfer</a>_x000D_
              <a href="#" class="btn btn-dark mr-2 ml-2">Replenish</a>_x000D_
              <a href="#" class="btn btn-dark mr-3">Account Details</a>_x000D_
          </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Flask at first run: Do not use the development server in a production environment

The official tutorial discusses deploying an app to production. One option is to use Waitress, a production WSGI server. Other servers include Gunicorn and uWSGI.

When running publicly rather than in development, you should not use the built-in development server (flask run). The development server is provided by Werkzeug for convenience, but is not designed to be particularly efficient, stable, or secure.

Instead, use a production WSGI server. For example, to use Waitress, first install it in the virtual environment:

$ pip install waitress

You need to tell Waitress about your application, but it doesn’t use FLASK_APP like flask run does. You need to tell it to import and call the application factory to get an application object.

$ waitress-serve --call 'flaskr:create_app'
Serving on http://0.0.0.0:8080

Or you can use waitress.serve() in the code instead of using the CLI command.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "<h1>Hello!</h1>"

if __name__ == "__main__":
    from waitress import serve
    serve(app, host="0.0.0.0", port=8080)
$ python hello.py

How to parse JSON and access results

Try:

$result = curl_exec($cURL);
$result = json_decode($result,true);

Now you can access MessageID from $result['MessageID'].

As for the database, it's simply using a query like so:

INSERT INTO `tableName`(`Cancelled`,`Queued`,`SMSError`,`SMSIncommingMessage`,`Sent`,`SentDateTime`) VALUES('?','?','?','?','?');

Prepared.

Delete files older than 3 months old in a directory using .NET

Here's a 1-liner lambda:

Directory.GetFiles(dirName)
         .Select(f => new FileInfo(f))
         .Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-3))
         .ToList()
         .ForEach(f => f.Delete());

When to use DataContract and DataMember attributes?

DataMember attribute is not mandatory to add to serialize data. When DataMember attribute is not added, old XMLSerializer serializes the data. Adding a DataMember provides useful properties like order, name, isrequired which cannot be used otherwise.

Can we call the function written in one JavaScript in another JS file?

yes you can . you need to refer both JS file to the .aspx page

<script language="javascript" type="text/javascript" src="JScript1.js">
 </script>

    <script language="javascript" type="text/javascript" src="JScript2.js">
    </script>

JScript1.js

function ani1() {
    alert("1");
    ani2();
}
JScript2.js
function ani2() {
    alert("2");
}

How to check a boolean condition in EL?

Both works. Instead of == you can write eq

IE7 Z-Index Layering Issues

In IE positioned elements generate a new stacking context, starting with a z-index value of 0. Therefore z-index doesn’t work correctly.

Try give the parent element a higher z-index value (can be even higher than the child’s z-index value itself) to fix the bug.

Capture Signature using HTML5 and iPad

Here's another canvas based version with variable width (based on drawing velocity) curves: demo at http://szimek.github.io/signature_pad and code at https://github.com/szimek/signature_pad.

signature sample

How to run .APK file on emulator

Step-by-Step way to do this:

  1. Install Android SDK
  2. Start the emulator by going to $SDK_root/emulator.exe
  3. Go to command prompt and go to the directory $SDK_root/platform-tools (or else add the path to windows environment)
  4. Type in the command adb install
  5. Bingo. Your app should be up and running on the emulator

How to get the return value from a thread in python?

I know this thread is old.... but I faced the same problem... If you are willing to use thread.join()

import threading

class test:

    def __init__(self):
        self.msg=""

    def hello(self,bar):
        print('hello {}'.format(bar))
        self.msg="foo"


    def main(self):
        thread = threading.Thread(target=self.hello, args=('world!',))
        thread.start()
        thread.join()
        print(self.msg)

g=test()
g.main()

Android 6.0 multiple permissions

There is nothing wrong with answers asking for multiple permissions but multiple permission result code is not implemented very elegantly and may cause checking wrong permission result.

if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) is terrible logic for checking multiple permissions result, i don't know why Google implemented such a terrible code.

It's a mess especially when you check multiple permissions. Let say you ask for CAMERA, ACCESS_FINE_LOCATION and ACCESS_NETWORK_STATE.

You need to check for ACCESS_FINE_LOCATION but user only granted CAMERA at first run and you check for grantResults[1] but in second run ACCESS_FINE_LOCATION becomes the permission with index 0. I got so many problems with user not granting all permissions at once and have to write so pointless permission result logic.

You should either use

   int size = permissions.length;
    boolean locationPermissionGranted = false;

    for (int i = 0; i < size; i++) {
        if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)
                && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
            locationPermissionGranted = true;
        }
    }

Or simpler one

   if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
           // Do something ...
        }

in onPermissionRequestResult method.

How can I print variable and string on same line in Python?

You can either use the f-string or .format() methods

Using f-string

print(f'If there was a birth every 7 seconds, there would be: {births} births')

Using .format()

print("If there was a birth every 7 seconds, there would be: {births} births".format(births=births))

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

If you are using jersey 2.x then you need different configuration in web.xml as servlet class is change in it. you can update your web.xml with following configuration.

    <servlet>
    <servlet-name>myrest</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>    
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>your.package.path</param-value>
    </init-param>
    <init-param>
     <param-name>unit:WidgetPU</param-name>
     <param-value>persistence/widget</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>myrest</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>

SELECT data from another schema in oracle

In addition to grants, you can try creating synonyms. It will avoid the need for specifying the table owner schema every time.

From the connecting schema:

CREATE SYNONYM pi_int FOR pct.pi_int;

Then you can query pi_int as:

SELECT * FROM pi_int;

How to plot two columns of a pandas data frame using points?

You can specify the style of the plotted line when calling df.plot:

df.plot(x='col_name_1', y='col_name_2', style='o')

The style argument can also be a dict or list, e.g.:

import numpy as np
import pandas as pd

d = {'one' : np.random.rand(10),
     'two' : np.random.rand(10)}

df = pd.DataFrame(d)

df.plot(style=['o','rx'])

All the accepted style formats are listed in the documentation of matplotlib.pyplot.plot.

Output

What is the closest thing Windows has to fork()?

If you only care about creating a subprocess and waiting for it, perhaps _spawn* API's in process.h are sufficient. Here's more information about that:

https://docs.microsoft.com/en-us/cpp/c-runtime-library/process-and-environment-control https://en.wikipedia.org/wiki/Process.h

Float sum with javascript

(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);

its going to give you solution i suppose

Get $_POST from multiple checkboxes

you have to name your checkboxes accordingly:

<input type="checkbox" name="check_list[]" value="…" />

you can then access all checked checkboxes with

// loop over checked checkboxes
foreach($_POST['check_list'] as $checkbox) {
   // do something
}

ps. make sure to properly escape your output (htmlspecialchars())

How do I select a random value from an enumeration?

Adapted as a Random class extension:

public static class RandomExtensions
{   
    public static T NextEnum<T>(this Random random)
    {
        var values = Enum.GetValues(typeof(T));
        return (T)values.GetValue(random.Next(values.Length));
    }
}

Example of usage:

var random = new Random();
var myEnumRandom = random.NextEnum<MyEnum>();

continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

vim - How to delete a large block of text without counting the lines?

If the entire block is visible on the screen, you can use relativenumber setting. See :help relativenumber. Available in 7.3

Could not find a version that satisfies the requirement tensorflow

Running this before the tensorflow installation solved it for me:

pip install "pip>=19"

As the tensorflow's system requirements states:

pip 19.0 or later

Regular expression to extract text between square brackets

You can use the following regex globally:

\[(.*?)\]

Explanation:

  • \[ : [ is a meta char and needs to be escaped if you want to match it literally.
  • (.*?) : match everything in a non-greedy way and capture it.
  • \] : ] is a meta char and needs to be escaped if you want to match it literally.

Problems after upgrading to Xcode 10: Build input file cannot be found

There is also one possibility that sometimes when you move your files to different folder and especially when you move your info.plist to other folder, you need to define the location of that file. To solve this problem, simply click on your project blue icon on the top, and you will see a button in place of project name and bundle id, click on it and locate the info.plist file there, clean and compile happily.

Java Mouse Event Right Click

I've seen

anEvent.isPopupTrigger() 

be used before. I'm fairly new to Java so I'm happy to hear thoughts about this approach :)

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

Building on Oded's answer, you could also set the default option but not make it a selectable option if it's just dummy text. For example you could do:

<option selected="selected" disabled="disabled">Select a language</option>

This would show "Select a language" before the user clicks the select box but the user wouldn't be able to select it because of the disabled attribute.

Import-CSV and Foreach

Solution is to change Delimiter.

Content of the csv file -> Note .. Also space and , in value

Values are 6 Dutch word aap,noot,mies,Piet, Gijs, Jan

Col1;Col2;Col3

a,ap;noo,t;mi es

P,iet;G ,ijs;Ja ,n



$csv = Import-Csv C:\TejaCopy.csv -Delimiter ';' 

Answer:

Write-Host $csv
@{Col1=a,ap; Col2=noo,t; Col3=mi es} @{Col1=P,iet; Col2=G ,ijs; Col3=Ja ,n}

It is possible to read a CSV file and use other Delimiter to separate each column.

It worked for my script :-)

Force GUI update from UI Thread

Call Application.DoEvents() after setting the label, but you should do all the work in a separate thread instead, so the user may close the window.

Argparse optional positional arguments?

parser.add_argument also has a switch required. You can use required=False. Here is a sample snippet with Python 2.7:

parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()

Easy way to concatenate two byte arrays

Another way is to use a utility function (you could make this a static method of a generic utility class if you like):

byte[] concat(byte[]...arrays)
{
    // Determine the length of the result array
    int totalLength = 0;
    for (int i = 0; i < arrays.length; i++)
    {
        totalLength += arrays[i].length;
    }

    // create the result array
    byte[] result = new byte[totalLength];

    // copy the source arrays into the result array
    int currentIndex = 0;
    for (int i = 0; i < arrays.length; i++)
    {
        System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
        currentIndex += arrays[i].length;
    }

    return result;
}

Invoke like so:

byte[] a;
byte[] b;
byte[] result = concat(a, b);

It will also work for concatenating 3, 4, 5 arrays, etc.

Doing it this way gives you the advantage of fast arraycopy code which is also very easy to read and maintain.

How to store image in SQL Server database tables column

give this a try,

insert into tableName (ImageColumn) 
SELECT BulkColumn 
FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img

INSERTING

enter image description here

REFRESHING THE TABLE

enter image description here

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

This problem can be caused by requests for certain files that don't exist. For example, requests for files in wp-content/uploads/ where the file does not exist.

If this is the situation you're seeing, you can solve the problem by going to .htaccess and changing this line:

RewriteRule ^(wp-(content|admin|includes).*) $1 [L]

to:

RewriteRule ^(wp-(content|admin|includes).*) - [L]

The underlying issue is that the rule above triggers a rewrite to the exact same url with a slash in front and because there was a rewrite, the newly rewritten request goes back through the rules again and the same rule is triggered. By changing that line's "$1" to "-", no rewrite happens and so the rewriting process does not start over again with the same URL.

It's possible that there's a difference in how apache 2.2 and 2.4 handle this situation of only-difference-is-a-slash-in-front and that's why the default rules provided by WordPress aren't working perfectly.

Ignore .pyc files in git repository

If you want to ignore '.pyc' files globally (i.e. if you do not want to add the line to .gitignore file in every git directory), try the following:

$ cat ~/.gitconfig 
[core]
    excludesFile = ~/.gitignore
$ cat ~/.gitignore
**/*.pyc

[Reference]
https://git-scm.com/docs/gitignore

  • Patterns which a user wants Git to ignore in all situations (e.g., backup or temporary files generated by the user’s editor of choice) generally go into a file specified by core.excludesFile in the user’s ~/.gitconfig.

  • A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".

How to get bitmap from a url in android?

This is a simple one line way to do it:

    try {
        URL url = new URL("http://....");
        Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    } catch(IOException e) {
        System.out.println(e);
    }

How to do multiple conditions for single If statement

As Hogan notes above, use an AND instead of &. See this tutorial for more info.

How to tell if a connection is dead in python

It depends on what you mean by "dropped". For TCP sockets, if the other end closes the connection either through close() or the process terminating, you'll find out by reading an end of file, or getting a read error, usually the errno being set to whatever 'connection reset by peer' is by your operating system. For python, you'll read a zero length string, or a socket.error will be thrown when you try to read or write from the socket.

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

If you want to filter rows by a certain number of columns with null values, you may use this:

df.iloc[df[(df.isnull().sum(axis=1) >= qty_of_nuls)].index]

So, here is the example:

Your dataframe:

>>> df = pd.DataFrame([range(4), [0, np.NaN, 0, np.NaN], [0, 0, np.NaN, 0], range(4), [np.NaN, 0, np.NaN, np.NaN]])
>>> df
     0    1    2    3
0  0.0  1.0  2.0  3.0
1  0.0  NaN  0.0  NaN
2  0.0  0.0  NaN  0.0
3  0.0  1.0  2.0  3.0
4  NaN  0.0  NaN  NaN

If you want to select the rows that have two or more columns with null value, you run the following:

>>> qty_of_nuls = 2
>>> df.iloc[df[(df.isnull().sum(axis=1) >=qty_of_nuls)].index]
     0    1    2   3
1  0.0  NaN  0.0 NaN
4  NaN  0.0  NaN NaN

Ant: How to execute a command for each file in directory?

Do what blak3r suggested and define your targets classpath like so

<taskdef resource="net/sf/antcontrib/antlib.xml">
    <classpath>
        <fileset dir="lib">
          <include name="**/*.jar"/>
        </fileset>
    </classpath>        
</taskdef>

where lib is where you store your jar's

Join two sql queries

You can use CTE also like below.

With cte as
(select Activity, SUM(Amount) as "Total Amount 2009"
   from Activities, Incomes
  where Activities.UnitName = ? AND
        Incomes.ActivityId = Activities.ActivityID
  GROUP BY Activity
),
cte1 as 
(select Activity, SUM(Amount) as "Total Amount 2008"
   from Activities, Incomes2008
  where Activities.UnitName = ? AND
        Incomes2008.ActivityId = Activities.ActivityID
  GROUP BY Activity
)
Select cte.Activity, cte.[Total Amount 2009] ,cte1.[Total Amount 2008]      
  from cte join cte1 ON cte.ActivityId = cte1.ActivityID
 WHERE a.UnitName = ?
 ORDER BY cte.Activity 

How do I set up CLion to compile and run?

I met some problems in Clion and finally, I solved them. Here is some experience.

  1. Download and install MinGW
  2. g++ and gcc package should be installed by default. Use the MinGW installation manager to install mingw32-libz and mingw32-make. You can open MinGW installation manager through C:\MinGW\libexec\mingw-get.exe This step is the most important step. If Clion cannot find make, C compiler and C++ compiler, recheck the MinGW installation manager to make every necessary package is installed.
  3. In Clion, open File->Settings->Build,Execution,Deployment->Toolchains. Set MinGW home as your local MinGW file.
  4. Start your "Hello World"!

How to update/refresh specific item in RecyclerView

In your adapter class, in onBindViewHolder method, set ViewHolder to setIsRecyclable(false) as in below code.

@Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder p1, int p2)
{
    // TODO: Implement this method
    p1.setIsRecyclable(false);

    // Then your other codes
}

Pandas dataframe fillna() only some columns in place

Here's how you can do it all in one line:

df[['a', 'b']].fillna(value=0, inplace=True)

Breakdown: df[['a', 'b']] selects the columns you want to fill NaN values for, value=0 tells it to fill NaNs with zero, and inplace=True will make the changes permanent, without having to make a copy of the object.

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

get current page from url

You could try this below.

string url = "http://localhost:1302/TESTERS/Default6.aspx";

string fileName = System.IO.Path.GetFileName(url);

Hope this helps.

How to take the nth digit of a number in python

I was curious about the relative speed of the two popular approaches - casting to string and using modular arithmetic - so I profiled them and was surprised to see how close they were in terms of performance.

(My use-case was slightly different, I wanted to get all digits in the number.)

The string approach gave:

         10000002 function calls in 1.113 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.113    0.000    1.113    0.000 sandbox.py:1(get_digits_str)
        1    0.000    0.000    0.000    0.000 cProfile.py:133(__exit__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

While the modular arithmetic approach gave:


         10000002 function calls in 1.102 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.102    0.000    1.102    0.000 sandbox.py:6(get_digits_mod)
        1    0.000    0.000    0.000    0.000 cProfile.py:133(__exit__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

There were 10^7 tests run with a max number size less than 10^28.

Code used for reference:

def get_digits_str(num):
    for n_str in str(num):
        yield int(n_str)


def get_digits_mod(num, radix=10):

    remaining = num
    yield remaining % radix

    while remaining := remaining // radix:
        yield remaining % radix


if __name__ == '__main__':

    import cProfile
    import random

    random_inputs = [random.randrange(0, 10000000000000000000000000000) for _ in range(10000000)]

    with cProfile.Profile() as str_profiler:
        for rand_num in random_inputs:
            get_digits_str(rand_num)

    str_profiler.print_stats(sort='cumtime')

    with cProfile.Profile() as mod_profiler:
        for rand_num in random_inputs:
            get_digits_mod(rand_num)

    mod_profiler.print_stats(sort='cumtime')

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

Method to replace substring in a sentence using React:

 const replace_in_javascript = (oldSubStr, newSubStr, sentence) => {
    let newStr = "";
    let i = 0;
    sentence.split(" ").forEach(obj => {
      if (obj.toUpperCase() === oldSubStr.toUpperCase()) {
        newStr = i === 0 ? newSubStr : newStr + " " + newSubStr;
        i = i + 1;
      } else {
        newStr = i === 0 ? obj : newStr + " " + obj;
        i = i + 1;
      }
    });
    return newStr;
  };

RunMethodHere

Understanding inplace=True

In pandas, is inplace = True considered harmful, or not?

TLDR; Yes, yes it is.

  • inplace, contrary to what the name implies, often does not prevent copies from being created, and (almost) never offers any performance benefits
  • inplace does not work with method chaining
  • inplace can lead to SettingWithCopyWarning if used on a DataFrame column, and may prevent the operation from going though, leading to hard-to-debug errors in code

The pain points above are common pitfalls for beginners, so removing this option will simplify the API.


I don't advise setting this parameter as it serves little purpose. See this GitHub issue which proposes the inplace argument be deprecated api-wide.

It is a common misconception that using inplace=True will lead to more efficient or optimized code. In reality, there are absolutely no performance benefits to using inplace=True. Both the in-place and out-of-place versions create a copy of the data anyway, with the in-place version automatically assigning the copy back.

inplace=True is a common pitfall for beginners. For example, it can trigger the SettingWithCopyWarning:

df = pd.DataFrame({'a': [3, 2, 1], 'b': ['x', 'y', 'z']})

df2 = df[df['a'] > 1]
df2['b'].replace({'x': 'abc'}, inplace=True)
# SettingWithCopyWarning: 
# A value is trying to be set on a copy of a slice from a DataFrame

Calling a function on a DataFrame column with inplace=True may or may not work. This is especially true when chained indexing is involved.

As if the problems described above aren't enough, inplace=True also hinders method chaining. Contrast the working of

result = df.some_function1().reset_index().some_function2()

As opposed to

temp = df.some_function1()
temp.reset_index(inplace=True)
result = temp.some_function2()

The former lends itself to better code organization and readability.


Another supporting claim is that the API for set_axis was recently changed such that inplace default value was switched from True to False. See GH27600. Great job devs!

Convert row to column header for Pandas DataFrame,

To rename the header without reassign df:

df.rename(columns=df.iloc[0], inplace = True)

To drop the row without reassign df:

df.drop(df.index[0], inplace = True)

Your password does not satisfy the current policy requirements

For Laravel users having this issue with MySQL 8.0.x, add

'modes'=> [
             'ONLY_FULL_GROUP_BY',
             'STRICT_TRANS_TABLES',
             'NO_ZERO_IN_DATE',
             'NO_ZERO_DATE',
             'ERROR_FOR_DIVISION_BY_ZERO',
             'NO_ENGINE_SUBSTITUTION',
            ],

to your database.php file as below:

// database.php

    'connections' => [

        'mysql' => [
            'driver'      => 'mysql',
            'host'        => env( 'DB_HOST', '127.0.0.1' ),
            'port'        => env( 'DB_PORT', '3306' ),
            'database'    => env( 'DB_DATABASE', 'forge' ),
            'username'    => env( 'DB_USERNAME', 'forge' ),
            'password'    => env( 'DB_PASSWORD', '' ),
            'unix_socket' => env( 'DB_SOCKET', '' ),
            'charset'     => 'utf8mb4',
            'collation'   => 'utf8mb4_unicode_ci',
            'prefix'      => '',
            'strict'      => true,
            'engine'      => null,
            'modes'       => [
                'ONLY_FULL_GROUP_BY',
                'STRICT_TRANS_TABLES',
                'NO_ZERO_IN_DATE',
                'NO_ZERO_DATE',
                'ERROR_FOR_DIVISION_BY_ZERO',
                'NO_ENGINE_SUBSTITUTION',
            ],
        ],
    ],

It fixed it for me.

How to programmatically set the SSLContext of a JAX-WS client?

This is how I solved it based on this post with some minor tweaks. This solution does not require creation of any additional classes.

SSLContext sc = SSLContext.getInstance("SSLv3");

KeyManagerFactory kmf =
    KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );

KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
ks.load(new FileInputStream( certPath ), certPasswd.toCharArray() );

kmf.init( ks, certPasswd.toCharArray() );

sc.init( kmf.getKeyManagers(), null, null );

((BindingProvider) webservicePort).getRequestContext()
    .put(
        "com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
        sc.getSocketFactory() );

C compiling - "undefined reference to"?

As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.

Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,

int main()
{
  int a = func();
}

int func()
{
   return 1;
}

However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.

int func();

int main()
{
   int a = func();
}

int func()
{
  return 1;
}

WCF change endpoint address at runtime

So your endpoint address defined in your first example is incomplete. You must also define endpoint identity as shown in client configuration. In code you can try this:

EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
var address = new EndpointAddress("http://id.web/Services/EchoService.svc", spn);   
var client = new EchoServiceClient(address); 
litResponse.Text = client.SendEcho("Hello World"); 
client.Close();

Actual working final version by valamas

EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
Uri uri = new Uri("http://id.web/Services/EchoService.svc");
var address = new EndpointAddress(uri, spn);
var client = new EchoServiceClient("WSHttpBinding_IEchoService", address);
client.SendEcho("Hello World");
client.Close(); 

Calling startActivity() from outside of an Activity?

Sometimes this error can occur without an explicit call to startActivity(...). For example, some of you may have seen a stack trace like this in Crashlytics:

Fatal Exception: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
       at android.app.ContextImpl.startActivity(ContextImpl.java:1597)
       at android.app.ContextImpl.startActivity(ContextImpl.java:1584)
       at android.content.ContextWrapper.startActivity(ContextWrapper.java:337)
       at android.text.style.URLSpan.onClick(URLSpan.java:62)
       at android.text.method.LinkMovementMethod.onTouchEvent(LinkMovementMethod.java:217)
       at android.widget.TextView.onTouchEvent(TextView.java:9522)
       at android.view.View.dispatchTouchEvent(View.java:8968)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.widget.AbsListView.dispatchTouchEvent(AbsListView.java:5303)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2559)
       at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1767)
       at android.app.Activity.dispatchTouchEvent(Activity.java:2866)
       at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
       at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
       at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2520)
       at android.view.View.dispatchPointerEvent(View.java:9173)
       at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4706)
       at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4544)
       at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4068)
       at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4121)
       at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4087)
       at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4201)
       at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4095)
       at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4258)
       at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4068)
       at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4121)
       at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4087)
       at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4095)
       at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4068)
       at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6564)
       at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6454)
       at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6425)
       at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6654)
       at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
       at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
       at android.os.MessageQueue.next(MessageQueue.java:143)
       at android.os.Looper.loop(Looper.java:130)
       at android.app.ActivityThread.main(ActivityThread.java:5942)
       at java.lang.reflect.Method.invoke(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

And you may wonder what you did wrong, since the trace only includes framework code. Well, here's an example of how this can happen. Let's say we're in a fragment.

Activity activity = getActivity();
Context activityContext = activity;
Context appContext = activityContext.getApplicationContext();
LayoutInflater inflater = LayoutInflater.from(appContext); // whoops!
View view = inflater.inflate(R.layout.some_layout, parent, false);
TextView tvWithLinks = (TextView) view.findViewById(R.id.tv_with_links);

tvWithLinks.setMovementMethod(LinkMovementMethod.getInstance()); // whoops!!

Now, when a user clicks on that text view, your app will crash with the stack trace above. This is because the layout inflater has a reference to the application context, and so therefore your text view has an application context. Clicking on that text view implicitly calls appContext.startActivity(...).

Final note: I tested this on Android 4, 5, 6, and 7 devices. It only affects 4, 5, and 6. Android 7 devices apparently have no trouble calling appContext.startActivity(...).

I hope this helps someone else!

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

The Request Payload - or to be more precise: payload body of a HTTP Request - is the data normally send by a POST or PUT Request. It's the part after the headers and the CRLF of a HTTP Request.

A request with Content-Type: application/json may look like this:

POST /some-path HTTP/1.1
Content-Type: application/json

{ "foo" : "bar", "name" : "John" }

If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.

If you submit a HTML-Form with method="POST" and Content-Type: application/x-www-form-urlencoded or Content-Type: multipart/form-data your request may look like this:

POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded

foo=bar&name=John

In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.

So, they differ in the Content-Type but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.

How do I implement charts in Bootstrap?

Later than my previous answer, but may be useful anyway; while gRaphaël Charting may be an outdated alternative, a more recent and nicer option may be http://chartjs.org - still without any Flash, with a MIT license, and a recently updated GitHub.

I've been using it myself since my last answer, so now I have some web apps with one and some with the other.

If you are starting a project anew, try with Chart.js first.

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Work for me.. Ubuntu 18.04

sudo nano /usr/share/phpmyadmin/libraries/sql.lib.php

Find for count($analyzed_sql_results['select_expr'] code on file. You can get this at line ~613.

|| (count($analyzed_sql_results['select_expr'] == 1)

Just replace with code :

|| ((count($analyzed_sql_results['select_expr']) == 1)

Save the file and reload PhpMyAdmin.

Done!!!

Redirect pages in JSP?

Extending @oopbase's answer with return; statement.

Let's consider a use case of traditional authentication system where we store login information into the session. On each page we check for active session like,

/* Some Import Statements here. */

if(null == session || !session.getAttribute("is_login").equals("1")) {
    response.sendRedirect("http://domain.com/login");
}

// ....

session.getAttribute("user_id");

// ....
/* Some More JSP+Java+HTML code here */

It looks fine at first glance however; It has one issue. If your server has expired session due to time limit and user is trying to access the page he might get error if you have not written your code in try..catch block or handled if(null != session.getAttribute("attr_name")) everytime.

So by putting a return; statement I stopped further execution and forced to redirect page to certain location.

if(null == session || !session.getAttribute("is_login").equals("1")) {
    response.sendRedirect("http://domain.com/login");
    return;
}

Note that Use of redirection may vary based on the requirements. Nowadays people don't use such authentication system. (Modern approach - Token Based Authentication) It's just an simple example to understand where and how to place redirection(s).

Array from dictionary keys in swift

This answer will be for swift dictionary w/ String keys. Like this one below.

let dict: [String: Int] = ["hey": 1, "yo": 2, "sup": 3, "hello": 4, "whassup": 5]

Here's the extension I'll use.

extension Dictionary {
  func allKeys() -> [String] {
    guard self.keys.first is String else {
      debugPrint("This function will not return other hashable types. (Only strings)")
      return []
    }
    return self.flatMap { (anEntry) -> String? in
                          guard let temp = anEntry.key as? String else { return nil }
                          return temp }
  }
}

And I'll get all the keys later using this.

let componentsArray = dict.allKeys()

MySQL - select data from database between two dates

Have you tried before and after rather than >= and <=? Also, is this a date or a timestamp?

Python Pandas Error tokenizing data

I had a similar case as this and setting

train = pd.read_csv('input.csv' , encoding='latin1',engine='python') 

worked

How to escape single quotes in MySQL

There is another way to do this which may or may not be safer, depending upon your perspective. It requires MySQL 5.6 or later because of the use of a specific string function: FROM_BASE64.

Let's say you have this message you'd like to insert:

"Ah," Nearly Headless Nick waved an elegant hand, "a matter of no importance. . . . It's not as though I really wanted to join. . . . Thought I'd apply, but apparently I 'don't fulfill requirements' -"

That quote has a bunch of single- and double-quotes and would be a real pain to insert into MySQL. If you are inserting that from a program, it's easy to escape the quotes, etc. But, if you have to put that into a SQL script, you'll have to edit the text (to escape the quotes) which could be error prone or sensitive to word-wrapping, etc.

Instead, you can Base64-encode the text, so you have a "clean" string:

SWtGb0xDSWdUbVZoY214NUlFaGxZV1JzWlhOeklFNXBZMnNnZD JGMlpXUWdZVzRnWld4bFoyRnVkQ0JvWVc1a0xDQWlZU0J0WVhS MFpYCklnYjJZZ2JtOGdhVzF3YjNKMFlXNWpaUzRnTGlBdUlDNG dTWFFuY3lCdWIzUWdZWE1nZEdodmRXZG9JRWtnY21WaGJHeDVJ SGRoYm5SbApaQ0IwYnlCcWIybHVMaUF1SUM0Z0xpQlVhRzkxWj JoMElFa25aQ0JoY0hCc2VTd2dZblYwSUdGd2NHRnlaVzUwYkhr Z1NTQW5aRzl1SjMKUWdablZzWm1sc2JDQnlaWEYxYVhKbGJXVn VkSE1uSUMwaUlBPT0K

Some notes about Base64-encoding:

  1. Base64-encoding is a binary encoding, so you'd better make sure that you get your character set correct when you do the encoding, because MySQL is going to decode the Base64-encoded string into bytes and then interpret those. Be sure base64 and MySQL agree on what the character encoding is (I recommend UTF-8).
  2. I've wrapped the string to 50 columns for readability on Stack Overflow. You can wrap it to any number of columns you want (or not wrap at all) and it will still work.

Now, to load this into MySQL:

INSERT INTO my_table (text) VALUES (FROM_BASE64(' SWtGb0xDSWdUbVZoY214NUlFaGxZV1JzWlhOeklFNXBZMnNnZD JGMlpXUWdZVzRnWld4bFoyRnVkQ0JvWVc1a0xDQWlZU0J0WVhS MFpYCklnYjJZZ2JtOGdhVzF3YjNKMFlXNWpaUzRnTGlBdUlDNG dTWFFuY3lCdWIzUWdZWE1nZEdodmRXZG9JRWtnY21WaGJHeDVJ SGRoYm5SbApaQ0IwYnlCcWIybHVMaUF1SUM0Z0xpQlVhRzkxWj JoMElFa25aQ0JoY0hCc2VTd2dZblYwSUdGd2NHRnlaVzUwYkhr Z1NTQW5aRzl1SjMKUWdablZzWm1sc2JDQnlaWEYxYVhKbGJXVn VkSE1uSUMwaUlBPT0K '));

This will insert without any complaints, and you didn't have to manually-escape any text inside the string.

Laravel migration default value

Might be a little too late to the party, but hope this helps someone with similar issue.

The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.

Let me illustrate with an example.

This line means Laravel is generating a new Book instance, as specified in your model. The new Book object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.

$book = new Book();

Now the following lines are setting up the values of each property of the Book object. Same still, nothing is written on the database yet.

$book->author = 'Test'
$book->title = 'Test'

This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).

$book->save();

And thus, the default value will not pop up before you save it to the database.

But, that is not enough. If you try to access $book->price, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.

So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the

Book::find($book->id);

Or, a more sophisticated way by refreshing the instance

$book->refresh();

And then, the next time you try to access the object, it will be filled with the default values.

What's the difference between django OneToOneField and ForeignKey?

Also OneToOneField is useful to be used as primary key to avoid key duplication. One may do not have implicit / explicit autofield

models.AutoField(primary_key=True)

but use OneToOneField as primary key instead (imagine UserProfile model for example):

user = models.OneToOneField(
    User, null=False, primary_key=True, verbose_name='Member profile')

How to correctly use the extern keyword in C

If each file in your program is first compiled to an object file, then the object files are linked together, you need extern. It tells the compiler "This function exists, but the code for it is somewhere else. Don't panic."

Command line input in Python

Start your script with the following line. The script will first run and then you will get the python command prompt. At this point all variables and functions will be available for interactive use and invocations.

#!/usr/bin/env python -i

What is the correct way to write HTML using Javascript?

Perhaps a good idea is to use jQuery in this case. It provides handy functionality and you can do things like this:

$('div').html('<b>Test</b>');

Take a look at http://docs.jquery.com/Attributes/html#val for more information.

Converting an integer to a hexadecimal string in Ruby

Just in case you have a preference for how negative numbers are formatted:

p "%x" % -1   #=> "..f"
p -1.to_s(16) #=> "-1"

How to set the component size with GridLayout? Is there a better way?

Don't use GridLayout for something it wasn't meant to do. It sounds to me like GridBagLayout would be a better fit for you, either that or MigLayout (though you'll have to download that first since it's not part of standard Java). Either that or combine layout managers such as BoxLayout for the lines and GridLayout to hold all the rows.

For example, using GridBagLayout:

import java.awt.*;
import javax.swing.*;

public class LayoutEg1 extends JPanel{
    private static final int ROWS = 10;

    public LayoutEg1() {
        setLayout(new GridBagLayout());
        for (int i = 0; i < ROWS; i++) {
            GridBagConstraints gbc = makeGbc(0, i);
            JLabel label = new JLabel("Row Label " + (i + 1));
            add(label, gbc);

            JPanel panel = new JPanel();
            panel.add(new JCheckBox("check box"));
            panel.add(new JTextField(10));
            panel.add(new JButton("Button"));
            panel.setBorder(BorderFactory.createEtchedBorder());
            gbc = makeGbc(1, i);
            add(panel, gbc);
        }
    }

    private GridBagConstraints makeGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.weightx = x;
        gbc.weighty = 1.0;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = (x == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        return gbc;
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("Layout Eg1");
        frame.getContentPane().add(new LayoutEg1());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

Check if a parameter is null or empty in a stored procedure

To check if variable is null or empty use this

IF(@PreviousStartDate IS NULL OR @PreviousStartDate = '')

Setting transparent images background in IrfanView

You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.

You just need to re-open the image with IrfanView after changing the view color to white.

To change the viewing color in Irfanview go to:

Options > Properties/Settings > Viewing > Main window color

How to check if ZooKeeper is running or up from command prompt?

Zookeeper is just a Java process and when you start a Zookeeper instance it runs a org.apache.zookeeper.server.quorum.QuorumPeerMain class. So you can check for a running Zookeeper like this:

jps -l | grep zookeeper

or even like this:

jps | grep Quorum

upd:

regarding this: will hostname be the hostname of my box?? - the answer is yes.

SQL to search objects, including stored procedures, in Oracle

I'm not sure I quite understand the question but if you want to search objects on the database for a particular search string try:

SELECT owner, name, type, line, text 
FROM dba_source
WHERE instr(UPPER(text), UPPER(:srch_str)) > 0;

From there if you need any more info you can just look up the object / line number.

Textarea to resize based on content length

Use this function:

function adjustHeight(el){
    el.style.height = (el.scrollHeight > el.clientHeight) ? (el.scrollHeight)+"px" : "60px";
}

Use this html:

<textarea onkeyup="adjustHeight(this)"></textarea>

And finally use this css:

textarea {
min-height: 60px;
overflow-y: auto;
word-wrap:break-word
}

The solution simply is letting the scrollbar appears to detect that height needs to be adjusted, and whenever the scrollbar appears in your text area, it adjusts the height just as much as to hide the scrollbar again.

Why does Google prepend while(1); to their JSON responses?

This is to ensure some other site can't do nasty tricks to try to steal your data. For example, by replacing the array constructor, then including this JSON URL via a <script> tag, a malicious third-party site could steal the data from the JSON response. By putting a while(1); at the start, the script will hang instead.

A same-site request using XHR and a separate JSON parser, on the other hand, can easily ignore the while(1); prefix.

Volatile vs Static in Java

In simple terms,

  1. static : static variables are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory

  2. volatile: This keyword is applicable to both class and instance variables.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads

Have a look at this article by Javin Paul to understand volatile variables in a better way.

enter image description here

In absence of volatile keyword, the value of variable in each thread's stack may be different. By making the variable as volatile, all threads will get same value in their working memory and memory consistency errors have been avoided.

Here the term variable can be either static (class) variable or instance (object) variable.

Regarding your query :

Anyway a static variable value is also going to be one value for all threads, then why should we go for volatile?

If I need instance variable in my application, I can't use static variable. Even in case of static variable, consistency is not guaranteed due to Thread cache as shown in the diagram.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.

What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change => memory consistency errors are still possible with volatile variables. To avoid side effects, you have to use synchronized variables. But there is a better solution in java.

Using simple atomic variable access is more efficient than accessing these variables through synchronized code

Some of the classes in the java.util.concurrent package provide atomic methods that do not rely on synchronization.

Refer to this high level concurrency control article for more details.

Especially have a look at Atomic variables.

Related SE questions:

Volatile Vs Atomic

Volatile boolean vs AtomicBoolean

Difference between volatile and synchronized in Java

Default Xmxsize in Java 8 (max heap size)

On my Ubuntu VM, with 1048 MB total RAM, java -XX:+PrintFlagsFinal -version | grep HeapSize printed : uintx MaxHeapSize := 266338304, which is approx 266MB and is 1/4th of my total RAM.

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

Using scanner.nextLine()

I think your problem is that

int selection = scanner.nextInt();

reads just the number, not the end of line or anything after the number. When you declare

String sentence = scanner.nextLine();

This reads the remainder of the line with the number on it (with nothing after the number I suspect)

Try placing a scanner.nextLine(); after each nextInt() if you intend to ignore the rest of the line.

Change default icon

you should put your icon on the project folder, before build it

What is the height of Navigation Bar in iOS 7?

There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.

Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/

Find most frequent value in SQL column

If you can't use LIMIT or LIMIT is not an option for your query tool. You can use "ROWNUM" instead, but you will need a sub query:

SELECT FIELD_1, ALIAS1
FROM(SELECT FIELD_1, COUNT(FIELD_1) ALIAS1
    FROM TABLENAME
    GROUP BY FIELD_1
    ORDER BY COUNT(FIELD_1) DESC)
WHERE ROWNUM = 1

jQuery - on change input text

I recently was wondering why my code doesn't work, then I realized, I need to setup the event handlers as soon as the document is loaded, otherwise when browser loads the code line by line, it loads the JavaScript, but it does not yet have the element to assign the event handler to it. with your example, it should be like this:

$(document).ready(function(){
     $("#kat").change(function(){ 
         alert("Hello");
     });
});

TypeScript and React - children type?

A React Node is one of the following types:

  • Boolean (which is ignored)
  • null or undefined (which is ignored)
  • Number
  • String
  • A React element (result of JSX)
  • An array of any of the above, possibly a nested one

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

How to do tag wrapping in VS code?

A quick search on the VSCode marketplace: https://marketplace.visualstudio.com/items/bradgashler.htmltagwrap.

  1. Launch VS Code Quick Open (Ctrl+P)

  2. paste ext install htmltagwrap and enter

  3. select HTML

  4. press Alt + W (Option + W for Mac).

Trying to check if username already exists in MySQL database using PHP

change your query to like.

$username = mysql_real_escape_string($username); // escape string before passing it to query.
$query = mysql_query("SELECT username FROM Users WHERE username='".$username."'");

However, MySQL is deprecated. You should instead use MySQLi or PDO

How to convert a string of bytes into an int?

As mentioned above using unpack function of struct is a good way. If you want to implement your own function there is an another solution:

def bytes_to_int(bytes):
    result = 0
    for b in bytes:
        result = result * 256 + int(b)
return result

Finding the next available id in MySQL

One way to do it is to set the index to be auto incrementing. Then your SQL statement simply specifies NULL and then SQL parser does the rest for you.

INSERT INTO foo VALUES (null);

How to execute a remote command over ssh with arguments?

Reviving an old thread, but this pretty clean approach was not listed.

function mycommand() {
    ssh [email protected] <<+
    cd testdir;./test.sh "$1"
+
}

Using margin:auto to vertically-align a div

Using Flexbox:

HTML:

<div class="container">
  <img src="http://lorempixel.com/400/200" />
</div>

CSS:

.container {
  height: 500px;
  display: flex;
  justify-content: center; /* horizontal center */
  align-items: center;     /* vertical center */
}

View result

Carousel with Thumbnails in Bootstrap 3.0

  1. Use the carousel's indicators to display thumbnails.
  2. Position the thumbnails outside of the main carousel with CSS.
  3. Set the maximum height of the indicators to not be larger than the thumbnails.
  4. Whenever the carousel has slid, update the position of the indicators, positioning the active indicator in the middle of the indicators.

I'm using this on my site (for example here), but I'm using some extra stuff to do lazy loading, meaning extracting the code isn't as straightforward as I would like it to be for putting it in a fiddle.

Also, my templating engine is smarty, but I'm sure you get the idea.

The meat...

Updating the indicators:

<ol class="carousel-indicators">
    {assign var='walker' value=0}
    {foreach from=$item["imagearray"] key="key" item="value"}
        <li data-target="#myCarousel" data-slide-to="{$walker}"{if $walker == 0} class="active"{/if}>
            <img src='http://farm{$value["farm"]}.static.flickr.com/{$value["server"]}/{$value["id"]}_{$value["secret"]}_s.jpg'>
        </li>

        {assign var='walker' value=1 + $walker}
    {/foreach}
</ol>

Changing the CSS related to the indicators:

.carousel-indicators {
    bottom:-50px;
    height: 36px;
    overflow-x: hidden;
    white-space: nowrap;
}

.carousel-indicators li {
    text-indent: 0;
    width: 34px !important;
    height: 34px !important;
    border-radius: 0;
}

.carousel-indicators li img {
    width: 32px;
    height: 32px;
    opacity: 0.5;
}

.carousel-indicators li:hover img, .carousel-indicators li.active img {
    opacity: 1;
}

.carousel-indicators .active {
    border-color: #337ab7;
}

When the carousel has slid, update the list of thumbnails:

$('#myCarousel').on('slid.bs.carousel', function() {
    var widthEstimate = -1 * $(".carousel-indicators li:first").position().left + $(".carousel-indicators li:last").position().left + $(".carousel-indicators li:last").width(); 
    var newIndicatorPosition = $(".carousel-indicators li.active").position().left + $(".carousel-indicators li.active").width() / 2;
    var toScroll = newIndicatorPosition + indicatorPosition;
    var adjustedScroll = toScroll - ($(".carousel-indicators").width() / 2);
    if (adjustedScroll < 0)
        adjustedScroll = 0;

    if (adjustedScroll > widthEstimate - $(".carousel-indicators").width())
        adjustedScroll = widthEstimate - $(".carousel-indicators").width();

    $('.carousel-indicators').animate({ scrollLeft: adjustedScroll }, 800);

    indicatorPosition = adjustedScroll;
});

And, when your page loads, set the initial scroll position of the thumbnails:

var indicatorPosition = 0;

What's a Good Javascript Time Picker?

I wasn't happy with any of the suggested time pickers, so I created my own with inspiration from Perifer's and the HTML5 spec:

http://github.com/gregersrygg/jquery.timeInput

You can either use the new html5 attributes for time input (step, min, max), or use an options object:

<input type="time" name="myTime" class="time-mm-hh" min="9:00" max="18:00" step="1800" />
<input type="time" name="myTime2" class="time-mm-hh" />

<script type="text/javascript">
    $("input[name='myTime']").timeInput(); // use default or html5 attributes
    $("input[name='myTime2']").timeInput({min: "6:00", max: "15:00", step: 900}); // 15 min intervals from 6:00 am to 3:00 pm
</script>

Validates input like this:

  • Insert ":" if missing
  • Not valid time? Replace with blank
  • Not a valid time according to step? Round up/down to closest step

The HTML5 spec doesn't allow am/pm or localized time syntax, so it only allowes the format hh:mm. Seconds is allowed according to spec, but I have not implemented it yet.

It's very "alpha", so there might be some bugs. Feel free to send me patches/pull requests. Have manually tested in IE 6&8, FF, Chrome and Opera (Latest stable on Linux for the latter ones).

Finding the indices of matching elements in list in Python

You are using .index() which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0) will always return 2, no matter how many times 1.0 occurs in the list.

Use enumerate() to add indices to your loop instead:

def find(lst, a, b):
    result = []
    for i, x in enumerate(lst):
        if x<a or x>b:
            result.append(i)
    return result

You can collapse this into a list comprehension:

def find(lst, a, b):
    return [i for i, x in enumerate(lst) if x<a or x>b]

Gaussian fit for Python

Here is corrected code:

import pylab as plb
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp

x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])

n = len(x)                          #the number of data
mean = sum(x*y)/n                   #note this correction
sigma = sum(y*(x-mean)**2)/n        #note this correction

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])

plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

result:
enter image description here

Detecting which UIButton was pressed in a UITableView

It's simple; make a custom cell and take a outlet of button

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
         NSString *identifier = @"identifier";
        customCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    cell.yourButton.tag = indexPath.Row;

- (void)buttonPressedAction:(id)sender

change id in above method to (UIButton *)

You can get the value that which button is being tapped by doing sender.tag.

How can I add a background thread to flask?

Your additional threads must be initiated from the same app that is called by the WSGI server.

The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.

import threading
import atexit
from flask import Flask

POOL_TIME = 5 #Seconds

# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()

def create_app():
    app = Flask(__name__)

    def interrupt():
        global yourThread
        yourThread.cancel()

    def doStuff():
        global commonDataStruct
        global yourThread
        with dataLock:
        # Do your stuff with commonDataStruct Here

        # Set the next thread to happen
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()   

    def doStuffStart():
        # Do initialisation stuff here
        global yourThread
        # Create your thread
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()

    # Initiate
    doStuffStart()
    # When you kill Flask (SIGTERM), clear the trigger for the next thread
    atexit.register(interrupt)
    return app

app = create_app()          

Call it from Gunicorn with something like this:

gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app

Sort columns of a dataframe by column name

  test[,sort(names(test))]

sort on names of columns can work easily.

How do I convert from stringstream to string in C++?

Use the .str()-method:

Manages the contents of the underlying string object.

1) Returns a copy of the underlying string as if by calling rdbuf()->str().

2) Replaces the contents of the underlying string as if by calling rdbuf()->str(new_str)...

Notes

The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer...

Remove rows with all or some NAs (missing values) in data.frame

I am a synthesizer:). Here I combined the answers into one function:

#' keep rows that have a certain number (range) of NAs anywhere/somewhere and delete others
#' @param df a data frame
#' @param col restrict to the columns where you would like to search for NA; eg, 3, c(3), 2:5, "place", c("place","age")
#' \cr default is NULL, search for all columns
#' @param n integer or vector, 0, c(3,5), number/range of NAs allowed.
#' \cr If a number, the exact number of NAs kept
#' \cr Range includes both ends 3<=n<=5
#' \cr Range could be -Inf, Inf
#' @return returns a new df with rows that have NA(s) removed
#' @export
ez.na.keep = function(df, col=NULL, n=0){
    if (!is.null(col)) {
        # R converts a single row/col to a vector if the parameter col has only one col
        # see https://radfordneal.wordpress.com/2008/08/20/design-flaws-in-r-2-%E2%80%94-dropped-dimensions/#comments
        df.temp = df[,col,drop=FALSE]
    } else {
        df.temp = df
    }

    if (length(n)==1){
        if (n==0) {
            # simply call complete.cases which might be faster
            result = df[complete.cases(df.temp),]
        } else {
            # credit: http://stackoverflow.com/a/30461945/2292993
            log <- apply(df.temp, 2, is.na)
            logindex <- apply(log, 1, function(x) sum(x) == n)
            result = df[logindex, ]
        }
    }

    if (length(n)==2){
        min = n[1]; max = n[2]
        log <- apply(df.temp, 2, is.na)
        logindex <- apply(log, 1, function(x) {sum(x) >= min && sum(x) <= max})
        result = df[logindex, ]
    }

    return(result)
}

How to use JQuery with ReactJS

Step 1:

npm install jquery

Step 2:

touch loader.js 

Somewhere in your project folder

Step 3:

//loader.js
window.$ = window.jQuery = require('jquery')

Step 4:

Import the loader into your root file before you import the files which require jQuery

//App.js
import '<pathToYourLoader>/loader.js'

Step 5:

Now use jQuery anywhere in your code:

//SomeReact.js
class SomeClass extends React.Compontent {

...

handleClick = () => {
   $('.accor > .head').on('click', function(){
      $('.accor > .body').slideUp();
      $(this).next().slideDown();
   });
}

...

export default SomeClass

How to get the second column from command output?

You don't need awk for that. Using read in Bash shell should be enough, e.g.

some_command | while read c1 c2; do echo $c2; done

or:

while read c1 c2; do echo $c2; done < in.txt

PostgreSQL Exception Handling

To catch the error message and its code:

do $$       
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    raise notice 'The transaction is in an uncommittable state. '
                 'Transaction was rolled back';

    raise notice '% %', SQLERRM, SQLSTATE;

end; $$ 
language 'plpgsql';

Haven't found the line number yet

UPDATE April, 16, 2019

As suggested by Diego Scaravaggi, for Postgres 9.2 and up, use GET STACKED DIAGNOSTICS:

do language plpgsql $$
declare
    v_state   TEXT;
    v_msg     TEXT;
    v_detail  TEXT;
    v_hint    TEXT;
    v_context TEXT;
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    get stacked diagnostics
        v_state   = returned_sqlstate,
        v_msg     = message_text,
        v_detail  = pg_exception_detail,
        v_hint    = pg_exception_hint,
        v_context = pg_exception_context;

    raise notice E'Got exception:
        state  : %
        message: %
        detail : %
        hint   : %
        context: %', v_state, v_msg, v_detail, v_hint, v_context;

    raise notice E'Got exception:
        SQLSTATE: % 
        SQLERRM: %', SQLSTATE, SQLERRM;     

    raise notice '%', message_text; -- invalid. message_text is contextual to GET STACKED DIAGNOSTICS only

end; $$;

Result:

NOTICE:  Got exception:
        state  : 42P07
        message: relation "yyy" already exists
        detail : 
        hint   : 
        context: SQL statement "create table yyy(a int)"
PL/pgSQL function inline_code_block line 11 at SQL statement
NOTICE:  Got exception:
        SQLSTATE: 42P07 
        SQLERRM: relation "yyy" already exists

ERROR:  column "message_text" does not exist
LINE 1: SELECT message_text
               ^
QUERY:  SELECT message_text
CONTEXT:  PL/pgSQL function inline_code_block line 33 at RAISE
SQL state: 42703

Aside from GET STACKED DIAGNOSTICS is SQL standard-compliant, its diagnostics variables (e.g., message_text) are contextual to GSD only. So if you have a field named message_text in your table, there's no chance that GSD can interfere with your field's value.

Still no line number though.

What is the use of printStackTrace() method in Java?

printStackTrace() helps the programmer to understand where the actual problem occurred. printStacktrace() is a method of the class Throwable of java.lang package. It prints several lines in the output console. The first line consists of several strings. It contains the name of the Throwable sub-class & the package information. From second line onwards, it describes the error position/line number beginning with at.

The last line always describes the destination affected by the error/exception. The second last line informs us about the next line in the stack where the control goes after getting transfer from the line number described in the last line. The errors/exceptions represents the output in the form a stack, which were fed into the stack by fillInStackTrace() method of Throwable class, which itself fills in the program control transfer details into the execution stack. The lines starting with at, are nothing but the values of the execution stack. In this way the programmer can understand where in code the actual problem is.

Along with the printStackTrace() method, it's a good idea to use e.getmessage().

What does -Xmn jvm option stands for

From here:

-Xmn : the size of the heap for the young generation

Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".

And a more "official" source from IBM:

-Xmn

Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.

Compiling php with curl, where is curl installed?

None of these will allow you to compile PHP with cURL enabled.

In order to compile with cURL, you need libcurl header files (.h files). They are usually found in /usr/include/curl. They generally are bundled in a separate development package.

Per example, to install libcurl in Ubuntu:

sudo apt-get install libcurl4-gnutls-dev

Or CentOS:

sudo yum install curl-devel

Then you can just do:

./configure --with-curl # other options...

If you compile cURL manually, you can specify the path to the files without the lib or include suffix. (e.g.: /usr/local if cURL headers are in /usr/local/include/curl).

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

As mentioned above the following would solve the problem: mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

However in my case the provider did this [0..1] or [0..*] serialization rather as a bug and I could not enforce fixing. On the other hand it did not want to impact my strict mapper for all other cases which needs to be validated strictly.

So I did a Jackson NASTY HACK (which should not be copied in general ;-) ), especially because my SingleOrListElement had only few properties to patch:

@JsonProperty(value = "SingleOrListElement", access = JsonProperty.Access.WRITE_ONLY)
private Object singleOrListElement; 

public List<SingleOrListElement> patch(Object singleOrListElement) {
  if (singleOrListElement instanceof List) {
    return (ArrayList<SingleOrListElement>) singleOrListElement;
  } else {
    LinkedHashMap map = (LinkedHashMap) singleOrListElement;
    return Collections.singletonList(SingletonList.builder()
                            .property1((String) map.get("p1"))
                            .property2((Integer) map.get("p2"))
                            .build());
  }

Seeing the underlying SQL in the Spring JdbcTemplate?

Try adding in log4j.xml

<!--  enable query logging -->
<category name="org.springframework.jdbc.core.JdbcTemplate">
    <priority value="DEBUG" />
</category>

<!-- enable query logging for SQL statement parameter value -->
<category name="org.springframework.jdbc.core.StatementCreatorUtils">
    <priority value="TRACE" />
</category>

your logs looks like:

DEBUG JdbcTemplate:682 - Executing prepared SQL query
DEBUG JdbcTemplate:616 - Executing prepared SQL statement [your sql query]
TRACE StatementCreatorUtils:228 - Setting SQL statement parameter value: column index 1, parameter value [param], value class [java.lang.String], SQL type unknown

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

Rather than creating empty directories in source to exclude, you can supply the full destination path to the /XD switch to have the destination directories untouched

robocopy "%SOURCE_PATH%" "%DEST_PATH%" /MIR /XD "%DEST_PATH%"\hq04s2dba301

How to get pip to work behind a proxy server

At least for pip 1.3.1, it honors the http_proxy and https_proxy environment variables. Make sure you define both, as it will access the PYPI index using https.

export https_proxy="http://<proxy.server>:<port>"
pip install TwitterApi

Load CSV data into MySQL in Python

I think you have to do mydb.commit() all the insert into.

Something like this

import csv
import MySQLdb

mydb = MySQLdb.connect(host='localhost',
    user='root',
    passwd='',
    db='mydb')
cursor = mydb.cursor()

csv_data = csv.reader(file('students.csv'))
for row in csv_data:

    cursor.execute('INSERT INTO testcsv(names, \
          classes, mark )' \
          'VALUES("%s", "%s", "%s")', 
          row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"

How is Java platform-independent when it needs a JVM to run?

Doesn't independent means that Java code should be able to run on any machine and would need no special software to be installed (JVM in this case has to be present in the machine)?

With Java, you can compile source code on Windows and the compiled code (bytecode to be precise) can be executed (interpreted) on any platform running a JVM. So yes you need a JVM but the JVM can run any compiled code, the compiled code is platform independent.

In other words, you have both portability of source code and portability of compiled code.

Like, for example, we need to have Turbo C Compiler in order to compile C/C++ source code and then execute it.. The machine has to have the C compiler.

The machine doesn't have to have a C compiler, the machine has to use a platform specific binary. With C or C++, the compiled code is specific to each architecture, it is platform independent.

In other words, with C / C++ you have portability of source code (with some discipline) but not portability of compiled code: you need to recompile for each architecture into platform specific binaries.

Python read in string from file and split it into values

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456

Now you can do what is necessary with x and y as assigned, which are integers.

AttributeError: 'numpy.ndarray' object has no attribute 'append'

I got this error after change a loop in my program, let`s see:

for ...
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:

for ...
  x_batch = []
  y_batch = []
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

Then, check if you are using np.asarray() or something like that.

Running Jupyter via command line on Windows

first you should make sure that you are put your python path in your system variables .. Then try run this

python -m pip install jupyter --user

and then run this

py -m notebook or  jupyter notebook

How to add users to Docker container?

Alternatively you can do like this.

RUN addgroup demo && adduser -DH -G demo demo

First command creates group called demo. Second command creates demo user and adds him to previously created demo group.

Flags stands for:

-G Group
-D Don't assign password
-H Don't create home directory

Android Shared preferences for creating one time activity (example)

public class Preferences {

public static final String PREF_NAME = "your preferences name";

@SuppressWarnings("deprecation")
public static final int MODE = Context.MODE_WORLD_WRITEABLE;

public static final String USER_ID = "USER_ID_NEW";
public static final String USER_NAME = "USER_NAME";

public static final String NAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String PHONE = "PHONE";
public static final String address = "address";

public static void writeBoolean(Context context, String key, boolean value) {
    getEditor(context).putBoolean(key, value).commit();
}

public static boolean readBoolean(Context context, String key,
        boolean defValue) {
    return getPreferences(context).getBoolean(key, defValue);
}

public static void writeInteger(Context context, String key, int value) {
    getEditor(context).putInt(key, value).commit();

}

public static int readInteger(Context context, String key, int defValue) {
    return getPreferences(context).getInt(key, defValue);
}

public static void writeString(Context context, String key, String value) {
    getEditor(context).putString(key, value).commit();

}

public static String readString(Context context, String key, String defValue) {
    return getPreferences(context).getString(key, defValue);
}

public static void writeFloat(Context context, String key, float value) {
    getEditor(context).putFloat(key, value).commit();
}

public static float readFloat(Context context, String key, float defValue) {
    return getPreferences(context).getFloat(key, defValue);
}

public static void writeLong(Context context, String key, long value) {
    getEditor(context).putLong(key, value).commit();
}

public static long readLong(Context context, String key, long defValue) {
    return getPreferences(context).getLong(key, defValue);
}

public static SharedPreferences getPreferences(Context context) {
    return context.getSharedPreferences(PREF_NAME, MODE);
}

public static Editor getEditor(Context context) {
    return getPreferences(context).edit();
}

}

****Use Preferences to Write value using:-****

Preferences.writeString(getApplicationContext(),
                    Preferences.NAME, "dev");

****Use Preferences to Read value using:-****

Preferences.readString(getApplicationContext(), Preferences.NAME,
                    "");

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

How to get named excel sheets while exporting from SSRS

The Rectangle method

The simplest and most reliable way I've found of achieving worksheets/page-breaks is with use of the rectangle tool.

Group your page within rectangles or a single rectangle that fills the page in a sub-report, as follows:

  • The quickest way I've found of placing the rectangle is to draw it around the objects you wish to place in the rectangle.

  • Right click and in the layout menu, send the rectangle to back.

  • Select all your objects and drag them slightly, but be sure they land in the same place they were. They will all now be in the rectangle.

In the rectangle properties you can set the page-break to occur at the start or end of the rectangle and name of the page can be based on an expression.

The worksheets will be named the same as the name of the page.

Duplicate names will have a number in brackets suffix.

Note: Ensure that the names are valid worksheet names.

How to store .pdf files into MySQL as BLOBs using PHP?

In regards to Gordon M's answer above, the 1st and 2nd parameter in mysqli_real_escape_string () call should be swapped for the newer php versions, according to: http://php.net/manual/en/mysqli.real-escape-string.php

Android new Bottom Navigation bar or BottomNavigationView

I think this is also be useful.

Snippet

public class MainActivity : AppCompatActivity, BottomNavigationBar.Listeners.IOnTabSelectedListener
{
    private BottomBar _bottomBar;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.MainActivity);

        _bottomBar = BottomBar.Attach(this, bundle);
        _bottomBar.SetItems(
            new BottomBarTab(Resource.Drawable.ic_recents, "Recents"),
            new BottomBarTab(Resource.Drawable.ic_favorites, "Favorites"),
            new BottomBarTab(Resource.Drawable.ic_nearby, "Nearby")
        );
        _bottomBar.SetOnItemSelectedListener(this);
        _bottomBar.HideShadow();
        _bottomBar.UseDarkTheme(true);
        _bottomBar.SetTypeFace("Roboto-Regular.ttf");

        var badge = _bottomBar.MakeBadgeForTabAt(1, Color.ParseColor("#f02d4c"), 1);
        badge.AutoShowAfterUnSelection = true;
    }

    public void OnItemSelected(int position)
    {

    }

    protected override void OnSaveInstanceState(Bundle outState)
    {
        base.OnSaveInstanceState(outState);

        // Necessary to restore the BottomBar's state, otherwise we would
        // lose the current tab on orientation change.
        _bottomBar.OnSaveInstanceState(outState);
    }
}

Links

https://github.com/pocheshire/BottomNavigationBar

It's https://github.com/roughike/BottomBar ported to C# for Xamarin developers

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

  1. Open File Menu > Project Structure > Module > Select Dependency > +
  2. Select one from given option
    • Jar
    • Library
    • Module dependency
  3. Apply + Ok
  4. Import into java class

How to get a variable from a file to another file in Node.js

You need module.exports:

Exports

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

module.exports = { variableName: "variableValue" };

Or you can set the individual value with:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

Alternatively, you can deconstruct it.

const { variableName } = require('./sourceFile');
//            current directory --^
// ../     would be one directory down
// ../../  is two directories down

If all you want out of the file is variableName then

./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js:

const variableName = require('./sourceFile')

Edit (2020):

Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.

  • For Node v13.9.0 and beyond, experimental modules are enabled by default
  • For versions of Node less than version 13.9.0, use --experimental-modules

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .mjs.
  • Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.

Once you have it setup, you can use import and export.

Using the example above, there are two approaches you can take

./sourceFile.js:

// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default. 
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary. 
// You can actually omit declaring what variableName is here. 
// { variableName } is equivalent to { variableName: variableName } in this case. 
export default { variableName: variableName } 

./consumer.js:

// There are three ways of importing. 
// If you need access to a non-default export, then 
// you use { nameOfExportedVariable } 
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'

// Otherwise, you simply provide a local variable name 
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'

./sourceFileWithoutDefault.js:

// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'

./consumer2.js

// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'

console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'

// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'

// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }

// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue

JS how to cache a variable

You have three options:

  1. Cookies: https://developer.mozilla.org/en-US/docs/DOM/document.cookie
  2. DOMStorage (sessionStorage or localStorage): https://developer.mozilla.org/en-US/docs/DOM/Storage
  3. If your users are logged in, you could persist data in your server's DB that is keyed to a user (or group)

How to use youtube-dl from a python program?

Here is a way.

We set-up options' string, in a list, just as we set-up command line arguments. In this case opts=['-g', 'videoID']. Then, invoke youtube_dl.main(opts). In this way, we write our custom .py module, import youtube_dl and then invoke the main() function.

How to auto-format code in Eclipse?

Also note that you can also "protect" a block from being formatted with @formatter:off and @formatter:on, avoiding a reformat on a comment for example, like in:

// Master dataframe
Dataset<Row> countyStateDf = df
    .withColumn(
        "countyState",
        split(df.col("label"), ", "));

// I could split the column in one operation if I wanted:
// @formatter:off
//    Dataset<Row> countyState0Df = df
//        .withColumn(
//            "state",
//            split(df.col("label"), ", ").getItem(1))
//        .withColumn(
//            "county",
//            split(df.col("label"), ", ").getItem(0));
// @formatter:on

countyStateDf.sample(.01).show(5, false);

How to convert Set<String> to String[]?

Set<String> stringSet= new HashSet<>();
String[] s = (String[])stringSet.toArray();

Injecting Mockito mocks into a Spring bean

Today I found out that a spring context where I declared a before the Mockito beans, was failing to load. After moving the AFTER the mocks, the app context was loaded successfully. Take care :)

ORA-01036: illegal variable name/number when running query through C#

The Oracle error ORA-01036 means that the query uses an undefined variable somewhere. From the query we can determine which variables are in use, namely all that start with @. However, if you're inputting this into an advanced query, it's important to confirm that all variables have a matching input parameter, including the same case as in the variable name, if your Oracle database is Case Sensitive.

Removing single-quote from a string in php

Using your current str_replace method:

$FileName = str_replace("'", "", $UserInput);

While it's hard to see, the first argument is a double quote followed by a single quote followed by a double quote. The second argument is two double quotes with nothing in between.

With str_replace, you could even have an array of strings you want to remove entirely:

$remove[] = "'";
$remove[] = '"';
$remove[] = "-"; // just as another example

$FileName = str_replace( $remove, "", $UserInput );

arranging div one below the other

Set the main div CSS to somthing like:

<style>
    .wrapper{
        display:flex;
        flex-direction: column;
    }
</style>

<div id="wrapper">
        <div id="inner1">This is inner div 1</div>
        <div id="inner2">This is inner div 2</div>
</div>

For more flexbox CSS refer: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

What is the best way to manage a user's session in React?

To name a few we can use redux-react-session which is having good API for session management like, initSessionService, refreshFromLocalStorage, checkAuth and many other. It also provide some advanced functionality like Immutable JS.

Alternatively we can leverage react-web-session which provides options like callback and timeout.

How to pass a view's onClick event to its parent on Android?

This answer is similar to Alexander Ukhov's answer, except that it uses touch events rather than click events. Those event allow the parent to display the proper pressed states (e.g., ripple effect). This answer is also in Kotlin instead of Java.

view.setOnTouchListener { view, motionEvent ->
    (view.parent as View).onTouchEvent(motionEvent)
}

Removing a Fragment from the back stack

What happens if the fragment that you want to remove is not on top of the stack?

Then you can use theses functions

popBackStack(int arg0, int arg1);

popBackStack(String arg0, int arg1);

How can I plot with 2 different y-axes?

Another alternative which is similar to the accepted answer by @BenBolker is redefining the coordinates of the existing plot when adding a second set of points.

Here is a minimal example.

Data:

x  <- 1:10
y1 <- rnorm(10, 100, 20)
y2 <- rnorm(10, 1, 1)

Plot:

par(mar=c(5,5,5,5)+0.1, las=1)

plot.new()
plot.window(xlim=range(x), ylim=range(y1))
points(x, y1, col="red", pch=19)
axis(1)
axis(2, col.axis="red")
box()

plot.window(xlim=range(x), ylim=range(y2))
points(x, y2, col="limegreen", pch=19)
axis(4, col.axis="limegreen")

example

Cannot find pkg-config error

Answer to my question (after several Google searches) revealed the following:

$ curl https://pkgconfig.freedesktop.org/releases/pkg-config-0.29.tar.gz -o pkgconfig.tgz
$ tar -zxf pkgconfig.tgz && cd pkg-config-0.29
$ ./configure && make install

from the following link: Link showing above

Thanks to everyone for their comments, and sorry for my linux/OSX ignorance!

Doing this fixed my issues as mentioned above.

Difference between jQuery .hide() and .css("display", "none")

Yes there is a difference.

jQuery('#id').css("display","block") will always set the element you want to show as block.

jQuery('#id').show() will et is to what display type it initially was, display: inline for example.

See Jquery Doc

Recursively add the entire folder to a repository

Scenario / Solution 1:
Ensure your Folder / Sub-folder is not in the .gitignore file, by any chance.


Scenario / Solution 2:
By default, git add . works recursively.


Scenario / Solution 3:
git add --all :/ works smoothly, where git add . doesn't (work).
(@JasonHartley's comment)


Scenario / Solution 4:
The issue I personally faced was adding Subfolders or Files, which were common between multiple Folders.

For example:
Folder/Subfolder-L1/Subfolder-L2/...file12.txt
Folder/Subfolder-L1/Subfolder-L2/Subfolder-L3/...file123.txt
Folder/Subfolder-L1/...file1.txt

So Git was recommending me to add git submodule, which I tried but was a pain.


Finally what worked for me was:

1. git add one file that's at the last end / level of a Folder.
For example:
git add Folder/Subfolder-L1/Subfolder-L2/Subfolder-L3/...file123.txt

2. git add --all :/ now.
It'll very swiftly add all the Folders, Subfolders and files.


How can I get current date in Android?

I am providing the modern answer.

java.time and ThreeTenABP

To get the current date:

    LocalDate today = LocalDate.now(ZoneId.of("America/Hermosillo"));

This gives you a LocalDate object, which is what you should use for keeping a date in your program. A LocalDate is a date without time of day.

Only when you need to display the date to a user, format it into a string suitable for the user’s locale:

    DateTimeFormatter userFormatter
            = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
    System.out.println(today.format(userFormatter));

When I ran this snippet today in US English locale, output was:

July 13, 2019

If you want it shorter, specify FormatStyle.MEDIUM or even FormatStyle.SHORT. DateTimeFormatter.ofLocalizedDate uses the default formatting locale, so the point is that it will give output suitable for that locale, different for different locales.

If your user has very special requirements for the output format, use a format pattern string:

    DateTimeFormatter userFormatter = DateTimeFormatter.ofPattern(
            "d-MMM-u", Locale.forLanguageTag("ar-AE"));

13-???-2019

I am using and recommending java.time, the modern Java date and time API. DateFormat, SimpleDateFormat, Date and Calendar used in the question and/or many of the other answers, are poorly designed and long outdated. And java.time is so much nicer to work with.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

AttributeError: can't set attribute in python

items[node.ind] = items[node.ind]._replace(v=node.v)

(Note: Don't be discouraged to use this solution because of the leading underscore in the function _replace. Specifically for namedtuple some functions have leading underscore which is not for indicating they are meant to be "private")

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

How to start and stop/pause setInterval?

The reason you're seeing this specific problem:

JSFiddle wraps your code in a function, so start() is not defined in the global scope.

enter image description here


Moral of the story: don't use inline event bindings. Use addEventListener/attachEvent.


Other notes:

Please don't pass strings to setTimeout and setInterval. It's eval in disguise.

Use a function instead, and get cozy with var and white space:

_x000D_
_x000D_
var input = document.getElementById("input"),
  add;

function start() {
  add = setInterval(function() {
    input.value++;
  }, 1000);
}

start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />
_x000D_
_x000D_
_x000D_

Sending event when AngularJS finished loading

i observe DOM manipulation of angular with JQuery and i did set a finish for my app (some sort of predefined and satisfactory situation that i need for my app-abstract) for example i expect my ng-repeater to produce 7 result and there for i will set an observation function with the help of setInterval for this purpose .

$(document).ready(function(){

  var interval = setInterval(function(){

  if($("article").size() == 7){
     myFunction();
     clearInterval(interval);
  }

  },50);

});

Python: How to use RegEx in an if statement?

Regex's shouldn't really be used in this fashion - unless you want something more complicated than what you're trying to do - for instance, you could just normalise your content string and comparision string to be:

if 'facebook.com' in content.lower():
    shutil.copy(x, "C:/Users/David/Desktop/Test/MyFiles2")

Rotate label text in seaborn factorplot

You can also use plt.setp as follows:

import matplotlib.pyplot as plt
import seaborn as sns

plot=sns.barplot(data=df,  x=" ", y=" ")
plt.setp(plot.get_xticklabels(), rotation=90)

to rotate the labels 90 degrees.

Difference between using bean id and name in Spring configuration file

Is there difference in defining Id & name in ApplicationContext xml ? No As of 3.1(spring), id is also defined as an xsd:string type. It means whatever characters allowed in defining name are also allowed in Id. This was not possible prior to Spring 3.1.

Why to use name when it is same as Id ? It is useful for some situations, such as allowing each component in an application to refer to a common dependency by using a bean name that is specific to that component itself.

For example, the configuration metadata for subsystem A may refer to a DataSource via the name subsystemA-dataSource. The configuration metadata for subsystem B may refer to a DataSource via the name subsystemB-dataSource. When composing the main application that uses both these subsystems the main application refers to the DataSource via the name myApp-dataSource. To have all three names refer to the same object you add to the MyApp configuration metadata the following 

<bean id="myApp-dataSource" name="subsystemA-dataSource,subsystemB-dataSource" ..../>

Alternatively, You can have separate xml configuration files for each sub-system and then you can make use of
alias to define your own names.

<alias name="subsystemA-dataSource" alias="subsystemB-dataSource"/>
<alias name="subsystemA-dataSource" alias="myApp-dataSource" />

"Field has incomplete type" error

The problem is that your ui property uses a forward declaration of class Ui::MainWindowClass, hence the "incomplete type" error.

Including the header file in which this class is declared will fix the problem.

EDIT

Based on your comment, the following code:

namespace Ui
{
    class MainWindowClass;
}

does NOT declare a class. It's a forward declaration, meaning that the class will exist at some point, at link time.
Basically, it just tells the compiler that the type will exist, and that it shouldn't warn about it.

But the class has to be defined somewhere.

Note this can only work if you have a pointer to such a type.
You can't have a statically allocated instance of an incomplete type.

So either you actually want an incomplete type, and then you should declare your ui member as a pointer:

namespace Ui
{
    // Forward declaration - Class will have to exist at link time
    class MainWindowClass;
}

class MainWindow : public QMainWindow
{
    private:

        // Member needs to be a pointer, as it's an incomplete type
        Ui::MainWindowClass * ui;
};

Or you want a statically allocated instance of Ui::MainWindowClass, and then it needs to be declared. You can do it in another header file (usually, there's one header file per class).
But simply changing the code to:

namespace Ui
{
    // Real class declaration - May/Should be in a specific header file
    class MainWindowClass
    {};
}


class MainWindow : public QMainWindow
{
    private:

        // Member can be statically allocated, as the type is complete
        Ui::MainWindowClass ui;
};

will also work.

Note the difference between the two declarations. First uses a forward declaration, while the second one actually declares the class (here with no properties nor methods).

Bootstrap dropdown not working

You'll have to check conflicting css files/properties for example you could have ".nav" custom style contents elsewhere try to disable your own css files and check if that works then check which file or custom style that makes the conflicts also make sure you are including the bootstrap.min.js in your code

How can I recover a lost commit in Git?

Try this, This will show all commits recorded in git for a period of time

git reflog

Find the commit you want with

git log HEAD@{3}

or

git log -p HEAD@{3}    

Then check it out if it's the right one:

git checkout HEAD@{3}

This will create a detached head for that commit. Add and commit any changes if needed

git status 
git add
git commit -m "temp_work" 

Now if want to restore commit back to a branch lets say master you will need to name this branch switch to master then merge to master.

git branch temp
git checkout master
git merge temp

Here's also a link specifically for reflog on a Git tutorial site: Atlassian Git Tutorial

List the queries running on SQL Server

You should try very usefull procedure sp_whoIsActive which can be found here: http://whoisactive.com and it is free.

Resize image in PHP

I would suggest an easy way:

function resize($file, $width, $height) {
    switch(pathinfo($file)['extension']) {
        case "png": return imagepng(imagescale(imagecreatefrompng($file), $width, $height), $file);
        case "gif": return imagegif(imagescale(imagecreatefromgif($file), $width, $height), $file);
        default : return imagejpeg(imagescale(imagecreatefromjpeg($file), $width, $height), $file);
    }
}

How to convert md5 string to normal text?

I you send passwords to users in an email, you might as well have no passwords at all.

You cannot reverse the MD5 function, so your only option is to generate a new password and send that to the user (preferably over some secure channel).

Add a new item to recyclerview programmatically?

if you are adding multiple items to the list use this:

mAdapter.notifyItemRangeInserted(startPosition, itemcount);

This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount

existing item in the dataset still considered up to date.

What is the iPhone 4 user-agent?

This site seems to keep a complete list that's still maintained

iPhone, iPod Touch, and iPad from iOS 2.0 - 5.1.1 (to date).

You do need to assemble the full user-agent string out of the information listed in the page's columns.

How to import csv file in PHP?

PHP > 5.3 use fgetcsv() or str_getcsv(). Couldn't be simpler.

Passing just a type as a parameter in C#

You can do this, just wrap it in typeof()

foo.GetColumnValues(typeof(int))

public void GetColumnValues(Type type)
{
    //logic
}

Concatenate rows of two dataframes in pandas

call concat and pass param axis=1 to concatenate column-wise:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

There is a useful guide to the various methods of merging, joining and concatenating online.

For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

And for the same reasons as above a simple join works too:

In [7]:

df_a.join(df_b)
Out[7]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

Me too faced the same issue. But the problem was I forgot to list the module in the list of modules the ng-app depends on.

relative path to CSS file

You have to move the css folder into your web folder. It seems that your web folder on the hard drive equals the /ServletApp folder as seen from the www. Other content than inside your web folder cannot be accessed from the browsers.

The url of the CSS link is then

 <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>

Print a variable in hexadecimal in Python

You can try something like this I guess:

new_str = ""
str_value = "rojbasr"
for i in str_value:
    new_str += "0x%s " % (i.encode('hex'))
print new_str

Your output would be something like this:

0x72 0x6f 0x6a 0x62 0x61 0x73 0x72

Android Button setOnClickListener Design

If you're targeting 1.6 or later, you can use the android:onClick xml attribute to remove some of the repetitive code. See this blog post by Romain Guy.

<Button 
   android:height="wrap_content"
   android:width="wrap_content"
   android:onClick="myClickHandler" />

And in the Java class, use these below lines of code:

class MyActivity extends Activity {
    public void myClickHandler(View target) {
        // Do stuff
    }
}

AngularJS - add HTML element to dom in directive without jQuery

You could use something like this

var el = document.createElement("svg");
el.style.width="600px";
el.style.height="100px";
....
iElement[0].appendChild(el)

How to create two columns on a web page?

Basically you need 3 divs. First as wrapper, second as left and third as right.

.wrapper {
 width:500px;
 overflow:hidden;
}

.left {
 width:250px;
 float:left;
}

.right {
 width:250px;
 float:right;
}

Example how to make 2 columns http://jsfiddle.net/huhu/HDGvN/


CSS Cheat Sheet for reference

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

This is simple if you only use Selenium WebDriver, and forget the usage of Selenium-RC. I'd go like this.

WebDriver driver = new FirefoxDriver();
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("[email protected]");

The reason for NullPointerException however is that your variable driver has never been started, you start FirefoxDriver in a variable wb thas is never being used.

How to save username and password in Git?

just use

git config --global credential.helper store

and do the git pull, it will ask for username and password, from now on it will not provide any prompt for username and password it will store the details

How do I set vertical space between list items?

Many times when producing HTML email blasts you cannot use style sheets or style /style blocks. All CSS needs to be inline. In the case where you want to adjust the spacing between the bullets I use li style="margin-bottom:8px;" in each bullet item. Customize the pixels value to your liking.

What is `related_name` used for in Django?

To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material

@with_author 
class BOM(models.Model): 
    name = models.CharField(max_length=200,null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    tomaterial =  models.ForeignKey(Material, related_name = 'tomaterial')
    frommaterial =  models.ForeignKey(Material, related_name = 'frommaterial')
    creation_time = models.DateTimeField(auto_now_add=True, blank=True)
    quantity = models.DecimalField(max_digits=19, decimal_places=10)

So when you will have to access this data you only can use related name

 bom = material.tomaterial.all().order_by('-creation_time')

It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)

Undefined index error PHP

This is happening because your PHP code is getting executed before the form gets posted.

To avoid this wrap your PHP code in following if statement and it will handle the rest no need to set if statements for each variables

       if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST))
        {
             //process PHP Code
        }
        else
        {
             //do nothing
         }

Excel how to fill all selected blank cells with text

If all the cells are under one column, you could just filter the column and then select "(blank)" and then insert any value into the cells. But be careful, press "alt + 4" to make sure you are inserting value into the visible cells only.

How to get parameter on Angular2 route in Angular way?

As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:

private _entityId: number;

constructor(private _route: ActivatedRoute) {
    // ...
}

ngOnInit() {
    // For a static snapshot of the route...
    this._entityId = this._route.snapshot.paramMap.get('id');

    // For subscribing to the observable paramMap...
    this._route.paramMap.pipe(
        switchMap((params: ParamMap) => this._entityId = params.get('id'))
    );

    // Or as an alternative, with slightly different execution...
    this._route.paramMap.subscribe((params: ParamMap) =>  {
        this._entityId = params.get('id');
    });
}

I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.

Source in Angular Docs

Add custom header in HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
    {
        const string WEBSERVICE_URL = "<<Web service URL>>";
        try
        {
            var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
            if (webRequest != null)
            {
                webRequest.Method = "GET";
                webRequest.Timeout = 12000;
                webRequest.ContentType = "application/json";
                webRequest.Headers.Add("Authorization", "Basic dchZ2VudDM6cGFdGVzC5zc3dvmQ=");

                using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                    {
                        var jsonResponse = sr.ReadToEnd();
                        Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

Make browser window blink in task Bar

you could change the title of the web page with each new message to alert the user. I did this for a browser chat client and most users thought it worked well enough.

document.title = "[user] hello world";

TypeError: 'int' object is not callable

Somewhere else in your code you have something that looks like this:

round = 42

Then when you write

round((a/b)*0.9*c)

that is interpreted as meaning a function call on the object bound to round, which is an int. And that fails.

The problem is whatever code binds an int to the name round. Find that and remove it.

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Used to face the same problem. The reason was in incorrect context passing to AlertDialog.Builder(here). use like AlertDialog.Builder(Homeactivity.this)

.NET 4.0 has a new GAC, why?

I also wanted to know why 2 GAC and found the following explanation by Mark Miller in the comments section of .NET 4.0 has 2 Global Assembly Cache (GAC):

Mark Miller said... June 28, 2010 12:13 PM

Thanks for the post. "Interference issues" was intentionally vague. At the time of writing, the issues were still being investigated, but it was clear there were several broken scenarios.

For instance, some applications use Assemby.LoadWithPartialName to load the highest version of an assembly. If the highest version was compiled with v4, then a v2 (3.0 or 3.5) app could not load it, and the app would crash, even if there were a version that would have worked. Originally, we partitioned the GAC under it's original location, but that caused some problems with windows upgrade scenarios. Both of these involved code that had already shipped, so we moved our (version-partitioned GAC to another place.

This shouldn't have any impact to most applications, and doesn't add any maintenance burden. Both locations should only be accessed or modified using the native GAC APIs, which deal with the partitioning as expected. The places where this does surface are through APIs that expose the paths of the GAC such as GetCachePath, or examining the path of mscorlib loaded into managed code.

It's worth noting that we modified GAC locations when we released v2 as well when we introduced architecture as part of the assembly identity. Those added GAC_MSIL, GAC_32, and GAC_64, although all still under %windir%\assembly. Unfortunately, that wasn't an option for this release.

Hope it helps future readers.

When to use MyISAM and InnoDB?

Read about Storage Engines.

MyISAM:

The MyISAM storage engine in MySQL.

  • Simpler to design and create, thus better for beginners. No worries about the foreign relationships between tables.
  • Faster than InnoDB on the whole as a result of the simpler structure thus much less costs of server resources. -- Mostly no longer true.
  • Full-text indexing. -- InnoDB has it now
  • Especially good for read-intensive (select) tables. -- Mostly no longer true.
  • Disk footprint is 2x-3x less than InnoDB's. -- As of Version 5.7, this is perhaps the only real advantage of MyISAM.

InnoDB:

The InnoDB storage engine in MySQL.

  • Support for transactions (giving you support for the ACID property).
  • Row-level locking. Having a more fine grained locking-mechanism gives you higher concurrency compared to, for instance, MyISAM.
  • Foreign key constraints. Allowing you to let the database ensure the integrity of the state of the database, and the relationships between tables.
  • InnoDB is more resistant to table corruption than MyISAM.
  • Support for large buffer pool for both data and indexes. MyISAM key buffer is only for indexes.
  • MyISAM is stagnant; all future enhancements will be in InnoDB. This was made abundantly clear with the roll out of Version 8.0.

MyISAM Limitations:

  • No foreign keys and cascading deletes/updates
  • No transactional integrity (ACID compliance)
  • No rollback abilities
  • 4,284,867,296 row limit (2^32) -- This is old default. The configurable limit (for many versions) has been 2**56 bytes.
  • Maximum of 64 indexes per table

InnoDB Limitations:

  • No full text indexing (Below-5.6 mysql version)
  • Cannot be compressed for fast, read-only (5.5.14 introduced ROW_FORMAT=COMPRESSED)
  • You cannot repair an InnoDB table

For brief understanding read below links:

  1. MySQL Engines: InnoDB vs. MyISAM – A Comparison of Pros and Cons
  2. MySQL Engines: MyISAM vs. InnoDB
  3. What are the main differences between InnoDB and MyISAM?
  4. MyISAM versus InnoDB
  5. What's the difference between MyISAM and InnoDB?
  6. MySql: MyISAM vs. Inno DB!

If Cell Starts with Text String... Formula

As of Excel 2019 you could do this. The "Error" at the end is the default.

SWITCH(LEFT(A1,1), "A", "Pick Up", "B", "Collect", "C", "Prepaid", "Error")

Microsoft Excel Switch Documentation

Are querystring parameters secure in HTTPS (HTTP + SSL)?

The entire transmission, including the query string, the whole URL, and even the type of request (GET, POST, etc.) is encrypted when using HTTPS.

How to add time to DateTime in SQL

Try this

SELECT DATEADD(MINUTE,HOW_MANY_MINUTES,TO_WHICH_TIME)

Here MINUTE is constant which indicates er are going to add/subtract minutes from TO_WHICH_TIME specifier. HOW_MANY_MINUTES is the interval by which we need to add minutes, if it is specified negative, time will be subtracted, else would be added to the TO_WHICH_TIME specifier and TO_WHICH_TIME is the original time to which you are adding MINUTE.

Hope this helps.

open read and close a file in 1 line of code

Using CPython, your file will be closed immediately after the line is executed, because the file object is immediately garbage collected. There are two drawbacks, though:

  1. In Python implementations different from CPython, the file often isn't immediately closed, but rather at a later time, beyond your control.

  2. In Python 3.2 or above, this will throw a ResourceWarning, if enabled.

Better to invest one additional line:

with open('pagehead.section.htm','r') as f:
    output = f.read()

This will ensure that the file is correctly closed under all circumstances.

how to fire event on file select

You could subscribe for the onchange event on the input field:

<input type="file" id="file" name="file" />

and then:

document.getElementById('file').onchange = function() {
    // fire the upload here
};

Multiple Python versions on the same machine?

On Windows they get installed to separate folders, "C:\python26" and "C:\python31", but the executables have the same "python.exe" name.

I created another "C:\python" folder that contains "python.bat" and "python3.bat" that serve as wrappers to "python26" and "python31" respectively, and added "C:\python" to the PATH environment variable.

This allows me to type python or python3 in my .bat Python wrappers to start the one I desire.

On Linux, you can use the #! trick to specify which version you want a script to use.

How to print multiple lines of text with Python

The triple quotes answer is great for ASCII art, but for those wondering - what if my multiple lines are a tuple, list, or other iterable that returns strings (perhaps a list comprehension?), then how about:

print("\n".join(<*iterable*>))

For example:

print("\n".join(["{}={}".format(k, v) for k, v in os.environ.items() if 'PATH' in k]))

How do I make an http request using cookies on Android?

A cookie is just another HTTP header. You can always set it while making a HTTP call with the apache library or with HTTPUrlConnection. Either way you should be able to read and set HTTP cookies in this fashion.

You can read this article for more information.

I can share my peace of code to demonstrate how easy you can make it.

public static String getServerResponseByHttpGet(String url, String token) {

        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            get.setHeader("Cookie", "PHPSESSID=" + token + ";");
            Log.d(TAG, "Try to open => " + url);

            HttpResponse httpResponse = client.execute(get);
            int connectionStatusCode = httpResponse.getStatusLine().getStatusCode();
            Log.d(TAG, "Connection code: " + connectionStatusCode + " for request: " + url);

            HttpEntity entity = httpResponse.getEntity();
            String serverResponse = EntityUtils.toString(entity);
            Log.d(TAG, "Server response for request " + url + " => " + serverResponse);

            if(!isStatusOk(connectionStatusCode))
                return null;

            return serverResponse;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

How to free memory from char array in C

The memory associated with arr is freed automatically when arr goes out of scope. It is either a local variable, or allocated statically, but it is not dynamically allocated.

A simple rule for you to follow is that you must only every call free() on a pointer that was returned by a call to malloc, calloc or realloc.

How to make a function wait until a callback has been called using node.js

One way to achieve this is to wrap the API call into a promise and then use await to wait for the result.

// let's say this is the API function with two callbacks,
// one for success and the other for error
function apiFunction(query, successCallback, errorCallback) {
    if (query == "bad query") {
        errorCallback("problem with the query");
    }
    successCallback("Your query was <" + query + ">");
}

// myFunction wraps the above API call into a Promise
// and handles the callbacks with resolve and reject
function apiFunctionWrapper(query) {
    return new Promise((resolve, reject) => {
        apiFunction(query,(successResponse) => {
            resolve(successResponse);
        }, (errorResponse) => {
            reject(errorResponse);
        });
    });
}

// now you can use await to get the result from the wrapped api function
// and you can use standard try-catch to handle the errors
async function businessLogic() {
    try {
        const result = await apiFunctionWrapper("query all users");
        console.log(result);
        
        // the next line will fail
        const result2 = await apiFunctionWrapper("bad query");
    } catch(error) {
        console.error("ERROR:" + error);
    }
}

// call the main function
businessLogic();

Output:

Your query was <query all users>
ERROR:problem with the query

What is the difference between Google App Engine and Google Compute Engine?

The cloud services provides a range of options from fully managed to less managed services. Less managed services gives more control to the developers. The same is the difference in Compute and App engine also. The below image elaborate more on this point enter image description here

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

I had the same problem when I used code-first migrations to build my database for an MVC 5 application. I eventually found the seed method in my configuration.cs file to be causing the issue. My seed method was creating a table entry for the table containing the foreign key before creating the entry with the matching primary key.

Merge trunk to branch in Subversion

It is “old-fashioned” way to specify ranges of revisions you wish to merge. With 1.5+ you can use:

svn merge HEAD url/of/trunk path/to/branch/wc

Hashmap with Streams in Java 8 Streams to collect value of Map

If you are sure you are going to get at most a single element that passed the filter (which is guaranteed by your filter), you can use findFirst :

Optional<List> o = id1.entrySet()
                      .stream()
                      .filter( e -> e.getKey() == 1)
                      .map(Map.Entry::getValue)
                      .findFirst();

In the general case, if the filter may match multiple Lists, you can collect them to a List of Lists :

List<List> list = id1.entrySet()
                     .stream()
                     .filter(.. some predicate...)
                     .map(Map.Entry::getValue)
                     .collect(Collectors.toList());

How do you add CSS with Javascript?

Here's a slightly updated version of Chris Herring's solution, taking into account that you can use innerHTML as well instead of a creating a new text node:

function insertCss( code ) {
    var style = document.createElement('style');
    style.type = 'text/css';

    if (style.styleSheet) {
        // IE
        style.styleSheet.cssText = code;
    } else {
        // Other browsers
        style.innerHTML = code;
    }

    document.getElementsByTagName("head")[0].appendChild( style );
}

programmatically add column & rows to WPF Datagrid

To Bind the DataTable into the DataGridTextColumn in CodeBehind xaml

<DataGrid
  Name="TrkDataGrid"
  AutoGenerateColumns="False"
  ItemsSource="{Binding}">
</DataGrid>

xaml.cs

  foreach (DataColumn col in dt.Columns)
  {
    TrkDataGrid.Columns.Add(
      new DataGridTextColumn
      {
        Header = col.ColumnName,
        Binding = new Binding(string.Format("[{0}]", col.ColumnName))
      });
  }

  TrkDataGrid.ItemsSource= dt.DefaultView;

How does "FOR" work in cmd batch file?

for /f iterates per line input, so in your program will only output first path.

your program treats %PATH% as one-line input, and deliminate by ;, put first result to %%g, then output %%g (first deliminated path).

How to output to the console in C++/Windows

If you're using Visual Studio, it should work just fine!

Here's a code example:

#include <iostream>

using namespace std;

int main (int) {
    cout << "This will print to the console!" << endl;
}

Make sure you chose a Win32 console application when creating a new project. Still you can redirect the output of your project to a file by using the console switch (>>). This will actually redirect the console pipe away from the stdout to your file. (for example, myprog.exe >> myfile.txt).

I wish I'm not mistaken!

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

Try this one:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy"); 
LocalDate fromLocalDate = LocalDate.parse(fromdstrong textate, dateTimeFormatter);

You can add any format you want. That works for me!