Programs & Examples On #Sp who2

Command not found error in Bash variable assignment

When you define any variable then you do not have to put in any extra spaces.

E.g.

name = "Stack Overflow"  
// it is not valid, you will get an error saying- "Command not found"

So remove spaces:

name="Stack Overflow" 

and it will work fine.

Calling Web API from MVC controller

Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:

// All code to find the files are here and is working perfectly...

It doesn't make sense to call a API Controller from another controller on the same website.

This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...

How to redirect output of an entire shell script within the script itself?

You can make the whole script a function like this:

main_function() {
  do_things_here
}

then at the end of the script have this:

if [ -z $TERM ]; then
  # if not run via terminal, log everything into a log file
  main_function 2>&1 >> /var/log/my_uber_script.log
else
  # run via terminal, only output to screen
  main_function
fi

Alternatively, you may log everything into logfile each run and still output it to stdout by simply doing:

# log everything, but also output to stdout
main_function 2>&1 | tee -a /var/log/my_uber_script.log

Copy file or directories recursively in Python

The python shutil.copytree method its a mess. I've done one that works correctly:

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)
    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

CUDA incompatible with my gcc version

Another way of configuring nvcc to use a specific version of gcc (gcc-4.4, for instance), is to edit nvcc.profile and alter PATH to include the path to the gcc you want to use first.

For example (gcc-4.4.6 installed in /opt):

PATH += /opt/gcc-4.4.6/lib/gcc/x86_64-unknown-linux-gnu/4.4.6:/opt/gcc-4.4.6/bin:$(TOP)/open64/bin:$(TOP)/share/cuda/nvvm:$(_HERE_):

The location of nvcc.profile varies, but it should be in the same directory as the nvcc executable itself.

This is a bit of a hack, as nvcc.profile is not intended for user configuration as per the nvcc manual, but it was the solution which worked best for me.

Correct use for angular-translate in controllers

What is happening is that Angular-translate is watching the expression with an event-based system, and just as in any other case of binding or two-way binding, an event is fired when the data is retrieved, and the value changed, which obviously doesn't work for translation. Translation data, unlike other dynamic data on the page, must, of course, show up immediately to the user. It can't pop in after the page loads.

Even if you can successfully debug this issue, the bigger problem is that the development work involved is huge. A developer has to manually extract every string on the site, put it in a .json file, manually reference it by string code (ie 'pageTitle' in this case). Most commercial sites have thousands of strings for which this needs to happen. And that is just the beginning. You now need a system of keeping the translations in synch when the underlying text changes in some of them, a system for sending the translation files out to the various translators, of reintegrating them into the build, of redeploying the site so the translators can see their changes in context, and on and on.

Also, as this is a 'binding', event-based system, an event is being fired for every single string on the page, which not only is a slower way to transform the page but can slow down all the actions on the page, if you start adding large numbers of events to it.

Anyway, using a post-processing translation platform makes more sense to me. Using GlobalizeIt for example, a translator can just go to a page on the site and start editing the text directly on the page for their language, and that's it: https://www.globalizeit.com/HowItWorks. No programming needed (though it can be programmatically extensible), it integrates easily with Angular: https://www.globalizeit.com/Translate/Angular, the transformation of the page happens in one go, and it always displays the translated text with the initial render of the page.

Full disclosure: I'm a co-founder :)

How to convert an Image to base64 string in java?

this did it for me. you can vary the options for the output format to Base64.Default whatsoever.

// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);

Get list of databases from SQL Server

SELECT [name] 
FROM master.dbo.sysdatabases 
WHERE dbid > 4 and [name] <> 'ReportServer' and [name] <> 'ReportServerTempDB'

This will work for both condition, Whether reporting is enabled or not

Regex for numbers only

I think that this one is the simplest one and it accepts European and USA way of writing numbers e.g. USA 10,555.12 European 10.555,12 Also this one does not allow several commas or dots one after each other e.g. 10..22 or 10,.22 In addition to this numbers like .55 or ,55 would pass. This may be handy.

^([,|.]?[0-9])+$

How to get file size in Java

Did a quick google. Seems that to find the file size you do this,

long size = f.length();

The differences between the three methods you posted can be found here

getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.

Round integers to the nearest 10

if you want the algebric form and still use round for it it's hard to get simpler than:

interval = 5
n = 4
print(round(n/interval))*interval

What jar should I include to use javax.persistence package in a hibernate based application?

If you are using maven, adding below dependency should work

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

android EditText - finished typing event

both @Reno and @Vinayak B answers together if you want to hide the keyboard after the action

textView.setOnEditorActionListener(new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(textView.getWindowToken(), 0);
            return true;
        }
        return false;
    }
});

textView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
             // your action here
        }
    }
});

What is the difference between an int and a long in C++?

When compiling for x64, the difference between int and long is somewhere between 0 and 4 bytes, depending on what compiler you use.

GCC uses the LP64 model, which means that ints are 32-bits but longs are 64-bits under 64-bit mode.

MSVC for example uses the LLP64 model, which means both ints and longs are 32-bits even in 64-bit mode.

Row count with PDO

Answering this because I trapped myself with it by now knowing this and maybe it will be useful.

Keep in mind that you cant fetch results twice. You have to save fetch result into array, get row count by count($array), and output results with foreach. For example:

$query = "your_query_here";
$STH = $DBH->prepare($query);
$STH->execute();
$rows = $STH->fetchAll();
//all your results is in $rows array
$STH->setFetchMode(PDO::FETCH_ASSOC);           
if (count($rows) > 0) {             
    foreach ($rows as $row) {
        //output your rows
    }                       
}

How to sort a list of lists by a specific index of the inner list?

**old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]
    #let's assume we want to sort lists by last value ( old_list[2] )
    new_list = sorted(old_list, key=lambda x: x[2])**

correct me if i'm wrong but isnt the 'x[2]' calling the 3rd item in the list, not the 3rd item in the nested list? should it be x[2][2]?

How to create a delay in Swift?

To create a simple time delay, you can import Darwin and then use sleep(seconds) to do the delay. That only takes whole seconds, though, so for more precise measurements you can import Darwin and use usleep(millionths of a second) for very precise measurement. To test this, I wrote:

import Darwin
print("This is one.")
sleep(1)
print("This is two.")
usleep(400000)
print("This is three.")

Which prints, then waits for 1 sec and prints, then waits for 0.4 sec then prints. All worked as expected.

How do you read scanf until EOF in C?

Man, if you are using Windows, EOF is not reached by pressing enter, but by pressing Crtl+Z at the console. This will print "^Z", an indicator of EOF. The behavior of functions when reading this (the EOF or Crtl+Z):

Function: Output: scanf(...) EOF gets(<variable>) NULL feof(stdin) 1 getchar() EOF

Two inline-block, width 50% elements wrap to second line

inline and inline-block elements are affected by whitespace in the HTML.

The simplest way to fix your problem is to remove the whitespace between </div> and <div id="col2">, see: http://jsfiddle.net/XCDsu/15/

There are other possible solutions, see: bikeshedding CSS3 property alternative?

arranging div one below the other

The default behaviour of divs is to take the full width available in their parent container.
This is the same as if you'd give the inner divs a width of 100%.

By floating the divs, they ignore their default and size their width to fit the content. Everything behind it (in the HTML), is placed under the div (on the rendered page).
This is the reason that they align theirselves next to each other.

The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it. A floating element is one where the computed value of float is not none.

Source: https://developer.mozilla.org/en-US/docs/Web/CSS/float

Get rid of the float, and the divs will be aligned under each other.
If this does not happen, you'll have some other css on divs or children of wrapper defining a floating behaviour or an inline display.

If you want to keep the float, for whatever reason, you can use clear on the 2nd div to reset the floating properties of elements before that element.
clear has 5 valid values: none | left | right | both | inherit. Clearing no floats (used to override inherited properties), left or right floats or both floats. Inherit means it'll inherit the behaviour of the parent element

Also, because of the default behaviour, you don't need to set the width and height on auto.
You only need this is you want to set a hardcoded height/width. E.g. 80% / 800px / 500em / ...

<div id="wrapper">
    <div id="inner1"></div>
    <div id="inner2"></div>
</div>

CSS is

#wrapper{
    margin-left:auto;
    margin-right:auto;
    height:auto; // this is not needed, as parent container, this div will size automaticly
    width:auto; // this is not needed, as parent container, this div will size automaticly
}

/*
You can get rid of the inner divs in the css, unless you want to style them.
If you want to style them identicly, you can use concatenation
*/
#inner1, #inner2 {
    border: 1px solid black;
}

How can I make a button redirect my page to another page?

try

<button onclick="window.location.href='b.php'">Click me</button>

How do I determine the current operating system with Node.js

when you are using 32bits node on 64bits windows(like node-webkit or atom-shell developers), process.platform will echo win32

use

    function isOSWin64() {
      return process.arch === 'x64' || process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');
    }

(check here for details)

How to fix IndexError: invalid index to scalar variable

Basically, 1 is not a valid index of y. If the visitor is comming from his own code he should check if his y contains the index which he tries to access (in this case the index is 1).

Login to website, via C#

Sometimes, it may help switching off AllowAutoRedirect and setting both login POST and page GET requests the same user agent.

request.UserAgent = userAgent;
request.AllowAutoRedirect = false;

How to remove carriage return and newline from a variable in shell script

for a pure shell solution without calling external program:

NL=$'\n'    # define a variable to reference 'newline'

testVar=${testVar%$NL}    # removes trailing 'NL' from string

Drop default constraint on a column in TSQL

I would suggest:

DECLARE @sqlStatement nvarchar(MAX),
        @tableName nvarchar(50) = 'TripEvent',
        @columnName nvarchar(50) = 'CreatedDate';

SELECT                  @sqlStatement = 'ALTER TABLE ' + @tableName + ' DROP CONSTRAINT ' + dc.name + ';'
        FROM            sys.default_constraints AS dc
            LEFT JOIN   sys.columns AS sc
                ON      (dc.parent_column_id = sc.column_id)
        WHERE           dc.parent_object_id = OBJECT_ID(@tableName)
        AND         type_desc = 'DEFAULT_CONSTRAINT'
        AND         sc.name = @columnName
PRINT'   ['+@tableName+']:'+@@SERVERNAME+'.'+DB_NAME()+'@'+CONVERT(VarChar, GETDATE(), 127)+';  '+@sqlStatement;
IF(LEN(@sqlStatement)>0)EXEC sp_executesql @sqlStatement

Automatically pass $event with ng-click?

Take a peek at the ng-click directive source:

...
compile: function($element, attr) {
  var fn = $parse(attr[directiveName]);
  return function(scope, element, attr) {
    element.on(lowercase(name), function(event) {
      scope.$apply(function() {
        fn(scope, {$event:event});
      });
    });
  };
}

It shows how the event object is being passed on to the ng-click expression, using $event as a name of the parameter. This is done by the $parse service, which doesn't allow for the parameters to bleed into the target scope, which means the answer is no, you can't access the $event object any other way but through the callback parameter.

C# 4.0 optional out/ref arguments

No, but you can use a delegate (e.g. Action) as an alternative.

Inspired in part by Robin R's answer when facing a situation where I thought I wanted an optional out parameter, I instead used an Action delegate. I've borrowed his example code to modify for use of Action<int> in order to show the differences and similarities:

public string foo(string value, Action<int> outResult = null)
{
    // .. do something

    outResult?.Invoke(100);

    return value;
}

public void bar ()
{
    string str = "bar";

    string result;
    int optional = 0;

    // example: call without the optional out parameter
    result = foo (str);
    Console.WriteLine ("Output was {0} with no optional value used", result);

    // example: call it with optional parameter
    result = foo (str, x => optional = x);
    Console.WriteLine ("Output was {0} with optional value of {1}", result, optional);

    // example: call it with named optional parameter
    foo (str, outResult: x => optional = x);
    Console.WriteLine ("Output was {0} with optional value of {1}", result, optional);
}

This has the advantage that the optional variable appears in the source as a normal int (the compiler wraps it in a closure class, rather than us wrapping it explicitly in a user-defined class).

The variable needs explicit initialisation because the compiler cannot assume that the Action will be called before the function call exits.

It's not suitable for all use cases, but worked well for my real use case (a function that provides data for a unit test, and where a new unit test needed access to some internal state not present in the return value).

PHP Regex to check date is in YYYY-MM-DD format

From Laravel 5.7 and date format i.e.: 12/31/2019

function checkDateFormat(string $date): bool
{
    return preg_match("/^(0[1-9]|1[0-2])\/(0[1-9]|[1-2][0-9]|3[0-1])\/[0-9]{4}$/", $date);
}

How do I escape a reserved word in Oracle?

you have to rename the column to an other name because TABLE is reserved by Oracle.

You can see all reserved words of Oracle in the oracle view V$RESERVED_WORDS.

Deleting specific rows from DataTable

<asp:GridView ID="grd_item_list" runat="server" AutoGenerateColumns="false" Width="100%" CssClass="table table-bordered table-hover" OnRowCommand="grd_item_list_RowCommand">
    <Columns>
        <asp:TemplateField HeaderText="No">
            <ItemTemplate>
                <%# Container.DataItemIndex + 1 %>
            </ItemTemplate>
        </asp:TemplateField>            
        <asp:TemplateField HeaderText="Actions">
            <ItemTemplate>                    
                <asp:Button ID="remove_itemIndex" OnClientClick="if(confirm('Are You Sure to delete?')==true){ return true;} else{ return false;}" runat="server" class="btn btn-primary" Text="REMOVE" CommandName="REMOVE_ITEM" CommandArgument='<%# Container.DataItemIndex+1 %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

 **This is the row binding event**

protected void grd_item_list_RowCommand(object sender, GridViewCommandEventArgs e) {

    item_list_bind_structure();

    if (ViewState["item_list"] != null)
        dt = (DataTable)ViewState["item_list"];


    if (e.CommandName == "REMOVE_ITEM") {
        var RowNum = Convert.ToInt32(e.CommandArgument.ToString()) - 1;

        DataRow dr = dt.Rows[RowNum];
        dr.Delete();

    }

    grd_item_list.DataSource = dt;
    grd_item_list.DataBind();
}

How to get the list of files in a directory in a shell script?

This is a way to do it where the syntax is simpler for me to understand:

yourfilenames=`ls ./*.txt`
for eachfile in $yourfilenames
do
   echo $eachfile
done

./ is the current working directory but could be replaced with any path
*.txt returns anything.txt
You can check what will be listed easily by typing the ls command straight into the terminal.

Basically, you create a variable yourfilenames containing everything the list command returns as a separate element, and then you loop through it. The loop creates a temporary variable eachfile that contains a single element of the variable it's looping through, in this case a filename. This isn't necessarily better than the other answers, but I find it intuitive because I'm already familiar with the ls command and the for loop syntax.

Bundling data files with PyInstaller (--onefile)

I have been dealing with this issue for a long(well, very long) time. I've searched almost every source but things were not getting in a pattern in my head.

Finally, I think I have figured out exact steps to follow, I wanted to share.

Note that, my answer uses informations on the answers of others on this question.

How to create a standalone executable of a python project.

Assume, we have a project_folder and the file tree is as follows:

project_folder/
    main.py
    xxx.py # modules
    xxx.py # modules
    sound/ # directory containing the sound files
    img/ # directory containing the image files
    venv/ # if using a venv

First of all, let's say you have defined your paths to sound/ and img/ folders into variables sound_dir and img_dir as follows:

img_dir = os.path.join(os.path.dirname(__file__), "img")
sound_dir = os.path.join(os.path.dirname(__file__), "sound")

You have to change them, as follows:

img_dir = resource_path("img")
sound_dir = resource_path("sound")

Where, resource_path() is defined in the top of your script as:

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

Activate virtual env if using a venv,

Install pyinstaller if you didn't yet, by: pip3 install pyinstaller.

Run: pyi-makespec --onefile main.py to create the spec file for the compile and build process.

This will change file hierarchy to:

project_folder/
    main.py
    xxx.py # modules
    xxx.py # modules
    sound/ # directory containing the sound files
    img/ # directory containing the image files
    venv/ # if using a venv
    main.spec

Open(with an edior) main.spec:

At top of it, insert:

added_files = [

("sound", "sound"),
("img", "img")

]

Then, change the line of datas=[], to datas=added_files,

For the details of the operations done on main.spec see here.

Run pyinstaller --onefile main.spec

And that is all, you can run main in project_folder/dist from anywhere, without having anything else in its folder. You can distribute only that main file. It is now, a true standalone.

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

All i needed were the correct credentials. while deploying to a web app, i had to go to Deployment Center, Deployment Credentials. And then use either the App Credentials or create User Credentials. After this, delete the cached credentials on the local machine (windows: Control Panel\User Accounts\Credential Manager). run "git push webapp master:master" again, enter either of the Deployment Credentials. This worked for me.

Gradle does not find tools.jar

Put in gradle.properties file the following code line:

org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_45

Example image

Try catch statements in C

C itself doesn't support exceptions but you can simulate them to a degree with setjmp and longjmp calls.

static jmp_buf s_jumpBuffer;

void Example() { 
  if (setjmp(s_jumpBuffer)) {
    // The longjmp was executed and returned control here
    printf("Exception happened here\n");
  } else {
    // Normal code execution starts here
    Test();
  }
}

void Test() {
  // Rough equivalent of `throw`
  longjmp(s_jumpBuffer, 42);
}

This website has a nice tutorial on how to simulate exceptions with setjmp and longjmp

Check file extension in upload form in PHP

Personally,I prefer to use preg_match() function:

if(preg_match("/\.(gif|png|jpg)$/", $filename))

or in_array()

$exts = array('gif', 'png', 'jpg'); 
if(in_array(end(explode('.', $filename)), $exts)

With in_array() can be useful if you have a lot of extensions to validate and perfomance question. Another way to validade file images: you can use @imagecreatefrom*(), if the function fails, this mean the image is not valid.

For example:

function testimage($path)
{
   if(!preg_match("/\.(png|jpg|gif)$/",$path,$ext)) return 0;
   $ret = null;
   switch($ext)
   {
       case 'png': $ret = @imagecreatefrompng($path); break;
       case 'jpeg': $ret = @imagecreatefromjpeg($path); break;
       // ...
       default: $ret = 0;
   }

   return $ret;
}

then:

$valid = testimage('foo.png');

Assuming that foo.png is a PHP-script file with .png extension, the above function fails. It can avoid attacks like shell update and LFI.

Git Pull is Not Possible, Unmerged Files

Ryan Stewart's answer was almost there. In the case where you actually don't want to delete your local changes, there's a workflow you can use to merge:

  • Run git status. It will give you a list of unmerged files.
  • Merge them (by hand, etc.)
  • Run git commit

Git will commit just the merges into a new commit. (In my case, I had additional added files on disk, which weren't lumped into that commit.)

Git then considers the merge successful and allows you to move forward.

SQLAlchemy equivalent to SQL "LIKE" statement

try this code

output = dbsession.query(<model_class>).filter(<model_calss>.email.ilike('%' + < email > + '%'))

Use a loop to plot n charts Python

Use a dictionary!!

You can also use dictionaries that allows you to have more control over the plots:

import matplotlib.pyplot as plt
#   plot 0     plot 1    plot 2   plot 3
x=[[1,2,3,4],[1,4,3,4],[1,2,3,4],[9,8,7,4]]
y=[[3,2,3,4],[3,6,3,4],[6,7,8,9],[3,2,2,4]]

plots = zip(x,y)
def loop_plot(plots):
    figs={}
    axs={}
    for idx,plot in enumerate(plots):
        figs[idx]=plt.figure()
        axs[idx]=figs[idx].add_subplot(111)
        axs[idx].plot(plot[0],plot[1])
return figs, axs

figs, axs = loop_plot(plots)

Now you can select the plot that you want to modify easily:

axs[0].set_title("Now I can control it!")

Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx) or show them plt.show(). Use the argument block=False only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot function or in a separate loop using the dictionaries that the function provided.

remove duplicates from sql union

Others have already answered your direct question, but perhaps you could simplify the query to eliminate the question (or have I missed something, and a query like the following will really produce substantially different results?):

select * 
    from calls c join users u
        on c.assigned_to = u.user_id 
        or c.requestor_id = u.user_id
    where u.dept = 4

Pandas dataframe get first row of each group

This will give you the second row of each group (zero indexed, nth(0) is the same as first()):

df.groupby('id').nth(1) 

Documentation: http://pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-nth-row-of-each-group

Internet Explorer 11 detection

Okay try this, simple and for IE11 and IE below 11 version

browserIsIE = navigator.userAgent.toUpperCase().indexOf("TRIDENT/") != -1 || navigator.userAgent.toUpperCase().indexOf("MSIE") != -1;

navigator.userAgent.toUpperCase().indexOf("TRIDENT/") != -1 for IE 11 version navigator.userAgent.toUpperCase().indexOf("MSIE") != -1 for IE below 11 version

_x000D_
_x000D_
browserIsIE = navigator.userAgent.toUpperCase().indexOf("TRIDENT/") != -1 || navigator.userAgent.toUpperCase().indexOf("MSIE") != -1;_x000D_
_x000D_
console.log('Is IE Browser : '+ browserIsIE)
_x000D_
_x000D_
_x000D_

Get most recent row for given ID

Use the aggregate MAX(signin) grouped by id. This will list the most recent signin for each id.

SELECT 
 id, 
 MAX(signin) AS most_recent_signin
FROM tbl
GROUP BY id

To get the whole single record, perform an INNER JOIN against a subquery which returns only the MAX(signin) per id.

SELECT 
  tbl.id,
  signin,
  signout
FROM tbl
  INNER JOIN (
    SELECT id, MAX(signin) AS maxsign FROM tbl GROUP BY id
  ) ms ON tbl.id = ms.id AND signin = maxsign
WHERE tbl.id=1

How to "properly" print a list?

This is simple code, so if you are new you should understand it easily enough.

    mylist = ["x", 3, "b"]
    for items in mylist:
        print(items)

It prints all of them without quotes, like you wanted.

How to pass parameters on onChange of html select

Just in case someone is looking for a React solution without having to download addition dependancies you could write:

<select onChange={this.changed(this)}>
   <option value="Apple">Apple</option>
   <option value="Android">Android</option>                
</select>

changed(){
  return e => {
    console.log(e.target.value)
  }
}

Make sure to bind the changed() function in the constructor like:

this.changed = this.changed.bind(this);

How to call another controller Action From a controller in Mvc

as @DLeh says Use rather

var controller = DependencyResolver.Current.GetService<ControllerB>();

But, giving the controller, a controlller context is important especially when you need to access the User object, Server object, or the HttpContext inside the 'child' controller.

I have added a line of code:

controller.ControllerContext = new ControllerContext(Request.RequestContext, controller);

or else you could have used System.Web to acces the current context too, to access Server or the early metioned objects

NB: i am targetting the framework version 4.6 (Mvc5)

How do I add a simple onClick event handler to a canvas element?

When you draw to a canvas element, you are simply drawing a bitmap in immediate mode.

The elements (shapes, lines, images) that are drawn have no representation besides the pixels they use and their colour.

Therefore, to get a click event on a canvas element (shape), you need to capture click events on the canvas HTML element and use some math to determine which element was clicked, provided you are storing the elements' width/height and x/y offset.

To add a click event to your canvas element, use...

canvas.addEventListener('click', function() { }, false);

To determine which element was clicked...

var elem = document.getElementById('myCanvas'),
    elemLeft = elem.offsetLeft + elem.clientLeft,
    elemTop = elem.offsetTop + elem.clientTop,
    context = elem.getContext('2d'),
    elements = [];

// Add event listener for `click` events.
elem.addEventListener('click', function(event) {
    var x = event.pageX - elemLeft,
        y = event.pageY - elemTop;

    // Collision detection between clicked offset and element.
    elements.forEach(function(element) {
        if (y > element.top && y < element.top + element.height 
            && x > element.left && x < element.left + element.width) {
            alert('clicked an element');
        }
    });

}, false);

// Add element.
elements.push({
    colour: '#05EFFF',
    width: 150,
    height: 100,
    top: 20,
    left: 15
});

// Render elements.
elements.forEach(function(element) {
    context.fillStyle = element.colour;
    context.fillRect(element.left, element.top, element.width, element.height);
});?

jsFiddle.

This code attaches a click event to the canvas element, and then pushes one shape (called an element in my code) to an elements array. You could add as many as you wish here.

The purpose of creating an array of objects is so we can query their properties later. After all the elements have been pushed onto the array, we loop through and render each one based on their properties.

When the click event is triggered, the code loops through the elements and determines if the click was over any of the elements in the elements array. If so, it fires an alert(), which could easily be modified to do something such as remove the array item, in which case you'd need a separate render function to update the canvas.


For completeness, why your attempts didn't work...

elem.onClick = alert("hello world"); // displays alert without clicking

This is assigning the return value of alert() to the onClick property of elem. It is immediately invoking the alert().

elem.onClick = alert('hello world');  // displays alert without clicking

In JavaScript, the ' and " are semantically identical, the lexer probably uses ['"] for quotes.

elem.onClick = "alert('hello world!')"; // does nothing, even with clicking

You are assigning a string to the onClick property of elem.

elem.onClick = function() { alert('hello world!'); }; // does nothing

JavaScript is case sensitive. The onclick property is the archaic method of attaching event handlers. It only allows one event to be attached with the property and the event can be lost when serialising the HTML.

elem.onClick = function() { alert("hello world!"); }; // does nothing

Again, ' === ".

Uncaught ReferenceError: $ is not defined error in jQuery

Change the order you're including your scripts (jQuery first):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
    src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>

Reflection generic get field value

 Integer typeValue = 0;
 try {
     Class<Types> types = Types.class;
     java.lang.reflect.Field field = types.getDeclaredField("Type");
     field.setAccessible(true);
     Object value = field.get(types);
     typeValue = (Integer) value;
 } catch (Exception e) {
     e.printStackTrace();
 }

How do I combine two data-frames based on two columns?

Hope this helps;

df1 = data.frame(CustomerId=c(1:10),
             Hobby = c(rep("sing", 4), rep("pingpong", 3), rep("hiking", 3)),
             Product=c(rep("Toaster",3),rep("Phone", 2), rep("Radio",3), rep("Stereo", 2)))

df2 = data.frame(CustomerId=c(2,4,6, 8, 10),State=c(rep("Alabama",2),rep("Ohio",1),   rep("Cal", 2)),
             like=c("sing", 'hiking', "pingpong", 'hiking', "sing"))

df3 = merge(df1, df2, by.x=c("CustomerId", "Hobby"), by.y=c("CustomerId", "like"))

Assuming df1$Hobby and df2$like mean the same thing.

Allow scroll but hide scrollbar

I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.

Just add

::-webkit-scrollbar {display:none;}

To your id or class of the div you're using the scroll bar with.

Here is a helpful link Custom Scroll Bar in Webkit

How do I tell if .NET 3.5 SP1 is installed?

Use Add/Remove programs from the Control Panel.

How can I center an image in Bootstrap?

Since the img is an inline element, Just use text-center on it's container. Using mx-auto will center the container (column) too.

<div class="row">
    <div class="col-4 mx-auto text-center">
        <img src="..">
    </div>
</div>

By default, images are display:inline. If you only want the center the image (and not the other column content), make the image display:block using the d-block class, and then mx-auto will work.

<div class="row">
  <div class="col-4">
    <img class="mx-auto d-block" src="..">
  </div>
</div>

Demo: http://codeply.com/go/iakGGLdB8s

Algorithm to return all combinations of k elements from n

JavaScript, generator-based, recursive approach:

_x000D_
_x000D_
function *nCk(n,k){_x000D_
  for(var i=n-1;i>=k-1;--i)_x000D_
    if(k===1)_x000D_
      yield [i];_x000D_
    else_x000D_
      for(var temp of nCk(i,k-1)){_x000D_
        temp.unshift(i);_x000D_
        yield temp;_x000D_
      }_x000D_
}_x000D_
_x000D_
function test(){_x000D_
  try{_x000D_
    var n=parseInt(ninp.value);_x000D_
    var k=parseInt(kinp.value);_x000D_
    log.innerText="";_x000D_
    var stop=Date.now()+1000;_x000D_
    if(k>=1)_x000D_
      for(var res of nCk(n,k))_x000D_
        if(Date.now()<stop)_x000D_
          log.innerText+=JSON.stringify(res)+" ";_x000D_
        else{_x000D_
          log.innerText+="1 second passed, stopping here.";_x000D_
          break;_x000D_
        }_x000D_
  }catch(ex){}_x000D_
}
_x000D_
n:<input id="ninp" oninput="test()">_x000D_
&gt;= k:<input id="kinp" oninput="test()"> &gt;= 1_x000D_
<div id="log"></div>
_x000D_
_x000D_
_x000D_

This way (decreasing i and unshift()) it produces combinations and elements inside combinations in decreasing order, somewhat pleasing the eye.
Test stops after 1 second, so entering weird numbers is relatively safe.

Cannot open solution file in Visual Studio Code

But you can open the folder with the .SLN in to edit the code in the project, which will detect the .SLN to select the library that provides Intellisense.

AngularJs: How to set radio button checked based on model

Just do something like this,<input type="radio" ng-disabled="loading" name="dateRange" ng-model="filter.DateRange" value="1" ng-checked="(filter.DateRange == 1)"/>

How to set selected index JComboBox by value

Why not take a collection, likely a Map such as a HashMap, and use it as the nucleus of your own combo box model class that implements the ComboBoxModel interface? Then you could access your combo box's items easily via their key Strings rather than ints.

For instance...

import java.util.HashMap;
import java.util.Map;

import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataListener;

public class MyComboModel<K, V>   implements ComboBoxModel {
   private Map<K, V> nucleus = new HashMap<K, V>();

   // ... any constructors that you want would go here

   public void put(K key, V value) {
      nucleus.put(key, value);
   }

   public V get(K key) {
      return nucleus.get(key);
   }

   @Override
   public void addListDataListener(ListDataListener arg0) {
      // TODO Auto-generated method stub

   }

   // ... plus all the other methods required by the interface
}

SQL Server Group by Count of DateTime Per Hour?

You can also achieve this by using following SQL with date and hour in same columns and proper date time format and ordered by date time

SELECT  dateadd(hour, datediff(hour, 0, StartDate), 0) as 'ForDate', 
    COUNT(*) as 'Count' 
FROM #Events
GROUP BY dateadd(hour, datediff(hour, 0, LogTime), 0)
ORDER BY ForDate

how to bind img src in angular 2 in ngFor?

Angular 2.x to 8 Compatible!

You can directly give the source property of the current object in the img src attribute. Please see my code below:

<div *ngFor="let brochure of brochureList">
    <img class="brochure-poster" [src]="brochure.imageUrl" />
</div>

NOTE: You can as well use string interpolation but that is not a legit way to do it. Property binding was created for this very purpose hence better use this.

NOT RECOMMENDED :

<img class="brochure-poster" src="{{brochure.imageUrl}}"/>

Its because that defeats the purpose of property binding. It is more meaningful to use that for setting the properties. {{}} is a normal string interpolation expression, that does not reveal to anyone reading the code that it makes special meaning. Using [] makes it easily to spot the properties that are set dynamically.

Here is my brochureList contains the following json received from service(you can assign it to any variable):

[ {
            "productId":1,
            "productName":"Beauty Products",
            "productCode": "XXXXXX",            
            "description":  "Skin Care",           
            "imageUrl":"app/Images/c1.jpg"
         },
        {
             "productId":2,
            "productName":"Samsung Galaxy J5",
            "productCode": "MOB-124",      
            "description":  "8GB, Gold",
            "imageUrl":"app/Images/c8.jpg"
         }]

foreach vs someList.ForEach(){}

One thing to be wary of is how to exit from the Generic .ForEach method - see this discussion. Although the link seems to say that this way is the fastest. Not sure why - you'd think they would be equivalent once compiled...

Error renaming a column in MySQL

Lone Ranger is very close... in fact, you also need to specify the datatype of the renamed column. For example:

ALTER TABLE `xyz` CHANGE `manufacurerid` `manufacturerid` INT;

Remember :

  • Replace INT with whatever your column data type is (REQUIRED)
  • Tilde/ Backtick (`) is optional

Remove Unnamed columns in pandas dataframe

The pandas.DataFrame.dropna function removes missing values (e.g. NaN, NaT).

For example the following code would remove any columns from your dataframe, where all of the elements of that column are missing.

df.dropna(how='all', axis='columns')

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In my case, I had a collection of radio buttons that needed to be in a group. I just included a 'Selected' property in the model. Then, in the loop to output the radiobuttons just do...

@Html.RadioButtonFor(m => Model.Selected, Model.Categories[i].Title)

This way, the name is the same for all radio buttons. When the form is posted, the 'Selected' property is equal to the category title (or id or whatever) and this can be used to update the binding on the relevant radiobutton, like this...

model.Categories.Find(m => m.Title.Equals(model.Selected)).Selected = true;

May not be the best way, but it does work.

Are members of a C++ struct initialized to 0 by default?

In general, no. However, a struct declared as file-scope or static in a function /will/ be initialized to 0 (just like all other variables of those scopes):

int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0

void foo() {
  struct { int a, b; } bar; // undefined
  static struct { int c, d; } quux; // 0, 0
}

how to define variable in jquery

Remember jQuery is a JavaScript library, i.e. like an extension. That means you can use both jQuery and JavaScript in the same function (restrictions apply).

You declare/create variables in the same way as in Javascript: var example;

However, you can use jQuery for assigning values to variables:

var example = $("#unique_product_code").html();

Instead of pure JavaScript:

var example = document.getElementById("unique_product_code").innerHTML;

how to use html2canvas and jspdf to export to pdf in a proper and simple way

Changing this line:

var doc = new jsPDF('L', 'px', [w, h]);
var doc = new jsPDF('L', 'pt', [w, h]);

To fix the dimensions.

How to link to specific line number on github

Many editors (but also see the Commands section below) support linking to a file's line number or range on GitHub or BitBucket (or others). Here's a short list:

Atom

Open on GitHub

Emacs

git-link

Sublime Text

GitLink

Vim

gitlink-vim


Commands

  • git-link - Git subcommand for getting a repo-browser link to a git object
  • ghwd - Open the github URL that matches your shell's current branch and working directory

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

The best way is to do:

var obj ={"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10"??:0,"11":0,"12":0} 
Object.entries(obj);

Calling entries, as shown here, will return [key, value] pairs, as the asker requested.

Alternatively, you could call Object.values(obj), which would return only values.

disable editing default value of text input

You can either use the readonly or the disabled attribute. Note that when disabled, the input's value will not be submitted when submitting the form.

<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">

why windows 7 task scheduler task fails with error 2147942667

For me it was the "Start In" - I copied the values from an older server, and updated the path to the new .exe location, but I forgot to update the "start in" location - if it doesn't exist, you get this error too

Quoting @hans-passant 's comment from above, because it is valuable to debugging this issue:

Convert the error code to hex to get 0x8007010B. The 7 makes it a Windows error. Which makes 010B error code 267. "The directory name is invalid". Sure, that happens.

Showing line numbers in IPython/Jupyter Notebooks

Was looking for this: Shift-L in JupyterLab 1.0.0

Is it possible to add an HTML link in the body of a MAILTO link

Add the full link, with:

 "http://"

to the beginning of a line, and most decent email clients will auto-link it either before sending, or at the other end when receiving.

For really long urls that will likely wrap due to all the parameters, wrap the link in a less than/greater than symbol. This tells the email client not to wrap the url.

e.g.

  <http://www.example.com/foo.php?this=a&really=long&url=with&lots=and&lots=and&lots=of&prameters=on_it>

How do I run msbuild from the command line using Windows SDK 7.1?

Using the "Developer Command Prompt for Visual Studio 20XX" instead of "cmd" will set the path for msbuild automatically without having to add it to your environment variables.

Express: How to pass app-instance to routes from a different file?

For database separate out Data Access Service that will do all DB work with simple API and avoid shared state.

Separating routes.setup looks like overhead. I would prefer to place a configuration based routing instead. And configure routes in .json or with annotations.

async for loop in node.js

I've reduced your code sample to the following lines to make it easier to understand the explanation of the concept.

var results = [];
var config = JSON.parse(queries);
for (var key in config) {
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
    });
}
res.writeHead( ... );
res.end(results);

The problem with the previous code is that the search function is asynchronous, so when the loop has ended, none of the callback functions have been called. Consequently, the list of results is empty.

To fix the problem, you have to put the code after the loop in the callback function.

    search(query, function(result) {
        results.push(result);
        // Put res.writeHead( ... ) and res.end(results) here
    });

However, since the callback function is called multiple times (once for every iteration), you need to somehow know that all callbacks have been called. To do that, you need to count the number of callbacks, and check whether the number is equal to the number of asynchronous function calls.

To get a list of all keys, use Object.keys. Then, to iterate through this list, I use .forEach (you can also use for (var i = 0, key = keys[i]; i < keys.length; ++i) { .. }, but that could give problems, see JavaScript closure inside loops – simple practical example).

Here's a complete example:

var results = [];
var config = JSON.parse(queries);
var onComplete = function() {
    res.writeHead( ... );
    res.end(results);
};
var keys = Object.keys(config);
var tasksToGo = keys.length;
if (tasksToGo === 0) {
   onComplete();
} else {
    // There is at least one element, so the callback will be called.
    keys.forEach(function(key) {
        var query = config[key].query;
        search(query, function(result) {
            results.push(result);
            if (--tasksToGo === 0) {
                // No tasks left, good to go
                onComplete();
            }
        });
    });
}

Note: The asynchronous code in the previous example are executed in parallel. If the functions need to be called in a specific order, then you can use recursion to get the desired effect:

var results = [];
var config = JSON.parse(queries);
var keys = Object.keys(config);
(function next(index) {
    if (index === keys.length) { // No items left
        res.writeHead( ... );
        res.end(results);
        return;
    }
    var key = keys[index];
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
        next(index + 1);
    });
})(0);

What I've shown are the concepts, you could use one of the many (third-party) NodeJS modules in your implementation, such as async.

Add a CSS border on hover without moving the element

Add a border to the regular item, the same color as the background, so that it cannot be seen. That way the item has a border: 1px whether it is being hovered or not.

SQLDataReader Row Count

 DataTable dt = new DataTable();
 dt.Load(reader);
 int numRows= dt.Rows.Count;

remove table row with specific id

Simply $("#3").remove(); would be enough. But 3 isn't a good id (I think it's even illegal, as it starts with a digit).

Fast way to discover the row count of a table in PostgreSQL

Counting rows in big tables is known to be slow in PostgreSQL. To get a precise number it has to do a full count of rows due to the nature of MVCC. There is a way to speed this up dramatically if the count does not have to be exact like it seems to be in your case.

Instead of getting the exact count (slow with big tables):

SELECT count(*) AS exact_count FROM myschema.mytable;

You get a close estimate like this (extremely fast):

SELECT reltuples::bigint AS estimate FROM pg_class where relname='mytable';

How close the estimate is depends on whether you run ANALYZE enough. It is usually very close.
See the PostgreSQL Wiki FAQ.
Or the dedicated wiki page for count(*) performance.

Better yet

The article in the PostgreSQL Wiki is was a bit sloppy. It ignored the possibility that there can be multiple tables of the same name in one database - in different schemas. To account for that:

SELECT c.reltuples::bigint AS estimate
FROM   pg_class c
JOIN   pg_namespace n ON n.oid = c.relnamespace
WHERE  c.relname = 'mytable'
AND    n.nspname = 'myschema'

Or better still

SELECT reltuples::bigint AS estimate
FROM   pg_class
WHERE  oid = 'myschema.mytable'::regclass;

Faster, simpler, safer, more elegant. See the manual on Object Identifier Types.

Use to_regclass('myschema.mytable') in Postgres 9.4+ to avoid exceptions for invalid table names:


TABLESAMPLE SYSTEM (n) in Postgres 9.5+

SELECT 100 * count(*) AS estimate FROM mytable TABLESAMPLE SYSTEM (1);

Like @a_horse commented, the newly added clause for the SELECT command might be useful if statistics in pg_class are not current enough for some reason. For example:

  • No autovacuum running.
  • Immediately after a big INSERT or DELETE.
  • TEMPORARY tables (which are not covered by autovacuum).

This only looks at a random n % (1 in the example) selection of blocks and counts rows in it. A bigger sample increases the cost and reduces the error, your pick. Accuracy depends on more factors:

  • Distribution of row size. If a given block happens to hold wider than usual rows, the count is lower than usual etc.
  • Dead tuples or a FILLFACTOR occupy space per block. If unevenly distributed across the table, the estimate may be off.
  • General rounding errors.

In most cases the estimate from pg_class will be faster and more accurate.

Answer to actual question

First, I need to know the number of rows in that table, if the total count is greater than some predefined constant,

And whether it ...

... is possible at the moment the count pass my constant value, it will stop the counting (and not wait to finish the counting to inform the row count is greater).

Yes. You can use a subquery with LIMIT:

SELECT count(*) FROM (SELECT 1 FROM token LIMIT 500000) t;

Postgres actually stops counting beyond the given limit, you get an exact and current count for up to n rows (500000 in the example), and n otherwise. Not nearly as fast as the estimate in pg_class, though.

How can I check if an array contains a specific value in php?

Using dynamic variable for search in array

 /* https://ideone.com/Pfb0Ou */

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');

/* variable search */
$search = 'living_room';

if (in_array($search, $array)) {
    echo "this array contains $search";
} else
    echo "this array NOT contains $search";

How to determine CPU and memory consumption from inside a process?

Linux

A portable way of reading memory and load numbers is the sysinfo call

Usage

   #include <sys/sysinfo.h>

   int sysinfo(struct sysinfo *info);

DESCRIPTION

   Until Linux 2.3.16, sysinfo() used to return information in the
   following structure:

       struct sysinfo {
           long uptime;             /* Seconds since boot */
           unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
           unsigned long totalram;  /* Total usable main memory size */
           unsigned long freeram;   /* Available memory size */
           unsigned long sharedram; /* Amount of shared memory */
           unsigned long bufferram; /* Memory used by buffers */
           unsigned long totalswap; /* Total swap space size */
           unsigned long freeswap;  /* swap space still available */
           unsigned short procs;    /* Number of current processes */
           char _f[22];             /* Pads structure to 64 bytes */
       };

   and the sizes were given in bytes.

   Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure
   is:

       struct sysinfo {
           long uptime;             /* Seconds since boot */
           unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
           unsigned long totalram;  /* Total usable main memory size */
           unsigned long freeram;   /* Available memory size */
           unsigned long sharedram; /* Amount of shared memory */
           unsigned long bufferram; /* Memory used by buffers */
           unsigned long totalswap; /* Total swap space size */
           unsigned long freeswap;  /* swap space still available */
           unsigned short procs;    /* Number of current processes */
           unsigned long totalhigh; /* Total high memory size */
           unsigned long freehigh;  /* Available high memory size */
           unsigned int mem_unit;   /* Memory unit size in bytes */
           char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding to 64 bytes */
       };

   and the sizes are given as multiples of mem_unit bytes.

How to serialize object to CSV file?

I wrote a simple class that uses OpenCSV and has two static public methods.

static public File toCSVFile(Object object, String path, String name) {
    File pathFile = new File(path);
    pathFile.mkdirs();
    File returnFile = new File(path + name);
    try {

        CSVWriter writer = new CSVWriter(new FileWriter(returnFile));
        writer.writeNext(new String[]{"Member Name in Code", "Stored Value", "Type of Value"});
        for (Field field : object.getClass().getDeclaredFields()) {
            writer.writeNext(new String[]{field.getName(), field.get(object).toString(), field.getType().getName()});
        }
        writer.flush();
        writer.close();
        return returnFile;
    } catch (IOException e) {
        Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e);
        return null;
    } catch (IllegalAccessException e) {
        Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e);
        return null;
    }
}

static public void fromCSVFile(Object object, File file) {
    try {
        CSVReader reader = new CSVReader(new FileReader(file));
        String[] nextLine = reader.readNext(); // Ignore the first line.
        while ((nextLine = reader.readNext()) != null) {
            if (nextLine.length >= 2) {
                try {
                    Field field = object.getClass().getDeclaredField(nextLine[0]);
                    Class<?> rClass = field.getType();
                    if (rClass == String.class) {
                        field.set(object, nextLine[1]);
                    } else if (rClass == int.class) {
                        field.set(object, Integer.parseInt(nextLine[1]));
                    } else if (rClass == boolean.class) {
                        field.set(object, Boolean.parseBoolean(nextLine[1]));
                    } else if (rClass == float.class) {
                        field.set(object, Float.parseFloat(nextLine[1]));
                    } else if (rClass == long.class) {
                        field.set(object, Long.parseLong(nextLine[1]));
                    } else if (rClass == short.class) {
                        field.set(object, Short.parseShort(nextLine[1]));
                    } else if (rClass == double.class) {
                        field.set(object, Double.parseDouble(nextLine[1]));
                    } else if (rClass == byte.class) {
                        field.set(object, Byte.parseByte(nextLine[1]));
                    } else if (rClass == char.class) {
                        field.set(object, nextLine[1].charAt(0));
                    } else {
                        Log.e("EasyStorage", "Easy Storage doesn't yet support extracting " + rClass.getSimpleName() + " from CSV files.");
                    }
                } catch (NoSuchFieldException e) {
                    Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
                } catch (IllegalAccessException e) {
                    Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);

                }
            } // Close if (nextLine.length >= 2)
        } // Close while ((nextLine = reader.readNext()) != null)
    } catch (FileNotFoundException e) {
        Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
    } catch (IOException e) {
        Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
    } catch (IllegalArgumentException e) {
        Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
    }
}

I think with some simple recursion these methods could be modified to handle any Java object, but for me this was adequate.

How to mock location on device?

Add to your manifest

<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"
    tools:ignore="MockLocation,ProtectedPermissions" />

Mock location function

void setMockLocation() {
    LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    locationManager.addTestProvider(LocationManager.GPS_PROVIDER, false, false,
            false, false, true, true, true, 0, 5);
    locationManager.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);

    Location mockLocation = new Location(LocationManager.GPS_PROVIDER);
    mockLocation.setLatitude(-33.852);  // Sydney
    mockLocation.setLongitude(151.211);
    mockLocation.setAltitude(10);
    mockLocation.setAccuracy(5);
    mockLocation.setTime(System.currentTimeMillis());
    mockLocation.setElapsedRealtimeNanos(System.nanoTime());
    locationManager.setTestProviderLocation(LocationManager.GPS_PROVIDER, mockLocation);
}

You'll also need to enable mock locations in your devices developer settings. If that's not available, set the "mock location application" to your application once the above has been implemented.

How do I create a Bash alias?

It works for me on macOS Majave

You can do a few simple steps:

1) open terminal

2) sudo nano /.bash_profile

3) add your aliases, as example:

# some aliases
alias ll='ls -alF'
alias la='ls -A'
alias eb="sudo nano ~/.bash_profile && source ~/.bash_profile"
#docker aliases
alias d='docker'
alias dc='docker-compose'
alias dnax="docker rm $(docker ps -aq)"
#git aliases
alias g='git'
alias new="git checkout -b"
alias last="git log -2"
alias gg='git status'
alias lg="git log --pretty=format:'%h was %an, %ar, message: %s' --graph"
alias nah="git reset --hard && git clean -df"
alias squash="git rebase -i HEAD~2"

4) source /.bash_profile

Done. Use and enjoy!

With block equivalent in C#?

For me I was trying to auto generate code, and needed to reuse a simple variable like "x" for multiple different classes so that I didn't have to keep generating new variable names. I found that I could limit the scope of a variable and reuse it multiple times if I just put the code in a curly brace section {}.

See the example:

public class Main
{
    public void Execute()
    {
        // Execute new Foos and new Bars many times with same variable.
        double a = 0;
        double b = 0;
        double c = 0;
        double d = 0;
        double e = 0;
        double f = 0;

        double length = 0;
        double area = 0;
        double size = 0;

        {
            Foo x = new Foo(5, 6).Execute();
            a = x.A;
            b = x.B;
            c = x.C;
            d = x.D;
            e = x.E;
            f = x.F;
        }
        {
            Bar x = new Bar("red", "circle").Execute();
            length = x.Length;
            area = x.Area;
            size = x.Size;
        }
        {
            Foo x = new Foo(3, 10).Execute();
            a = x.A;
            b = x.B;
            c = x.C;
            d = x.D;
            e = x.E;
            f = x.F;
        }
        {
            Bar x = new Bar("blue", "square").Execute();
            length = x.Length;
            area = x.Area;
            size = x.Size;
        }
    }
}

public class Foo
{
    public int X { get; set; }
    public int Y { get; set; }
    public double A { get; private set; }
    public double B { get; private set; }
    public double C { get; private set; }
    public double D { get; private set; }
    public double E { get; private set; }
    public double F { get; private set; }

    public Foo(int x, int y)
    {
        X = x;
        Y = y;
    }

    public Foo Execute()
    {
        A = X * Y;
        B = X + Y;
        C = X / (X + Y + 1);
        D = Y / (X + Y + 1);
        E = (X + Y) / (X + Y + 1);
        F = (Y - X) / (X + Y + 1);
        return this;
    }
}

public class Bar
{
    public string Color { get; set; }
    public string Shape { get; set; }
    public double Size { get; private set; }
    public double Area { get; private set; }
    public double Length { get; private set; }
    
    public Bar(string color, string shape)
    {
        Color = color;
        Shape = shape;
    }

    public Bar Execute()
    {
        Length = Color.Length + Shape.Length;
        Area = Color.Length * Shape.Length;
        Size = Area * Length;
        return this;
    }
}

In VB I would have used the With and not needed variable "x" at all. Excluding the vb class definitions of Foo and Bar, the vb code is:

Public Class Main
    Public Sub Execute()
        Dim a As Double = 0
        Dim b As Double = 0
        Dim c As Double = 0
        Dim d As Double = 0
        Dim e As Double = 0
        Dim f As Double = 0
        Dim length As Double = 0
        Dim area As Double = 0
        Dim size As Double = 0

        With New Foo(5, 6).Execute()
            a = .A
            b = .B
            c = .C
            d = .D
            e = .E
            f = .F
        End With

        With New Bar("red", "circle").Execute()
            length = .Length
            area = .Area
            size = .Size
        End With

        With New Foo(3, 10).Execute()
            a = .A
            b = .B
            c = .C
            d = .D
            e = .E
            f = .F
        End With

        With New Bar("blue", "square").Execute()
            length = .Length
            area = .Area
            size = .Size
        End With
    End Sub
End Class

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

use labelpad parameter:

pl.xlabel("...", labelpad=20)

or set it after:

ax.xaxis.labelpad = 20

How to get height of entire document with JavaScript?

Add References properly

In my case I was using a ASCX page and the aspx page that contains the ascx control is not using the references properly. I just pasted the following code and it worked :

<script src="../js/jquery-1.3.2-vsdoc.js" type="text/javascript"></script>
<script src="../js/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../js/jquery-1.5.1.js" type="text/javascript"></script>

How to remove border from specific PrimeFaces p:panelGrid?

As mentioned by BalusC, the border is set by PrimeFaces on the generated tr and td elements, not on the table. However when trying with PrimeFaces version 5, it looks like there is a more specific match from the PrimeFaces CSS .ui-panelgrid .ui-panelgrid-cell > solid which still result in black borders being shown when appyling the style suggested.

Try using following style in order to overide the Primefaces one without using the !important declaration:

.companyHeaderGrid tr, .companyHeaderGrid td.ui-panelgrid-cell {
    border: none;
}

As mention make sure your CSS is loaded after the PrimeFaces one.

No output to console from a WPF application?

Right click on the project, "Properties", "Application" tab, change "Output Type" to "Console Application", and then it will also have a console.

Check status of one port on remote host

In Bash, you can use pseudo-device files which can open a TCP connection to the associated socket. The syntax is /dev/$tcp_udp/$host_ip/$port.

Here is simple example to test whether Memcached is running:

</dev/tcp/localhost/11211 && echo Port open || echo Port closed

Here is another test to see if specific website is accessible:

$ echo "HEAD / HTTP/1.0" > /dev/tcp/example.com/80 && echo Connection successful.
Connection successful.

For more info, check: Advanced Bash-Scripting Guide: Chapter 29. /dev and /proc.

Related: Test if a port on a remote system is reachable (without telnet) at SuperUser.

For more examples, see: How to open a TCP/UDP socket in a bash shell (article).

How can I add an item to a SelectList in ASP.net MVC

There really isn't a need to do this unless you insist on the value of 0. The HtmlHelper DropDownList extension allows you to set an option label that shows up as the initial value in the select with a null value. Simply use one of the DropDownList signatures that has the option label.

<%= Html.DropDownList( "DropDownValue",
                       (IEnumerable<SelectListItem>)ViewData["Menu"],
                        "-- Select One --" ) %>

How to output something in PowerShell

I think in this case you will need Write-Output.

If you have a script like

Write-Output "test1";
Write-Host "test2";
"test3";

then, if you call the script with redirected output, something like yourscript.ps1 > out.txt, you will get test2 on the screen test1\ntest3\n in the "out.txt".

Note that "test3" and the Write-Output line will always append a new line to your text and there is no way in PowerShell to stop this (that is, echo -n is impossible in PowerShell with the native commands). If you want (the somewhat basic and easy in Bash) functionality of echo -n then see samthebest's answer.

If a batch file runs a PowerShell command, it will most likely capture the Write-Output command. I have had "long discussions" with system administrators about what should be written to the console and what should not. We have now agreed that the only information if the script executed successfully or died has to be Write-Host'ed, and everything that is the script's author might need to know about the execution (what items were updated, what fields were set, et cetera) goes to Write-Output. This way, when you submit a script to the system administrator, he can easily runthescript.ps1 >someredirectedoutput.txt and see on the screen, if everything is OK. Then send the "someredirectedoutput.txt" back to the developers.

Get GPS location from the web browser

If you use the Geolocation API, it would be as simple as using the following code.

navigator.geolocation.getCurrentPosition(function(location) {
  console.log(location.coords.latitude);
  console.log(location.coords.longitude);
  console.log(location.coords.accuracy);
});

You may also be able to use Google's Client Location API.

This issue has been discussed in Is it possible to detect a mobile browser's GPS location? and Get position data from mobile browser. You can find more information there.

Setting CSS pseudo-class rules from JavaScript

In jquery you can easily set hover pseudo classes.

$("p").hover(function(){
$(this).css("background-color", "yellow");
}, function(){
$(this).css("background-color", "pink");
});

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

I had the same problem, changing my gmail password fixed the issue, and also don't forget to enable less secure app on on your gmail account

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

How to detect installed version of MS-Office?

How about HKEY_CLASSES_ROOT\Word.Application\CurVer?

Text in HTML Field to disappear when clicked?

What you want to do is use the HTML5 attribute placeholder which lets you set a default value for your input box:

<input type="text" name="inputBox" placeholder="enter your text here">

This should achieve what you're looking for. However, be careful because the placeholder attribute is not supported in Internet Explorer 9 and earlier versions.

How to Calculate Jump Target Address and Branch Target Address?

I think it would be quite hard to calculate those because the branch target address is determined at run time and that prediction is done in hardware. If you explained the problem a bit more in depth and described what you are trying to do it would be a little easier to help. (:

Show div on scrollDown after 800px

If you want to show a div after scrolling a number of pixels:

Working Example

$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 800) {
    $('.bottomMenu').fadeIn();
  } else {
    $('.bottomMenu').fadeOut();
  }
});

_x000D_
_x000D_
$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 800) {
    $('.bottomMenu').fadeIn();
  } else {
    $('.bottomMenu').fadeOut();
  }
});
_x000D_
body {
  height: 1600px;
}
.bottomMenu {
  display: none;
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  border-top: 1px solid #000;
  background: red;
  z-index: 1;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll down... </p>
<div class="bottomMenu"></div>
_x000D_
_x000D_
_x000D_

Its simple, but effective.

Documentation for .scroll()
Documentation for .scrollTop()


If you want to show a div after scrolling a number of pixels,

without jQuery:

Working Example

myID = document.getElementById("myID");

var myScrollFunc = function() {
  var y = window.scrollY;
  if (y >= 800) {
    myID.className = "bottomMenu show"
  } else {
    myID.className = "bottomMenu hide"
  }
};

window.addEventListener("scroll", myScrollFunc);

_x000D_
_x000D_
myID = document.getElementById("myID");

var myScrollFunc = function() {
  var y = window.scrollY;
  if (y >= 800) {
    myID.className = "bottomMenu show"
  } else {
    myID.className = "bottomMenu hide"
  }
};

window.addEventListener("scroll", myScrollFunc);
_x000D_
body {
  height: 2000px;
}
.bottomMenu {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  border-top: 1px solid #000;
  background: red;
  z-index: 1;
  transition: all 1s;
}
.hide {
  opacity: 0;
  left: -100%;
}
.show {
  opacity: 1;
  left: 0;
}
_x000D_
<div id="myID" class="bottomMenu hide"></div>
_x000D_
_x000D_
_x000D_

Documentation for .scrollY
Documentation for .className
Documentation for .addEventListener


If you want to show an element after scrolling to it:

Working Example

$('h1').each(function () {
    var y = $(document).scrollTop();
    var t = $(this).parent().offset().top;
    if (y > t) {
        $(this).fadeIn();
    } else {
        $(this).fadeOut();
    }
});

_x000D_
_x000D_
$(document).scroll(function() {
  //Show element after user scrolls 800px
  var y = $(this).scrollTop();
  if (y > 800) {
    $('.bottomMenu').fadeIn();
  } else {
    $('.bottomMenu').fadeOut();
  }

  // Show element after user scrolls past 
  // the top edge of its parent 
  $('h1').each(function() {
    var t = $(this).parent().offset().top;
    if (y > t) {
      $(this).fadeIn();
    } else {
      $(this).fadeOut();
    }
  });
});
_x000D_
body {
  height: 1600px;
}
.bottomMenu {
  display: none;
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  border-top: 1px solid #000;
  background: red;
  z-index: 1;
}
.scrollPast {
  width: 100%;
  height: 150px;
  background: blue;
  position: relative;
  top: 50px;
  margin: 20px 0;
}
h1 {
  display: none;
  position: absolute;
  bottom: 0;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll Down...</p>
<div class="scrollPast">
  <h1>I fade in when you scroll to my parent</h1>

</div>
<div class="scrollPast">
  <h1>I fade in when you scroll to my parent</h1>

</div>
<div class="scrollPast">
  <h1>I fade in when you scroll to my parent</h1>

</div>
<div class="bottomMenu">I fade in when you scroll past 800px</div>
_x000D_
_x000D_
_x000D_

Note that you can't get the offset of elements set to display: none;, grab the offset of the element's parent instead.

Documentation for .each()
Documentation for .parent()
Documentation for .offset()


If you want to have a nav or div stick or dock to the top of the page once you scroll to it and unstick/undock when you scroll back up:

Working Example

$(document).scroll(function () {
    //stick nav to top of page
    var y = $(this).scrollTop();
    var navWrap = $('#navWrap').offset().top;
    if (y > navWrap) {
        $('nav').addClass('sticky');
    } else {
        $('nav').removeClass('sticky');
    }
});

#navWrap {
    height:70px
}
nav {
    height: 70px;
    background:gray;
}
.sticky {
    position: fixed;
    top:0;
}

_x000D_
_x000D_
$(document).scroll(function () {
    //stick nav to top of page
    var y = $(this).scrollTop();
    var navWrap = $('#navWrap').offset().top;
    if (y > navWrap) {
        $('nav').addClass('sticky');
    } else {
        $('nav').removeClass('sticky');
    }
});
_x000D_
body {
    height:1600px;
    margin:0;
}
#navWrap {
    height:70px
}
nav {
    height: 70px;
    background:gray;
}
.sticky {
    position: fixed;
    top:0;
}
h1 {
    margin: 0;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas,
  imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum
  oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
<div id="navWrap">
  <nav>
    <h1>I stick to the top when you scroll down and unstick when you scroll up to my original position</h1>

  </nav>
</div>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas,
  imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum
  oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
_x000D_
_x000D_
_x000D_

Javascript dynamic array of strings

Here is an example. You enter a number (or whatever) in the textbox and press "add" to put it in the array. Then you press "show" to show the array items as elements.

<script type="text/javascript">

var arr = [];

function add() {
   var inp = document.getElementById('num');
   arr.push(inp.value);
   inp.value = '';
}

function show() {
   var html = '';
   for (var i=0; i<arr.length; i++) {
      html += '<div>' + arr[i] + '</div>';
   }
   var con = document.getElementById('container');
   con.innerHTML = html;
}

</script>

<input type="text" id="num" />
<input type="button" onclick="add();" value="add" />
<br />
<input type="button" onclick="show();" value="show" />
<div id="container"></div>

Get current date/time in seconds

On some day in 2020, inside Chrome 80.0.3987.132, this gives 1584533105

~~(new Date()/1000) // 1584533105
Number.isInteger(~~(new Date()/1000)) // true

Issue with background color and Google Chrome

Oddly enough it doesn't actually happen on every page and it doesn't seem to always work even when refreshed.

My solutions was to add {height: 100%;} as well.

Foreach loop in java for a custom object list

Using can also use Java 8 stream API and do the same thing in one line.

If you want to print any specific property then use this syntax:

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> System.out.println(room.getName()));

OR

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> {
    // here room is available
});

if you want to print all the properties of Java object then use this:

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(System.out::println);

Using multiple delimiters in awk

If your whitespace is consistent you could use that as a delimiter, also instead of inserting \t directly, you could set the output separator and it will be included automatically:

< file awk -v OFS='\t' -v FS='[/ ]' '{print $3, $5, $NF}'

Is a DIV inside a TD a bad idea?

Two ways of dealing with it

  1. put div inside tbody tag
  2. put div inside tr tag

Both approaches are valid, if you see feference: https://stackoverflow.com/a/23440419/2305243

Importing CommonCrypto in a Swift framework

This answer discusses how to make it work inside a framework, and with Cocoapods and Carthage

modulemap approach

I use modulemap in my wrapper around CommonCrypto https://github.com/onmyway133/arcane, https://github.com/onmyway133/Reindeer

For those getting header not found, please take a look https://github.com/onmyway133/Arcane/issues/4 or run xcode-select --install

  • Make a folder CCommonCrypto containing module.modulemap

      module CCommonCrypto {
        header "/usr/include/CommonCrypto/CommonCrypto.h"
        export *
      }
    
  • Go to Built Settings -> Import Paths

      ${SRCROOT}/Sources/CCommonCrypto
    

Cocoapods with modulemap approach

public header approach

Cocoapods with public header approach

Interesting related posts

How do I add an integer value with javascript (jquery) to a value that's returning a string?

parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.

var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);

How do I save a String to a text file using Java?

Use Apache Commons IO api. Its simple

Use API as

 FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");

Maven Dependency

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

Android Drawing Separator/Divider Line in Layout?

For example if you used recyclerView for yours items:

in build.gradle write:

dependencies {
    compile 'com.yqritc:recyclerview-flexibledivider:1.4.0'

If you want to set color, size and margin values, you can specify as the followings:

RecyclerView recyclerView = (RecyclerView) 
findViewById(R.id.recyclerview);
recyclerView.addItemDecoration(
        new HorizontalDividerItemDecoration.Builder(this)
                .color(Color.RED)
                .sizeResId(R.dimen.divider)
                .marginResId(R.dimen.leftmargin, R.dimen.rightmargin)
                .build());

Visual Studio 2010 always thinks project is out of date, but nothing has changed

For me, the problem arose in a WPF project where some files had their 'Build Action' property set to 'Resource' and their 'Copy to Output Directory' set to 'Copy if newer'. The solution seemed to be to change the 'Copy to Output Directory' property to 'Do not copy'.

msbuild knows not to copy 'Resource' files to the output - but still triggers a build if they're not there. Maybe that could be considered a bug?

It's hugely helpful with the answers here hinting how to get msbuild to spill the beans on why it keeps building everything!

How to send a POST request using volley with string body?

I liked this one, but it is sending JSON not string as requested in the question, reposting the code here, in case the original github got removed or changed, and this one found to be useful by someone.

public static void postNewComment(Context context,final UserAccount userAccount,final String comment,final int blogId,final int postId){
    mPostCommentResponse.requestStarted();
    RequestQueue queue = Volley.newRequestQueue(context);
    StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            mPostCommentResponse.requestCompleted();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mPostCommentResponse.requestEndedWithError(error);
        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put("user",userAccount.getUsername());
            params.put("pass",userAccount.getPassword());
            params.put("comment", Uri.encode(comment));
            params.put("comment_post_ID",String.valueOf(postId));
            params.put("blogId",String.valueOf(blogId));

            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("Content-Type","application/x-www-form-urlencoded");
            return params;
        }
    };
    queue.add(sr);
}

public interface PostCommentResponseListener {
    public void requestStarted();
    public void requestCompleted();
    public void requestEndedWithError(VolleyError error);
}

Update R using RStudio

I would recommend using the Windows package installr to accomplish this. Not only will the package update your R version, but it will also copy and update all of your packages. There is a blog on the subject here. Simply run the following commands in R Studio and follow the prompts:

# installing/loading the package:
if(!require(installr)) {
install.packages("installr"); require(installr)} #load / install+load installr

# using the package:
updateR() # this will start the updating process of your R installation.  It will check for newer versions, and if one is available, will guide you through the decisions you'd need to make.

increase the java heap size permanently?

Apparently, _JAVA_OPTIONS works on Linux, too:

$ export _JAVA_OPTIONS="-Xmx1g"
$ java -jar jconsole.jar &
Picked up _JAVA_OPTIONS: -Xmx1g

How to show only next line after the matched one?

you can try with awk:

awk '/blah/{getline; print}' logfile

Check if inputs form are empty jQuery

$('input[type="text"]').get().some(item => item.value !== '');

check if a number already exist in a list in python

If you want your numbers in ascending order you can add them into a set and then sort the set into an ascending list.

s = set()
if number1 not in s:
  s.add(number1)
if number2 not in s:
  s.add(number2)
...
s = sorted(s)  #Now a list in ascending order

Removing an element from an Array (Java)

Nice looking solution would be to use a List instead of array in the first place.

List.remove(index)

If you have to use arrays, two calls to System.arraycopy will most likely be the fastest.

Foo[] result = new Foo[source.length - 1];
System.arraycopy(source, 0, result, 0, index);
if (source.length != index) {
    System.arraycopy(source, index + 1, result, index, source.length - index - 1);
}

(Arrays.asList is also a good candidate for working with arrays, but it doesn't seem to support remove.)

How to change package name of an Android Application

  1. Fist change the package name in the manifest file
  2. Re-factor > Rename the name of the package in src folder and put a tick for rename subpackages
  3. That is all you are done.

.NET console application as Windows service

Here is a newer way of how to turn a Console Application to a Windows Service as a Worker Service based on the latest .Net Core 3.1.

If you create a Worker Service from Visual Studio 2019 it will give you almost everything you need for creating a Windows Service out of the box, which is also what you need to change to the console application in order to convert it to a Windows Service.

Here are the changes you need to do:

Install the following NuGet packages

Install-Package Microsoft.Extensions.Hosting.WindowsServices -Version 3.1.0
Install-Package Microsoft.Extensions.Configuration.Abstractions -Version 3.1.0

Change Program.cs to have an implementation like below:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ConsoleApp
{
    class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).UseWindowsService().Build().Run();
        }

        private static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                });
    }
}

and add Worker.cs where you will put the code which will be run by the service operations:

using Microsoft.Extensions.Hosting;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class Worker : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //do some operation
        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }
    }
}

When everything is ready, and the application has built successfully, you can use sc.exe to install your console application exe as a Windows Service with the following command:

sc.exe create DemoService binpath= "path/to/your/file.exe"

Sort an Array by keys based on another Array?

Take one array as your order:

$order = array('north', 'east', 'south', 'west');

You can sort another array based on values using array_intersect­Docs:

/* sort by value: */
$array = array('south', 'west', 'north');
$sorted = array_intersect($order, $array);
print_r($sorted);

Or in your case, to sort by keys, use array_intersect_key­Docs:

/* sort by key: */
$array = array_flip($array);
$sorted = array_intersect_key(array_flip($order), $array);
print_r($sorted);

Both functions will keep the order of the first parameter and will only return the values (or keys) from the second array.

So for these two standard cases you don't need to write a function on your own to perform the sorting/re-arranging.

How to perform case-insensitive sorting in JavaScript?

This may help if you have struggled to understand:

var array = ["sort", "Me", "alphabetically", "But", "Ignore", "case"];
console.log('Unordered array ---', array, '------------');

array.sort(function(a,b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    console.log("Compare '" + a + "' and '" + b + "'");

    if( a == b) {
        console.log('Comparison result, 0 --- leave as is ');
        return 0;
    }
    if( a > b) {
        console.log('Comparison result, 1 --- move '+b+' to before '+a+' ');
        return 1;
    }
    console.log('Comparison result, -1 --- move '+a+' to before '+b+' ');
    return -1;


});

console.log('Ordered array ---', array, '------------');


// return logic

/***
If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
***/

http://jsfiddle.net/ianjamieson/wmxn2ram/1/

How to allow only one radio button to be checked?

Add "name" attribute and keep the name same for all the radio buttons in a form.

i.e.,

<input type="radio" name="test" value="value1"> Value 1
<input type="radio" name="test" value="value2"> Value 2
<input type="radio" name="test" value="value3"> Value 3

Hope that would help.

Create Map in Java

Map <Integer, Point2D.Double> hm = new HashMap<Integer, Point2D>();
hm.put(1, new Point2D.Double(50, 50));

How to remove td border with html?

First

<table border="1">
      <tr>
        <td style='border:none;'>one</td>
        <td style='border:none;'>two</td>
      </tr>
      <tr>
        <td style='border:none;'>one</td>
        <td style='border:none;'>two</td>
    </tr>
    </table>

Second example

<table border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td style='border-left:none;border-top:none'>one</td>
    <td style='border:none;'>two</td>
  </tr>
  <tr>
    <td style='border-left:none;border-bottom:none;border-top:none'>one</td>
    <td style='border:none;'>two</td>
</tr>
</table>

Conditional Count on a field

IIF is not a standard SQL construct, but if it's supported by your database, you can achieve a more elegant statement producing the same result:

SELECT JobId, JobName,

COUNT(IIF (Priority=1, 1, NULL)) AS Priority1,
COUNT(IIF (Priority=2, 1, NULL)) AS Priority2,
COUNT(IIF (Priority=3, 1, NULL)) AS Priority3,
COUNT(IIF (Priority=4, 1, NULL)) AS Priority4,
COUNT(IIF (Priority=5, 1, NULL)) AS Priority5

FROM TableName
GROUP BY JobId, JobName

How connect Postgres to localhost server using pgAdmin on Ubuntu?

if you open the psql console in a terminal window, by typing

$ psql

you're super user username will be shown before the =#, for example:

elisechant=#$

That will be the user name you should use for localhost.

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

An explanation of the following error:

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already.

Summary:

You opened up more than the allowed limit of connections to the database. You ran something like this: Connection conn = myconn.Open(); inside of a loop, and forgot to run conn.close();. Just because your class is destroyed and garbage collected does not release the connection to the database. The quickest fix to this is to make sure you have the following code with whatever class that creates a connection:

protected void finalize() throws Throwable  
{  
    try { your_connection.close(); } 
    catch (SQLException e) { 
        e.printStackTrace();
    }
    super.finalize();  
}  

Place that code in any class where you create a Connection. Then when your class is garbage collected, your connection will be released.

Run this SQL to see postgresql max connections allowed:

show max_connections;

The default is 100. PostgreSQL on good hardware can support a few hundred connections at a time. If you want to have thousands, you should consider using connection pooling software to reduce the connection overhead.

Take a look at exactly who/what/when/where is holding open your connections:

SELECT * FROM pg_stat_activity;

The number of connections currently used is:

SELECT COUNT(*) from pg_stat_activity;

Debugging strategy

  1. You could give different usernames/passwords to the programs that might not be releasing the connections to find out which one it is, and then look in pg_stat_activity to find out which one is not cleaning up after itself.

  2. Do a full exception stack trace when the connections could not be created and follow the code back up to where you create a new Connection, make sure every code line where you create a connection ends with a connection.close();

How to set the max_connections higher:

max_connections in the postgresql.conf sets the maximum number of concurrent connections to the database server.

  1. First find your postgresql.conf file
  2. If you don't know where it is, query the database with the sql: SHOW config_file;
  3. Mine is in: /var/lib/pgsql/data/postgresql.conf
  4. Login as root and edit that file.
  5. Search for the string: "max_connections".
  6. You'll see a line that says max_connections=100.
  7. Set that number bigger, check the limit for your postgresql version.
  8. Restart the postgresql database for the changes to take effect.

What's the maximum max_connections?

Use this query:

select min_val, max_val from pg_settings where name='max_connections';

I get the value 8388607, in theory that's the most you are allowed to have, but then a runaway process can eat up thousands of connections, and surprise, your database is unresponsive until reboot. If you had a sensible max_connections like 100. The offending program would be denied a new connection.

Find commit by hash SHA in Git

Just use the following command

git show a2c25061

or (the exact equivalent):

git log -p -1 a2c25061

Is there any way to wait for AJAX response and halt execution?

The simple answer is to turn off async. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.

Instead of writing this:

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        }
    });
}

function foo () {
    var response = functABC();
    some_result = bar(response);
    // and other stuff and
    return some_result;
}

You should write it like this:

function functABC(callback){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: callback
    });
}

function foo (callback) {
    functABC(function(data){
        var response = data;
        some_result = bar(response);
        // and other stuff and
        callback(some_result);
    })
}

That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.


A quick explanation of why I say it's wrong to turn off async:

Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

How do I prevent and/or handle a StackOverflowException?

@WilliamJockusch, if I understood correctly your concern, it's not possible (from a mathematical point of view) to always identify an infinite recursion as it would mean to solve the Halting problem. To solve it you'd need a Super-recursive algorithm (like Trial-and-error predicates for example) or a machine that can hypercompute (an example is explained in the following section - available as preview - of this book).

From a practical point of view, you'd have to know:

  • How much stack memory you have left at the given time
  • How much stack memory your recursive method will need at the given time for the specific output.

Keep in mind that, with the current machines, this data is extremely mutable due to multitasking and I haven't heard of a software that does the task.

Let me know if something is unclear.

How can I remove file extension from a website address?

Tony, your script is ok, but if you have 100 files? Need add this code in all these :

include_once('scripts.php');
strip_php_extension();

I think you include a menu in each php file (probably your menu is showed in all your web pages), so you can add these 2 lines of code only in your menu file. This work for me :D

Removing elements by class name?

The skipping elements bug in this (code from above)

var len = cells.length;
for(var i = 0; i < len; i++) {
    if(cells[i].className.toLowerCase() == "column") {
        cells[i].parentNode.removeChild(cells[i]);
    }
}

can be fixed by just running the loop backwards as follows (so that the temporary array is not needed)

var len = cells.length;
for(var i = len-1; i >-1; i--) {
    if(cells[i].className.toLowerCase() == "column") {
        cells[i].parentNode.removeChild(cells[i]);
   }
}

How to create a list of objects?

You can create a list of objects in one line using a list comprehension.

class MyClass(object): pass

objs = [MyClass() for i in range(10)]

print(objs)

Parse an HTML string with JS

with this simple code you can do that:

let el = $('<div></div>');
$(document.body).append(el);
el.html(`<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>`);
console.log(el.find('a[href="test0"]'));

Get values from label using jQuery

var label = $('#current_month');
var month = label.val('month');
var year = label.val('year');
var text = label.text();
alert(text);

<label year="2010" month="6" id="current_month"> June &nbsp;2010</label>

header location not working in my php code

Try adding ob_start(); at the top of the code i.e. before the include statement.

What exactly is Spring Framework for?

Spring contains (as Skaffman rightly pointed out) a MVC framework. To explain in short here are my inputs. Spring supports segregation of service layer, web layer and business layer, but what it really does best is "injection" of objects. So to explain that with an example consider the example below:

public interface FourWheel
{
   public void drive();
}

public class Sedan implements FourWheel
{
   public void drive()
   {
      //drive gracefully
   }
}

public class SUV implements FourWheel
{
   public void drive()
   {
      //Rule the rough terrain
   }
}

Now in your code you have a class called RoadTrip as follows

public class RoadTrip
{
    private FourWheel myCarForTrip;
}

Now whenever you want a instance of Trip; sometimes you may want a SUV to initialize FourWheel or sometimes you may want Sedan. It really depends what you want based on specific situation.

To solve this problem you'd want to have a Factory Pattern as creational pattern. Where a factory returns the right instance. So eventually you'll end up with lots of glue code just to instantiate objects correctly. Spring does the job of glue code best without that glue code. You declare mappings in XML and it initialized the objects automatically. It also does lot using singleton architecture for instances and that helps in optimized memory usage.

This is also called Inversion Of Control. Other frameworks to do this are Google guice, Pico container etc.

Apart from this, Spring has validation framework, extensive support for DAO layer in collaboration with JDBC, iBatis and Hibernate (and many more). Provides excellent Transactional control over database transactions.

There is lot more to Spring that can be read up in good books like "Pro Spring".

Following URLs may be of help too.
http://static.springframework.org/docs/Spring-MVC-step-by-step/
http://en.wikipedia.org/wiki/Spring_Framework
http://www.theserverside.com/tt/articles/article.tss?l=SpringFramework

Removing elements from an array in C

Try this simple code:

#include <stdio.h>
#include <conio.h>
void main(void)
{ 
    clrscr();
    int a[4], i, b;
    printf("enter nos ");
    for (i = 1; i <= 5; i++) {
        scanf("%d", &a[i]);
    }
    for(i = 1; i <= 5; i++) {
        printf("\n%d", a[i]);
    }
    printf("\nenter element you want to delete ");
    scanf("%d", &b);
    for (i = 1; i <= 5; i++) {
        if(i == b) {
            a[i] = i++;
        }
        printf("\n%d", a[i]);
    }
    getch();
}

Bootstrap 4 Change Hamburger Toggler Color

You can create the toggler button with css only in a very easy way, there is no need to use any fonts in SVG or ... foramt.

Your Button:

<button 
     class="navbar-toggler collapsed" 
    data-target="#navbarsExampleDefault" 
    data-toggle="collapse">
        <span class="line"></span> 
        <span class="line"></span> 
        <span class="line"></span>
</button>

Your Button Style:

.navbar-toggler{
width: 47px;
height: 34px;
background-color: #7eb444;

}

Your horizontal line Style:

.navbar-toggler .line{
width: 100%;
float: left;
height: 2px;
background-color: #fff;
margin-bottom: 5px;

}

Demo

_x000D_
_x000D_
.navbar-toggler{_x000D_
    width: 47px;_x000D_
    height: 34px;_x000D_
    background-color: #7eb444;_x000D_
    border:none;_x000D_
}_x000D_
.navbar-toggler .line{_x000D_
    width: 100%;_x000D_
    float: left;_x000D_
    height: 2px;_x000D_
    background-color: #fff;_x000D_
    margin-bottom: 5px;_x000D_
}
_x000D_
<button class="navbar-toggler" data-target="#navbarsExampleDefault" data-toggle="collapse" aria-expanded="true" >_x000D_
        <span class="line"></span> _x000D_
        <span class="line"></span> _x000D_
        <span class="line" style="margin-bottom: 0;"></span>_x000D_
</button>
_x000D_
_x000D_
_x000D_

Converting a double to an int in Javascript without rounding

As @Quentin and @Pointy pointed out in their comments, it's not a good idea to use parseInt() because it is designed to convert a string to an integer. When you pass a decimal number to it, it first converts the number to a string, then casts it to an integer. I suggest you use Math.trunc(), Math.floor(), ~~num, ~~v , num | 0, num << 0, or num >> 0 depending on your needs. This performance test demonstrates the difference in parseInt() and Math.floor() performance. Also, this post explains the difference between the proposed methods.

Automatically deleting related rows in Laravel (Eloquent ORM)

Relation in User model:

public function photos()
{
    return $this->hasMany('Photo');
}

Delete record and related:

$user = User::find($id);

// delete related   
$user->photos()->delete();

$user->delete();

Best Practices for mapping one object to another

This is a possible generic implementation using a bit of reflection (pseudo-code, don't have VS now):

public class DtoMapper<DtoType>
{
    Dictionary<string,PropertyInfo> properties;

    public DtoMapper()
    {
        // Cache property infos
        var t = typeof(DtoType);
        properties = t.GetProperties().ToDictionary(p => p.Name, p => p);
     }

    public DtoType Map(Dto dto)
    {
        var instance = Activator.CreateInstance(typeOf(DtoType));

        foreach(var p in properties)
        {
            p.SetProperty(
                instance, 
                Convert.Type(
                    p.PropertyType, 
                    dto.Items[Array.IndexOf(dto.ItemsNames, p.Name)]);

            return instance;
        }
    }

Usage:

var mapper = new DtoMapper<Model>();
var modelInstance = mapper.Map(dto);

This will be slow when you create the mapper instance but much faster later.

How do I check for null values in JavaScript?

At first sight, it looks like a simple trade-off between coverage and strictness.

  • == covers multiple values, can handle more scenarios in less code.
  • === is the most strict, and that makes it predictable.

Predictability always wins, and that appears to make === a one-fits-all solution.

enter image description here

But it is wrong. Even though === is predictable, it does not always result in predictable code, because it overlooks scenarios.

const options = { };
if (options.callback !== null) {
  options.callback();      // error --> callback is undefined.
}

In general == does a more predictable job for null checks:

  • In general, null and undefined both mean the same thing: "something's missing". For predictability, you need to check both values. And then == null does a perfect job, because it covers exactly those 2 values. (i.e. == null is equivalent to === null && === undefined)

  • In exceptional cases you do want a clear distinction between null and undefined. And in those cases you're better of with a strict === undefined or === null. (e.g. a distinction between missing/ignore/skip and empty/clear/remove.) But it is rare.

It is not only rare, it's something to avoid. You can't store undefined in a traditional database. And you shouldn't rely on undefined values in your API designs neither, due to interopability reasons. But even when you don't make a distinction at all, you can't assume that undefined won't happen. People all around us indirectly take actions that generalize null/undefined (which is why questions like this are closed as "opinionated".).

So, to get back to your question. There's nothing wrong with using == null. It does exactly what it should do.

// FIX 1 --> yes === is very explicit
const options = { };
if (options.callback !== null && 
    options.callback !== undefined) {
  options.callback();
}


// FIX 2 --> but == is more accurate here
const options = { };
if (options.callback != null) {
  options.callback();
}

How to clear radio button in Javascript?

In my case this got the job done:

const chbx = document.getElementsByName("input_name");

for(let i=0; i < chbx.length; i++) {
    chbx[i].checked = false;
}

javascript code to check special characters

Directly from the w3schools website:

   var str = "The best things in life are free";
   var patt = new RegExp("e");
   var res = patt.test(str);

To combine their example with a regular expression, you could do the following:

function checkUserName() {
    var username = document.getElementsByName("username").value;
    var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
    if (pattern.test(username)) {
        alert("Please only use standard alphanumerics");
        return false;
    }
    return true; //good user input
}

Cleanest way to reset forms

The simplest method to clear a form with a button in angular2+ is

give your form a name using #

<form #your_form_name (ngSubmit)="submitData()"> </form>

<button (click)="clearForm(Your_form_name)"> clear form </button>

in your component.ts file

clearForm(form: FormGroup) {
form.reset();
}

how to delete installed library form react native project

I will post my answer here since it's the first result in google's search

1) react-native unlink <Module Name>

2) npm unlink <Module Name>

3) npm uninstall --save <Module name

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

Convert JavaScript String to be all lower case?

Try

<input type="text" style="text-transform: uppercase">  //uppercase
<input type="text" style="text-transform: lowercase">  //lowercase

Demo - JSFiddle

Resolve host name to an ip address

Windows XP has the Windows Firewall which can interfere with network traffic if not configured properly. You can turn off the Windows Firewall, if you have administrator privileges, by accessing the Windows Firewall applet through the Control Panel. If your application works with the Windows Firewall turned off then the problem is probably due to the settings of the firewall.

We have an application which runs on multiple PCs communicating using UDP/IP and we have been doing experiments so that the application can run on a PC with a user who does not have administrator privileges. In order for our application to communicate between multiple PCs we have had to use an administrator account to modify the Windows Firewall settings.

In our application, one PC is designated as the server and the others are clients in a server/client group and there may be several groups on the same subnet.

The first change was to use the functionality of the Exceptions tab of the Windows Firewall applet to create an exception for the port that we use for communication.

We are using host name lookup so that the clients can locate their assigned server by using the computer name which is composed of a mnemonic prefix with a dash followed by an assigned terminal number (for instance SERVER100-1). This allows several servers with their assigned clients to coexist on the same subnet. The client uses its prefix to generate the computer name for the assigned server and to then use host name lookup to discover the IP address of the assigned server.

What we found is that the host name lookup using the computer name (assigned through the Computer Name tab of the System Properties dialog) would not work unless the server PC's Windows Firewall had the File and Printer Sharing Service port enabled.

So we had to make two changes: (1) setup an exception for the port we used for communication and (2) enable File and Printer Service in the Exceptions tab to allow for the host name lookup.

** EDIT **

You may also find this Microsoft Knowledge Base article on helpful on Windows XP networking.

And see this article on NETBIOS name resolution in Windows.

How to perform string interpolation in TypeScript?

Just use special `

var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;

You can see more examples here.

How to create streams from string in Node.Js?

JavaScript is duck-typed, so if you just copy a readable stream's API, it'll work just fine. In fact, you can probably not implement most of those methods or just leave them as stubs; all you'll need to implement is what the library uses. You can use Node's pre-built EventEmitter class to deal with events, too, so you don't have to implement addListener and such yourself.

Here's how you might implement it in CoffeeScript:

class StringStream extends require('events').EventEmitter
  constructor: (@string) -> super()

  readable: true
  writable: false

  setEncoding: -> throw 'not implemented'
  pause: ->    # nothing to do
  resume: ->   # nothing to do
  destroy: ->  # nothing to do
  pipe: -> throw 'not implemented'

  send: ->
    @emit 'data', @string
    @emit 'end'

Then you could use it like so:

stream = new StringStream someString
doSomethingWith stream
stream.send()

How do I plot list of tuples in Python?

You could also use zip

import matplotlib.pyplot as plt

l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
     (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
     (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

x, y = zip(*l)

plt.plot(x, y)

How to downgrade to older version of Gradle

I did following steps to downgrade Gradle back to the original version:

  • I deleted content of '.gradle/caches' folder in user home directory (windows).
  • I deleted content of '.gradle' folder in my project root.
  • I checked that Gradle version is properly set in 'Project' option of 'Project Structure' in Android Studio.
  • I selected 'Use default gradle wrapper' option in 'Settings' in Android Studio, just search for gradle key word to find it.

Probably last step is enough as in my case the path to the new Gradle distribution was hardcoded there under 'Gradle home' option.

How to get the value of an input field using ReactJS?

There are three answers here, depending on the version of React you're (forced to) work(ing) with, and whether you want to use hooks.

First things first:

It's important to understand how React works, so you can do things properly (protip: it's is super worth running through the React tutorial exercise on the React website. It's well written, and covers all the basics in a way that actually explains how to do things). "Properly" here means that you're writing an application interface that happens to be rendered in a browser; all the interface work happens in React, not in "what you're used to if you're writing a web page" (this is why React apps are "apps", not "web pages").

React applications are rendered based off of two things:

  1. the component's properties as declared by whichever parent creates an instance of that component, which the parent can modify throughout its lifecycle, and
  2. the component's own internal state, which it can modify itself throughout its own lifecycle.

What you're expressly not doing when you use React is generating HTML elements and then using those: when you tell React to use an <input>, for instance, you are not creating an HTML input element, you are telling React to create a React input object that happens to render as an HTML input element, and whose event handling looks at, but is not controlled by, the HTML element's input events.

When using React, what you're doing is generating application UI elements that present the user with (often manipulable) data, with user interaction changing the Component's state, which may cause a rerender of part of your application interface to reflect the new state. In this model, the state is always the final authority, not "whatever UI library is used to render it", which on the web is the browser's DOM. The DOM is almost an afterthought in this programming model: it's just the particular UI framework that React happens to be using.

So in the case of an input element, the logic is:

  1. You type in the input element,
  2. nothing happens to your input element yet, the event got intercepted by React and killed off immediately,
  3. React forwards the event to the function you've set up for event handling,
  4. that function may schedule a state update,
  5. if it does, React runs that state update (asynchronously!) and will trigger a render call after the update, but only if the state update changed the state.
  6. only after this render has taken place will the UI show that you "typed a letter".

All of that happens in a matter of milliseconds, if not less, so it looks like you typed into the input element in the same way you're used to from "just using an input element on a page", but that's absolutely not what happened.

So, with that said, on to how to get values from elements in React:

React 15 and below, with ES5

To do things properly, your component has a state value, which is shown via an input field, and we can update it by making that UI element send change events back into the component:

var Component = React.createClass({
  getInitialState: function() {
    return {
      inputValue: ''
    };
  },

  render: function() {
    return (
      //...
      <input value={this.state.inputValue} onChange={this.updateInputValue}/>
      //...
    );
  },

  updateInputValue: function(evt) {
    this.setState({
      inputValue: evt.target.value
    });
  }
});

So we tell React to use the updateInputValue function to handle the user interaction, use setState to schedule the state update, and the fact that render taps into this.state.inputValue means that when it rerenders after updating the state, the user will see the update text based on what they typed.

addendum based on comments

Given that UI inputs represent state values (consider what happens if a user closes their tab midway, and the tab is restored. Should all those values they filled in be restored? If so, that's state). That might make you feel like a large form needs tens or even a hundred input forms, but React is about modeling your UI in a maintainable way: you do not have 100 independent input fields, you have groups of related inputs, so you capture each group in a component and then build up your "master" form as a collection of groups.

MyForm:
  render:
    <PersonalData/>
    <AppPreferences/>
    <ThirdParty/>
     ...

This is also much easier to maintain than a giant single form component. Split up groups into Components with state maintenance, where each component is only responsible for tracking a few input fields at a time.

You may also feel like it's "a hassle" to write out all that code, but that's a false saving: developers-who-are-not-you, including future you, actually benefit greatly from seeing all those inputs hooked up explicitly, because it makes code paths much easier to trace. However, you can always optimize. For instance, you can write a state linker

MyComponent = React.createClass({
  getInitialState() {
    return {
      firstName: this.props.firstName || "",
      lastName: this.props.lastName || "" 
      ...: ...
      ...
    }
  },
  componentWillMount() {
    Object.keys(this.state).forEach(n => {
      let fn = n + 'Changed';
      this[fn] = evt => {
        let update = {};
        update[n] = evt.target.value;
        this.setState(update);
      });
    });
  },
  render: function() {
    return Object.keys(this.state).map(n => {
      <input
        key={n} 
        type="text"
        value={this.state[n]}
        onChange={this[n + 'Changed']}/>
    });
  }
});

Of course, there are improved versions of this, so hit up https://npmjs.com and search for a React state linking solution that you like best. Open Source is mostly about finding what others have already done, and using that instead of writing everything yourself from scratch.

React 16 (and 15.5 transitional) and 'modern' JS

As of React 16 (and soft-starting with 15.5) the createClass call is no longer supported, and class syntax needs to be used. This changes two things: the obvious class syntax, but also the thiscontext binding that createClass can do "for free", so to ensure things still work make sure you're using "fat arrow" notation for this context preserving anonymous functions in onWhatever handlers, such as the onChange we use in the code here:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: ''
    };
  }

  render() {
    return (
      //...
      <input value={this.state.inputValue} onChange={evt => this.updateInputValue(evt)}/>
      //...
    );
  },

  updateInputValue(evt) {
    this.setState({
      inputValue: evt.target.value
    });
  }
});

You may also have seen people use bind in their constructor for all their event handling functions, like this:

constructor(props) {
  super(props);
  this.handler = this.handler.bind(this);
  ...
}

render() {
  return (
    ...
    <element onclick={this.handler}/>
    ...
  );
}

Don't do that.

Almost any time you're using bind, the proverbial "you're doing it wrong" applies. Your class already defines the object prototype, and so already defines the instance context. Don't put bind of top of that; use normal event forwarding instead of duplicating all your function calls in the constructor, because that duplication increases your bug surface, and makes it much harder to trace errors because the problem might be in your constructor instead of where you call your code. As well as placing a burden of maintenance on others that you (have or choose) to work with.

Yes, I know the react docs say it's fine. It's not, don't do it.

React 16.8, using function components with hooks

As of React 16.8 the function component (i.e. literally just a function that takes some props as argument can be used as if it's an instance of a component class, without ever writing a class) can also be given state, through the use of hooks.

If you don't need full class code, and a single instance function will do, then you can now use the useState hook to get yourself a single state variable, and its update function, which works roughly the same as the above examples, except without the setState function call:

import { useState } from 'react';

function myFunctionalComponentFunction() {
  const [input, setInput] = useState(''); // '' is the initial state value
  return (
    <div>
    <label>Please specify:</label>
    <input value={input} onInput={e => setInput(e.target.value)}/>
    </div>
  );
}

Previously the unofficial distinction between classes and function components was "function components don't have state", so we can't hide behind that one anymore: the difference between function components and classes components can be found spread over several pages in the very well-written react documentation (no shortcut one liner explanation to conveniently misinterpret for you!) which you should read so that you know what you're doing and can thus know whether you picked the best (whatever that means for you) solution to program yourself out of a problem you're having.

Enable/Disable Anchor Tags using AngularJS

Modifying @Nitin's answer to work with dynamic disabling:

angular.module('myApp').directive('a', function() {
  return {
    restrict: 'E',
    link: function(scope, elem, attrs) {
      elem.on('click', function(e) {
        if (attrs.disabled) {
          e.preventDefault(); // prevent link click
        }
      });
    }
  };
});

This checks the existence of disabled attribute and its value upon every click.

How do I convert a column of text URLs into active hyperlinks in Excel?

For anyone landing here with Excel 2016, you can simply highlight the column, then click the Hyperlink tab located on the Home ribbon in the Styles box.

enter image description here

Edit: Unfortunately, this only updates the cell style, not the function.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

If it is maven project do Maven Update will solve the problem - Right Click on Project --> Maven --> Update Project and start your project normally.

Using NSLog for debugging

The proper way of using NSLog, as the warning tries to explain, is the use of a formatter, instead of passing in a literal:

Instead of:

NSString *digit = [[sender titlelabel] text];
NSLog(digit);

Use:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@",digit);

It will still work doing that first way, but doing it this way will get rid of the warning.

Insert string in beginning of another string

import java.lang.StringBuilder;

public class Program {
    public static void main(String[] args) {

    // Create a new StringBuilder.
    StringBuilder builder = new StringBuilder();

    // Loop and append values.
    for (int i = 0; i < 5; i++) {
        builder.append("abc ");
    }
    // Convert to string.
    String result = builder.toString();

    // Print result.
    System.out.println(result);
    }
}

Get last 3 characters of string

The easiest way would be using Substring

string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);

Using the overload with one int as I put would get the substring of a string, starting from the index int. In your case being str.Length - 3, since you want to get the last three chars.

Clear History and Reload Page on Login/Logout Using Ionic Framework

Welcome to the framework! Actually the routing in Ionic is powered by ui-router. You should probably check out this previous SO question to find a couple of different ways to accomplish this.

If you just want to reload the state you can use:

$state.go($state.current, {}, {reload: true});

If you actually want to reload the page (as in, you want to re-bootstrap everything) then you can use:

$window.location.reload(true)

Good luck!

Right Align button in horizontal LinearLayout

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"             
    android:orientation="horizontal" 
    android:layout_marginTop="35dp">

    <TextView
        android:id="@+id/lblExpenseCancel"
        android:layout_width="0dp"
        android:layout_weight="0.5"
        android:layout_height="wrap_content"
        android:text="@string/cancel" 
        android:textColor="#404040"         
        android:layout_marginLeft="10dp" 
        android:textSize="20sp" 
        android:layout_marginTop="9dp"/>              

    <Button
        android:id="@+id/btnAddExpense"
        android:layout_width="0dp"
        android:layout_weight="0.5"
        android:layout_height="wrap_content"
        android:background="@drawable/stitch_button"
        android:layout_marginLeft="10dp"                    
        android:text="@string/add" 
        android:layout_gravity="right" 
        android:layout_marginRight="15dp"/>

</LinearLayout>

This will solve your problem

What is the use of System.in.read()?

May be this example will help you.

import java.io.IOException;

public class MainClass {

    public static void main(String[] args) {
        int inChar;
        System.out.println("Enter a Character:");
        try {
            inChar = System.in.read();
            System.out.print("You entered ");
            System.out.println(inChar);
        }
        catch (IOException e){
            System.out.println("Error reading from user");
        }
    }
}

How do you comment an MS-access Query?

It is not possible to add comments to 'normal' Access queries, that is, a QueryDef in an mdb, which is why a number of people recommend storing the sql for queries in a table.

Convert HTML5 into standalone Android App

Create an Android app using Eclipse.

Create a layout that has a <WebView> control.

Move your HTML code to /assets folder.

Load webview with your file:///android_asset/ file.

And you have an android app!

Return content with IHttpActionResult for non-OK response

this answer is based on Shamil Yakupov answer, with real object instead of string.

using System.Dynamic;

dynamic response = new ExpandoObject();
response.message = "Email address already exist";

return Content<object>(HttpStatusCode.BadRequest, response);

Select Row number in postgres

SELECT tab.*,
    row_number() OVER () as rnum
  FROM tab;

Here's the relevant section in the docs.

P.S. This, in fact, fully matches the answer in the referenced question.

Preferred way to create a Scala list

Using List.tabulate, like this,

List.tabulate(3)( x => 2*x )
res: List(0, 2, 4)

List.tabulate(3)( _ => Math.random )
res: List(0.935455779102479, 0.6004888906328091, 0.3425278797788426)

List.tabulate(3)( _ => (Math.random*10).toInt )
res: List(8, 0, 7)

How to sort a List of objects by their date (java collections, List<Object>)

You're using Comparators incorrectly.

 Collections.sort(movieItems, new Comparator<Movie>(){
           public int compare (Movie m1, Movie m2){
               return m1.getDate().compareTo(m2.getDate());
           }
       });

Python argparse command line flags without arguments

Your script is right. But by default is of None type. So it considers true of any other value other than None is assigned to args.argument_name variable.

I would suggest you to add a action="store_true". This would make the True/False type of flag. If used its True else False.

import argparse
parser = argparse.ArgumentParser('parser-name')
parser.add_argument("-f","--flag",action="store_true",help="just a flag argument")

usage

$ python3 script.py -f

After parsing when checked with args.f it returns true,

args = parser.parse_args()
print(args.f)
>>>true

How to properly apply a lambda function into a pandas data frame column

You need to add else in your lambda function. Because you are telling what to do in case your condition(here x < 90) is met, but you are not telling what to do in case the condition is not met.

sample['PR'] = sample['PR'].apply(lambda x: 'NaN' if x < 90 else x) 

OwinStartup not firing

I think what some people were trying to get to above is that if you want to programatically make your OWIN server "come to life", you'd be calling something like this:

using Microsoft.Owin.Hosting;

    IDisposable _server = WebApp.Start<StartupMethod>("http://+:5000"); 
              // Start Accepting HTTP via all interfaces on port 5000

Once you make this call, you will see the call to StartupMethod() fire in the debugger

How to Apply Gradient to background view of iOS Swift App

I wanted to add a gradient to a view, and then anchor it using auto-layout.

    class GradientView: UIView {

    private let gradient: CAGradientLayer = {
        let layer = CAGradientLayer()
        let topColor: UIColor = UIColor(red:0.98, green:0.96, blue:0.93, alpha:0.5)
        let bottomColor: UIColor = UIColor.white
        layer.colors = [topColor.cgColor, bottomColor.cgColor]
        layer.locations = [0,1]
        return layer
    }()

    init() {
        super.init(frame: .zero)
        gradient.frame = frame
        layer.insertSublayer(gradient, at: 0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        gradient.frame = bounds

    }
}

Bash Templating: How to build configuration files from templates with Bash?

Here's a modified perl script based on a few of the other answers:

perl -pe 's/([^\\]|^)\$\{([a-zA-Z_][a-zA-Z_0-9]*)\}/$1.$ENV{$2}/eg' -i template

Features (based on my needs, but should be easy to modify):

  • Skips escaped parameter expansions (e.g. \${VAR}).
  • Supports parameter expansions of the form ${VAR}, but not $VAR.
  • Replaces ${VAR} with a blank string if there is no VAR envar.
  • Only supports a-z, A-Z, 0-9 and underscore characters in the name (excluding digits in the first position).

Can you write virtual functions / methods in Java?

All non-private instance methods are virtual by default in Java.

In C++, private methods can be virtual. This can be exploited for the non-virtual-interface (NVI) idiom. In Java, you'd need to make the NVI overridable methods protected.

From the Java Language Specification, v3:

8.4.8.1 Overriding (by Instance Methods) An instance method m1 declared in a class C overrides another instance method, m2, declared in class A iff all of the following are true:

  1. C is a subclass of A.
  2. The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
  3. Either * m2 is public, protected or declared with default access in the same package as C, or * m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2.

Modifying a subset of rows in a pandas dataframe

To replace multiples columns convert to numpy array using .values:

df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2

LoDash: Get an array of values from an array of object properties

And if you need to extract several properties from each object, then

let newArr = _.map(arr, o => _.pick(o, ['name', 'surname', 'rate']));

latex large division sign in a math formula

I found the answer I was looking for. The thing to use here is the construct of

\left \middle \right

For example, in this case, two possible solutions are:

$\left( {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right) $

Or, in case the brackets are not necessary:

$\left. {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right. $

List of enum values in java

You can simply write

new ArrayList<MyEnum>(Arrays.asList(MyEnum.values()));

MySQL joins and COUNT(*) from another table

SELECT DISTINCT groups.id, 
       (SELECT COUNT(*) FROM group_members
        WHERE member_id = groups.id) AS memberCount
FROM groups

Correct file permissions for WordPress

When you setup WP you (the webserver) may need write access to the files. So the access rights may need to be loose.

chown www-data:www-data  -R * # Let Apache be owner
find . -type d -exec chmod 755 {} \;  # Change directory permissions rwxr-xr-x
find . -type f -exec chmod 644 {} \;  # Change file permissions rw-r--r--

After the setup you should tighten the access rights, according to Hardening WordPress all files except for wp-content should be writable by your user account only. wp-content must be writable by www-data too.

chown <username>:<username>  -R * # Let your useraccount be owner
chown www-data:www-data wp-content # Let apache be owner of wp-content

Maybe you want to change the contents in wp-content later on. In this case you could

  • temporarily change to the user to www-data with su,
  • give wp-content group write access 775 and join the group www-data or
  • give your user the access rights to the folder using ACLs.

Whatever you do, make sure the files have rw permissions for www-data.

How do I use cascade delete with SQL Server?

You will need to,

  • Drop the existing foreign key constraint,
  • Add a new one with the ON DELETE CASCADE setting enabled.

Something like:

ALTER TABLE dbo.T2
   DROP CONSTRAINT FK_T1_T2   -- or whatever it's called

ALTER TABLE dbo.T2
   ADD CONSTRAINT FK_T1_T2_Cascade
   FOREIGN KEY (EmployeeID) REFERENCES dbo.T1(EmployeeID) ON DELETE CASCADE

How do I redirect to the previous action in ASP.NET MVC?

try:

public ActionResult MyNextAction()
{
    return Redirect(Request.UrlReferrer.ToString());
}

alternatively, touching on what darin said, try this:

public ActionResult MyFirstAction()
{
    return RedirectToAction("MyNextAction",
        new { r = Request.Url.ToString() });
}

then:

public ActionResult MyNextAction()
{
    return Redirect(Request.QueryString["r"]);
}

Print newline in PHP in single quotes

echo 'hollow world' . PHP_EOL;

Use the constant PHP_EOL then it is OS independent too.

MySQL timezone change?

If SET time_zone or SET GLOBAL time_zone does not work, you can change as below:

  • Change timezone system, example: ubuntu... $ sudo dpkg-reconfigure tzdata

  • Restart the server or you can restart apache2 and mysql (/etc/init.d/mysql restart)

How do I capitalize first letter of first name and last name in C#?

The suggestions to use ToTitleCase won't work for strings that are all upper case. So you are gonna have to call ToUpper on the first char and ToLower on the remaining characters.

Read properties file outside JAR file

There's always a problem accessing files on your file directory from a jar file. Providing the classpath in a jar file is very limited. Instead try using a bat file or a sh file to start your program. In that way you can specify your classpath anyway you like, referencing any folder anywhere on the system.

Also check my answer on this question:

making .exe file for java project containing sqlite

The view didn't return an HttpResponse object. It returned None instead

if qs.count()==1:
        print('cart id exists')
        if ....

else:    
        return render(request,"carts/home.html",{})

Such type of code will also return you the same error this is because of the intents as the return statement should be for else not for if statement.

above code can be changed to

if qs.count()==1:
        print('cart id exists')
        if ....

else:   

return render(request,"carts/home.html",{})

This may solve such issues

What is a user agent stylesheet?

Define the values that you don't want to be used from Chrome's user agent style in your own CSS content.

Python Timezone conversion

Time conversion

To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():

so, below code is to convert the local time to other time zone.

  • datetime.datetime.today() - return current the local time
  • datetime.astimezone() - convert the time zone, but we have to pass the time zone.
  • pytz.timezone('Asia/Kolkata') -passing the time zone to pytz module
  • Strftime - Convert Datetime to string
# Time conversion from local time
import datetime
import pytz
dt_today = datetime.datetime.today()   # Local time
dt_India = dt_today.astimezone(pytz.timezone('Asia/Kolkata')) 
dt_London = dt_today.astimezone(pytz.timezone('Europe/London'))
India = (dt_India.strftime('%m/%d/%Y %H:%M'))
London = (dt_London.strftime('%m/%d/%Y %H:%M'))
print("Indian standard time: "+India+" IST")
print("British Summer Time: "+London+" BST")

list all the time zone

import pytz
for tz in pytz.all_timezones:
    print(tz)

How are VST Plugins made?

If you know a .NET language (C#/VB.NET etc) then checkout VST.NET. This framework allows you to create (unmanaged) VST 2.4 plugins in .NET. It comes with a framework that structures and simplifies the creation of a VST Plugin with support for Parameters, Programs and Persistence.

There are several samples that demonstrate the typical plugin scenarios. There's also documentation that explains how to get started and some of the concepts behind VST.NET.

Hope it helps. Marc Jacobi