Programs & Examples On #Braille

Anything related to the Braille system, a tactile writing system for blind or visually-impaired people where letters are encoded on a physical surface as combinations of small protruding dots, allowing the reader to "read" them using his/her fingers.

Using Chrome's Element Inspector in Print Preview Mode?

As of Chrome 48+, you can access the print preview via the following steps:

  1. Open dev tools – Ctrl/Cmd + Shift + I or right click on the page and choose 'Inspect'.

  2. Hit Esc to open the additional drawer.

  3. If 'Rendering' isn't already being show, click the 3 dot kebab and choose 'rendering'.

  4. Check the 'Emulate print media' checkbox.

From there Chrome will show you a print version of your page and you can inspect element and troubleshoot like you would the browser version.

Image of Chrome 49+ Print Preview option in Dev Tools

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

Difference between .dll and .exe?

EXE:

  1. It's a executable file
  2. When loading an executable, no export is called, but only the module entry point.
  3. When a system launches new executable, a new process is created
  4. The entry thread is called in context of main thread of that process.

DLL:

  1. It's a Dynamic Link Library
  2. There are multiple exported symbols.
  3. The system loads a DLL into the context of an existing process.

For More Details: http://www.c-sharpcorner.com/Interviews/Answer/Answers.aspxQuestionId=1431&MajorCategoryId=1&MinorCategoryId=1 http://wiki.answers.com/Q/What_is_the_difference_between_an_EXE_and_a_DLL

Reference: http://www.dotnetspider.com/forum/34260-What-difference-between-dll-exe.aspx

PyCharm import external library

Answer for PyCharm 2016.1 on OSX: (This is an update to the answer by @GeorgeWilliams993's answer above, but I don't have the rep yet to make comments.)

Go to Pycharm menu --> Preferences --> Project: (projectname) --> Project Interpreter

At the top is a popup for "Project Interpreter," and to the right of it is a button with ellipses (...) - click on this button for a different popup and choose "More" (or, as it turns out, click on the main popup and choose "Show All").

This shows a list of interpreters, with one selected. At the bottom of the screen are a set of tools... pick the rightmost one:

Show path for the selected interpreter button

Now you should see all the paths pycharm is searching to find imports, and you can use the "+" button at the bottom to add a new path.

I think the most significant difference from @GeorgeWilliams993's answer is that the gear button has been replaced by a set of ellipses. That threw me off.

how to open Jupyter notebook in chrome on windows

For windows set the default browser to open html files to Chrome. Configuration > Default Apps > Default Apps by File Type. Worked for me.

Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table

This cannot be done for the table; besides, you even cannot change this default value at all.

The answer is a server variable datetime_format, it is unused.

Handling optional parameters in javascript

Can you override the function? Will this not work:

function doSomething(id){}
function doSomething(id,parameters){}
function doSomething(id,parameters,callback){}

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

If earlier working project crashing suddenly with mentioned error you can try following solution.

  • Delete the bin folder of respective web/service project.
  • Build

This worked for me.

Set content of iframe

You need -

var $frame = $('myiframe');
    setTimeout( function() {
            var doc = $frame[0].contentWindow.document;
            var $body = $('body',doc);
            $body.html('<div>Test_Div</div>');
    }, 1 );

Code taken from - putting html inside an iframe (using javascript)

How to build a JSON array from mysql database

The PDO solution, just for a better implementation then mysql_*:

$array = $pdo->query("SELECT id, title, '$year-month-10' as start,url 
  FROM table")->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);

Nice feature is also that it will leave integers as integers as opposed to strings.

How do I run Redis on Windows?

Download redis from Download Redis for windows

  • Then install it
  • open cmd with admin rights
  • run command net start redis

Thats it.

datetime to string with series in python pandas

There is no str accessor for datetimes and you can't do dates.astype(str) either, you can call apply and use datetime.strftime:

In [73]:

dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0    2001-01-01
1    2001-03-31
dtype: object

You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.

Update

As of version 0.17.0 you can do this using dt.strftime

dates.dt.strftime('%Y-%m-%d')

will now work

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

You could try to reinstall the ca-certificates package, or explicitly allow the certificate in question as described here.

Put quotes around a variable string in JavaScript

var text = "http://example.com";

text = "'"+text+"'";

Would attach the single quotes (') to the front and the back of the string.

How do you dismiss the keyboard when editing a UITextField

Here is a quite clean way to end edition with the Return Key or a touch in the background.

In Interface builder, embed your fields in a view of class UIFormView

What does this class :

  • Automatically attach itself as fields delegate ( Either awaked from nib, or added manually )
  • Keep a reference on the current edited field
  • Dismiss the keyboard on return or touch in the background

Here is the code :

Interface

#import <UIKit/UIKit.h>

@interface UIFormView : UIView<UITextFieldDelegate>

-(BOOL)textFieldValueIsValid:(UITextField*)textField;
-(void)endEdit;

@end

Implementation

#import "UIFormView.h"

@implementation UIFormView
{
    UITextField* currentEditingTextField;
}

// Automatically register fields

-(void)addSubview:(UIView *)view
{
    [super addSubview:view];
    if ([view isKindOfClass:[UITextField class]]) {
        if ( ![(UITextField*)view delegate] ) [(UITextField*)view setDelegate:self];
    }
}

// UITextField Protocol

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    currentEditingTextField = textField;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    currentEditingTextField = NULL;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self endEdit];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([self textFieldValueIsValid:textField]) {
        [self endEdit];
        return YES;
    } else {
        return NO;
    }
}

// Own functions

-(void)endEdit
{
    if (currentEditingTextField) {
        [currentEditingTextField endEditing:YES];
        currentEditingTextField = NULL;
    }
}


// Override this in your subclass to handle eventual values that may prevent validation.

-(BOOL)textFieldValueIsValid:(UITextField*)textField
{
    return YES;
}

@end
  • By subclassing the form and overriding the textFieldValueIsValid: method, you can avoid end of edition if the value is not correct for the given field.

  • If a field has a delegate set in Interface Builder, then the form does not change it. I don't see many reasons to set a different delegate to a particular field, but why not…

There is many ways to improve this form view class - Attach a delegate, do some layout, handle when the keyboards covers a field ( using the currentEditingTextField frame ), automatically start edition for the next field, ...

I personally keep it in my framework, and always subclass it to add features, it is quite often useful "as-is".

I hope it will helps. Cheers all

How can I check if a user is logged-in in php?

See this script for registering. It is simple and very easy to understand.

<?php
    define('DB_HOST', 'Your Host[Could be localhost or also a website]');
    define('DB_NAME', 'database name');
    define('DB_USERNAME', 'Username[In many cases root, but some sites offer a MySQL page where the username might be different]');
    define('DB_PASSWORD', 'whatever you keep[if username is root then 99% of the password is blank]');

    $link = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);

    if (!$link) {
        die('Could not connect line 9');
    }

    $DB_SELECT = mysql_select_db(DB_NAME, $link);

    if (!$DB_SELECT) {
        die('Could not connect line 15');
    }

    $valueone = $_POST['name'];
    $valuetwo = $_POST['last_name'];
    $valuethree = $_POST['email'];
    $valuefour = $_POST['password'];
    $valuefive = $_POST['age'];

    $sqlone = "INSERT INTO user (name, last_name, email, password, age) VALUES ('$valueone','$valuetwo','$valuethree','$valuefour','$valuefive')";

    if (!mysql_query($sqlone)) {
        die('Could not connect name line 33');
    }

    mysql_close();
?>

Make sure you make all the database stuff using phpMyAdmin. It's a very easy tool to work with. You can find it here: phpMyAdmin

Regex to match 2 digits, optional decimal, two digits

A previous answer is mostly correct, but it will also match the empty string. The following would solve this.

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

How to start mongodb shell?

Just right click on your terminal icon, and select open a new window. Now you'll have two terminal windows open. In the new window, type, mongo and hit enter. Boom, that'll work like it's supposed to.

jQuery has deprecated synchronous XMLHTTPRequest

If we load script in partial view then this issue coming

  1. I removed script in partial view and moved to main view.

This solution working fine for me

Difference between java HH:mm and hh:mm on SimpleDateFormat

kk: (01-24) will look like 01, 02..24.

HH:(00-23) will look like 00, 01..23.

hh:(01-12 in AM/PM) will look like 01, 02..12.

so the last printout (working2) is a bit weird. It should say 12:00:00 (edit: if you were setting the working2 timezone and format, which (as kdagli pointed out) you are not)

Use jQuery to hide a DIV when the user clicks outside of it

I think it can be a lot easier. I did it like this:

$(':not(.form_wrapper)').click(function() {
    $('.form_wrapper').hide();
});

Creating a JSON Array in node js

You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.

Use JSON.stringify(object) to turn it into (a string of) JSON text.

MySQL dump by query

You could use --where option on mysqldump to produce an output that you are waiting for:

mysqldump -u root -p test t1 --where="1=1 limit 100" > arquivo.sql

At most 100 rows from test.t1 will be dumped from database table.

Cheers, WB

Why use @PostConstruct?

If your class performs all of its initialization in the constructor, then @PostConstruct is indeed redundant.

However, if your class has its dependencies injected using setter methods, then the class's constructor cannot fully initialize the object, and sometimes some initialization needs to be performed after all the setter methods have been called, hence the use case of @PostConstruct.

Javascript : calling function from another file

Why don't you take a look to this answer

Including javascript files inside javascript files

In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.

Calculate the mean by group

Adding alternative base R approach, which remains fast under various cases.

rowsummean <- function(df) {
  rowsum(df$speed, df$dive) / tabulate(df$dive)
}

Borrowing the benchmarks from @Ari:

10 rows, 2 groups

res1

10 million rows, 10 groups

res2

10 million rows, 1000 groups

res3

How to initialize array to 0 in C?

Global variables and static variables are automatically initialized to zero. If you have simply

char ZEROARRAY[1024];

at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:

char ZEROARRAY[1024] = {0};

The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:

memset(ZEROARRAY, 0, 1024);

That would be useful if you had changed it and wanted to reset it back to all zeros.

How do I ZIP a file in C#, using no 3rd-party APIs?

Based off Simon McKenzie's answer to this question, I'd suggest using a pair of methods like this:

    public static void ZipFolder(string sourceFolder, string zipFile)
    {
        if (!System.IO.Directory.Exists(sourceFolder))
            throw new ArgumentException("sourceDirectory");

        byte[] zipHeader = new byte[] { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

        using (System.IO.FileStream fs = System.IO.File.Create(zipFile))
        {
            fs.Write(zipHeader, 0, zipHeader.Length);
        }

        dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
        dynamic source = shellApplication.NameSpace(sourceFolder);
        dynamic destination = shellApplication.NameSpace(zipFile);

        destination.CopyHere(source.Items(), 20);
    }

    public static void UnzipFile(string zipFile, string targetFolder)
    {
        if (!System.IO.Directory.Exists(targetFolder))
            System.IO.Directory.CreateDirectory(targetFolder);

        dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
        dynamic compressedFolderContents = shellApplication.NameSpace(zipFile).Items;
        dynamic destinationFolder = shellApplication.NameSpace(targetFolder);

        destinationFolder.CopyHere(compressedFolderContents);
    }
}

At least one JAR was scanned for TLDs yet contained no TLDs

For anyone trying to get this working using the Sysdeo Eclipse Tomcat plugin, try the following steps (I used Sysdeo Tomcat Plugin 3.3.0, Eclipse Kepler, and Tomcat 7.0.53 to construct these steps):

  1. Window --> Preferences --> Expand the Tomcat node in the tree --> JVM Settings
  2. Under "Append to JVM Parameters", click the "Add" button.
  3. In the "New Tomcat JVM parameter" popup, enter -Djava.util.logging.config.file="{TOMCAT_HOME}\conf\logging.properties", where {TOMCAT_HOME} is the path to your Tomcat directory (example: C:\Tomcat\apache-tomcat-7.0.53\conf\logging.properties). Click OK.
  4. Under "Append to JVM Parameters", click the "Add" button again.
  5. In the "New Tomcat JVM parameter" popup, enter -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager. Click OK.
  6. Click OK in the Preferences window.
  7. Make the adjustments to the {TOMCAT_HOME}\conf\logging.properties file as specified in the question above.
  8. The next time you start Tomcat in Eclipse, you should see the scanned .jars listed in the Eclipse Console instead of the "Enable debug logging for this logger" message. The information should also be logged in {TOMCAT_HOME}\logs\catalina.yyyy-mm-dd.log.

Convert floating point number to a certain precision, and then copy to string

With Python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.

# Option one
older_method_string = "%.9f" % numvar

# Option two
newer_method_string = "{:.9f}".format(numvar)

But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.

For more information on option two, I suggest this link on string formatting from the Python documentation.

And for more information on option one, this link will suffice and has info on the various flags.

Python 3.6 (officially released in December of 2016), added the f string literal, see more information here, which extends the str.format method (use of curly braces such that f"{numvar:.9f}" solves the original problem), that is,

# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"

solves the problem. Check out @Or-Duan's answer for more info, but this method is fast.

New line in Sql Query

use CHAR(10) for New Line in SQL
char(9) for Tab
and Char(13) for Carriage Return

SQL SERVER: Check if variable is null and then assign statement for Where Clause

Isnull() syntax is built in for this kind of thing.

declare @Int int = null;

declare @Values table ( id int, def varchar(8) )

insert into @Values values (8, 'I am 8');

-- fails
select *
from @Values
where id = @Int

-- works fine
select *
from @Values
where id = isnull(@Int, 8);

For your example keep in mind you can change scope to be yet another where predicate off of a different variable for complex boolean logic. Only caveat is you need to cast it differently if you need to examine for a different data type. So if I add another row but wish to specify int of 8 AND also the reference of text similar to 'repeat' I can do that with a reference again back to the 'isnull' of the first variable yet return an entirely different result data type for a different reference to a different field.

declare @Int int = null;

declare @Values table ( id int, def varchar(16) )

insert into @Values values (8, 'I am 8'), (8, 'I am 8 repeat');

select *
from @Values
where id = isnull(@Int, 8)
and def like isnull(cast(@Int as varchar), '%repeat%')

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

Updated Answer

Now that we can use dataFor() to check if the binding has been applied, I would prefer check the data binding, rather than cleanNode() and applyBindings().

Like this:

var koNode = document.getElementById('formEdit');
var hasDataBinding = !!ko.dataFor(koNode);
console.log('has data binding', hasDataBinding);
if (!hasDataBinding) { ko.applyBindings(vm, koNode);}

Original Answer.

A lot of answers already!

First, let's say it is fairly common that we need to do the binding multiple times in a page. Say, I have a form inside the Bootstrap modal, which will be loaded again and again. Many of the form input have two-way binding.

I usually take the easy route: clearing the binding every time before the the binding.

var koNode = document.getElementById('formEdit');
ko.cleanNode(koNode);
ko.applyBindings(vm, koNode);

Just make sure here koNode is required, for, ko.cleanNode() requires a node element, even though we can omit it in ko.applyBinding(vm).

How to get keyboard input in pygame?

You should use clock.tick(10) as stated in the docs.

How to install gdb (debugger) in Mac OSX El Capitan?

On my Mac OS X El Capitan, I use homebrew to install gdb:

brew install gdb

Then I follow the instruction here: https://sourceware.org/gdb/wiki/BuildingOnDarwin, in the section 2.1. Method for Mac OS X 10.5 (Leopard) and later.

MVC 4 Razor File Upload

The Upload method's HttpPostedFileBase parameter must have the same name as the the file input.

So just change the input to this:

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

Also, you could find the files in Request.Files:

[HttpPost]
public ActionResult Upload()
{
     if (Request.Files.Count > 0)
     {
         var file = Request.Files[0];

         if (file != null && file.ContentLength > 0)
         {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
            file.SaveAs(path);
         }
     }

     return RedirectToAction("UploadDocument");
 }

Get selected value from combo box in C# WPF

I have figured it out a bit of a strange way of doing it compared to the old WF forms:

ComboBoxItem typeItem = (ComboBoxItem)cboType.SelectedItem;
string value = typeItem.Content.ToString();

Reading DataSet

DataSet resembles database. DataTable resembles database table, and DataRow resembles a record in a table. If you want to add filtering or sorting options, you then do so with a DataView object, and convert it back to a separate DataTable object.

If you're using database to store your data, then you first load a database table to a DataSet object in memory. You can load multiple database tables to one DataSet, and select specific table to read from the DataSet through DataTable object. Subsequently, you read a specific row of data from your DataTable through DataRow. Following codes demonstrate the steps:

SqlCeDataAdapter da = new SqlCeDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();

da.SelectCommand = new SqlCommand(@"SELECT * FROM FooTable", connString);
da.Fill(ds, "FooTable");
dt = ds.Tables["FooTable"];

foreach (DataRow dr in dt.Rows)
{
    MessageBox.Show(dr["Column1"].ToString());
}

To read a specific cell in a row:

int rowNum // row number
string columnName = "DepartureTime";  // database table column name
dt.Rows[rowNum][columnName].ToString();

Should each and every table have a primary key?

Will you ever need to join this table to other tables? Do you need a way to uniquely identify a record? If the answer is yes, you need a primary key. Assume your data is something like a customer table that has the names of the people who are customers. There may be no natural key because you need the addresses, emails, phone numbers, etc. to determine if this Sally Smith is different from that Sally Smith and you will be storing that information in related tables as the person can have mulitple phones, addesses, emails, etc. Suppose Sally Smith marries John Jones and becomes Sally Jones. If you don't have an artifical key onthe table, when you update the name, you just changed 7 Sally Smiths to Sally Jones even though only one of them got married and changed her name. And of course in this case withouth an artificial key how do you know which Sally Smith lives in Chicago and which one lives in LA?

You say you have no natural key, therefore you don't have any combinations of field to make unique either, this makes the artficial key critical.

I have found anytime I don't have a natural key, an artifical key is an absolute must for maintaining data integrity. If you do have a natural key, you can use that as the key field instead. But personally unless the natural key is one field, I still prefer an artifical key and unique index on the natural key. You will regret it later if you don't put one in.

How do I vertically align text in a paragraph?

Below styles will vertically center it for you.

p.event_desc {
 font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
 line-height: 14px;
 height: 35px;
 display: table-cell;
 vertical-align: middle;
 margin: 0px;
}

How do you push a tag to a remote repository using Git?

I am using git push <remote-name> tag <tag-name> to ensure that I am pushing a tag. I use it like: git push origin tag v1.0.1. This pattern is based upon the documentation (man git-push):

OPTIONS
   ...
   <refspec>...
       ...
       tag <tag> means the same as refs/tags/<tag>:refs/tags/<tag>.

What is the function __construct used for?

class Person{
 private $fname;
 private $lname;

 public function __construct($fname,$lname){
  $this->fname = $fname;
  $this->lname = $lname;
 }
}
$objPerson1 = new Person('john','smith');

How to select the last record from MySQL table using SQL syntax

SELECT   *
FROM     table
ORDER BY id DESC
LIMIT    0, 1

How to send custom headers with requests in Swagger UI?

Here's a simpler answer for the ASP.NET Core Web Api/Swashbuckle combo, that doesn't require you to register any custom filters. Third time's a charm you know :).

Adding the code below to your Swagger config will cause the Authorize button to appear, allowing you to enter a bearer token to be sent for all requests. Don't forget to enter this token as Bearer <your token here> when asked.

Note that the code below will send the token for any and all requests and operations, which may or may not be what you want.


    services.AddSwaggerGen(c =>
    {
        //...

        c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
        {
            Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
            Name = "Authorization",
            In = "header",
            Type = "apiKey"
        });

        c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
        {
            { "Bearer", new string[] { } }
        });

        //...
    }

Via this thread.

Find control by name from Windows Forms controls

Use Control.ControlCollection.Find.

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

EDIT for asker:

Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
    tbxs[0].Text = "Found!";
}

How to trigger event when a variable's value is changed?

A simple method involves using the get and set functions on the variable


    using System;
    public string Name{
    get{
     return name;
    }
    
    set{
     name= value;
     OnVarChange?.Invoke();
    }
    }
    private string name;
    
    public event System.Action OnVarChange;

Make code in LaTeX look *nice*

The listings package is quite nice and very flexible (e.g. different sizes for comments and code).

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

When I removed the following lines from my code, all worked OK!

set_include_path(get_include_path() . get_include_path() . '/phpseclib');
include_once('Net/SSH2.php');
include_once('Net/SFTP.php');

These lines were included in every file I was running. When running the files one by one, all worked OK, but when running all files together I got the memory leak issue. Somehow the "include_once" is not including things once, or I am doing something wrong...

'Static readonly' vs. 'const'

public static readonly fields are a little unusual; public static properties (with only a get) would be more common (perhaps backed by a private static readonly field).

const values are burned directly into the call-site; this is double edged:

  • it is useless if the value is fetched at runtime, perhaps from config
  • if you change the value of a const, you need to rebuild all the clients
  • but it can be faster, as it avoids a method call...
  • ...which might sometimes have been inlined by the JIT anyway

If the value will never change, then const is fine - Zero etc make reasonable consts ;p Other than that, static properties are more common.

How do I compile jrxml to get jasper?

Using Version 5.1.0:

Just click preview and it will create a YourReportName.jasper for you in the same working directory.

How do I insert datetime value into a SQLite database?

Use CURRENT_TIMESTAMP when you need it, instead OF NOW() (which is MySQL)

pip installs packages successfully, but executables not found from command line

If you're installing using --user (e.g. pip3.6 install --user tmuxp), it is possible to get the platform-specific user install directory from Python itself using the site module. For example, on macOS:

$ python2.7 -m site --user-base
/Users/alexp/Library/Python/2.7

By appending /bin to this, we now have the path where package executables will be installed. We can dynamically populate the PATH in your shell's rc file based on the output; I'm using bash, but with any luck this is portable:

# Add Python bin directories to path
python3.6 -m site &> /dev/null && PATH="$PATH:`python3.6 -m site --user-base`/bin"
python2.7 -m site &> /dev/null && PATH="$PATH:`python2.7 -m site --user-base`/bin"

I use the precise Python versions to reduce the chance of the executables just "disappearing" when Python upgrades a minor version, e.g. from 3.5 to 3.6. They'll disappear because, as can be seen above, the user installation path may include the Python version. So while python3 could point to 3.5 or 3.6, python3.6 will always point to 3.6. This needs to be kept in mind when installing further packages, e.g. use pip3.6 over pip3.

If you don't mind the idea of packages disappearing, you can use python2 and python3 instead:

# Add Python bin directories to path
# Note: When Python is upgraded, packages may need to be re-installed
#       or Python versions managed.
python3 -m site &> /dev/null && PATH="$PATH:`python3 -m site --user-base`/bin"
python2 -m site &> /dev/null && PATH="$PATH:`python2 -m site --user-base`/bin"

How do I convert a String to an InputStream in Java?

I find that using Apache Commons IO makes my life much easier.

String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");

You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.

Find Number of CPUs and Cores per CPU using Command Prompt

If you want to find how many processors (or CPUs) a machine has the same way %NUMBER_OF_PROCESSORS% shows you the number of cores, save the following script in a batch file, for example, GetNumberOfCores.cmd:

@echo off
for /f "tokens=*" %%f in ('wmic cpu get NumberOfCores /value ^| find "="') do set %%f

And then execute like this:

GetNumberOfCores.cmd

echo %NumberOfCores%

The script will set a environment variable named %NumberOfCores% and it will contain the number of processors.

How to toggle (hide / show) sidebar div using jQuery

$('#toggle').click(function() {
  $('#B').toggleClass('extended-panel');
  $('#A').toggle(/** specify a time here for an animation */);
});

and in the CSS:

.extended-panel {
  left: 0px !important;
}

What is the $$hashKey added to my JSON.stringify result

In my use case (feeding the resulting object to X2JS) the recommended approach

data = angular.toJson(source);

help to remove the $$hashKey properties, but the result could then no longer be processed by X2JS.

data = angular.copy(source);

removed the $$hashKey properties as well, but the result remained usable as a parameter for X2JS.

How to post data to specific URL using WebClient in C#

Using webapiclient with model send serialize json parameter request.

PostModel.cs

    public string Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }

WebApiClient.cs

internal class WebApiClient  : IDisposable
  {

    private bool _isDispose;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public void Dispose(bool disposing)
    {
        if (!_isDispose)
        {

            if (disposing)
            {

            }
        }

        _isDispose = true;
    }

    private void SetHeaderParameters(WebClient client)
    {
        client.Headers.Clear();
        client.Headers.Add("Content-Type", "application/json");
        client.Encoding = Encoding.UTF8;
    }

    public async Task<T> PostJsonWithModelAsync<T>(string address, string data,)
    {
        using (var client = new WebClient())
        {
            SetHeaderParameters(client);
            string result = await client.UploadStringTaskAsync(address, data); //  method:
    //The HTTP method used to send the file to the resource. If null, the default is  POST 
            return JsonConvert.DeserializeObject<T>(result);
        }
    }
}

Business caller method

    public async Task<ResultDTO> GetResultAsync(PostModel model)
    {
        try
        {
            using (var client = new WebApiClient())
            {
                var serializeModel= JsonConvert.SerializeObject(model);// using Newtonsoft.Json;
                var response = await client.PostJsonWithModelAsync<ResultDTO>("http://www.website.com/api/create", serializeModel);
                return response;
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

    }

Android - Set text to TextView

first your should create an object for text view TextView show_alter

show_alert = (TextView)findViewById(R.id.show_alert);
show_alert.setText("My Awesome Text");

How can I extract a number from a string in JavaScript?

Use this one-line code to get the first number in a string without getting errors:

var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

On Ubuntu with OpenJDK, it installed in /usr/lib/jvm/default-java/jre/lib/ext/jfxrt.jar (technically its a symlink to /usr/share/java/openjfx/jre/lib/ext/jfxrt.jar, but it is probably better to use the default-java link)

Unable to start Service Intent

For anyone else coming across this thread I had this issue and was pulling my hair out. I had the service declaration OUTSIDE of the '< application>' end tag DUH!

RIGHT:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  ...>
...
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity ...>
        ...
    </activity>    

    <service android:name=".Service"/>

    <receiver android:name=".Receiver">
        <intent-filter>
            ...
        </intent-filter>
    </receiver>        
</application>

<uses-permission android:name="..." />

WRONG but still compiles without errors:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  ...>
...
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity ...>
        ...
    </activity>

</application>

    <service android:name=".Service"/>

    <receiver android:name=".Receiver">
        <intent-filter>
            ...
        </intent-filter>
    </receiver>        

<uses-permission android:name="..." />

Reset input value in angular 2

If you want to clear the input by using the HTML ONLY, then you can do something like this:

<input type="text"
       (keyup)="0"
       #searchCollectorInput
       class="search-metrics"
       placeholder="Find">

Notice the importance of (keyup)=0 and the reference to the input of course.

Then reset it like this:

<span *ngIf="searchCollectorInput.value.length > 0"
      (click)="searchCollectorInput.value = ''"
      class="fa fa-close" ></span>

Height equal to dynamic width (CSS fluid layout)

It is possible without any Javascript :)

The HTML:

<div class='box'>
    <div class='content'>Aspect ratio of 1:1</div>
</div> 

The CSS:

.box {
    position: relative;
    width:    50%; /* desired width */
}

.box:before {
    content:     "";
    display:     block;
    padding-top: 100%; /* initial ratio of 1:1*/
}

.content {
    position: absolute;
    top:      0;
    left:     0;
    bottom:   0;
    right:    0;
}

/* Other ratios - just apply the desired class to the "box" element */
.ratio2_1:before{
    padding-top: 50%;
}
.ratio1_2:before{
    padding-top: 200%;
}
.ratio4_3:before{
    padding-top: 75%;
}
.ratio16_9:before{
    padding-top: 56.25%;
}

Pass Additional ViewData to a Strongly-Typed Partial View

RenderPartial takes another parameter that is simply a ViewDataDictionary. You're almost there, just call it like this:

Html.RenderPartial(
      "ProductImageForm", 
       image, 
       new ViewDataDictionary { { "index", index } }
); 

Note that this will override the default ViewData that all your other Views have by default. If you are adding anything to ViewData, it will not be in this new dictionary that you're passing to your partial view.

Preferred way of getting the selected item of a JComboBox

String x = JComboBox.getSelectedItem().toString();

will convert any value weather it is Integer, Double, Long, Short into text on the other hand,

String x = String.valueOf(JComboBox.getSelectedItem());

will avoid null values, and convert the selected item from object to string

Should CSS always preceed Javascript?

Were your tests performed on your personal computer, or on a web server? It is a blank page, or is it a complex online system with images, databases, etc.? Are your scripts performing a simple hover event action, or are they a core component to how your website renders and interacts with the user? There are several things to consider here, and the relevance of these recommendations almost always become rules when you venture into high-caliber web development.

The purpose of the "put stylesheets at the top and scripts at the bottom" rule is that, in general, it's the best way to achieve optimal progressive rendering, which is critical to the user experience.

All else aside: assuming your test is valid, and you really are producing results contrary to the popular rules, it'd come as no surprise, really. Every website (and everything it takes to make the whole thing appear on a user's screen) is different and the Internet is constantly evolving.

Case insensitive string compare in LINQ-to-SQL

I tried this using Lambda expression, and it worked.

List<MyList>.Any (x => (String.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)) && (x.Type == qbType) );

How can I remove an entry in global configuration with git config?

You can edit the ~/.gitconfig file in your home folder. This is where all --global settings are saved.

How to get HttpClient returning status code and response body?

You can avoid the BasicResponseHandler, but use the HttpResponse itself to get both status and response as a String.

HttpResponse response = httpClient.execute(get);

// Getting the status code.
int statusCode = response.getStatusLine().getStatusCode();

// Getting the response body.
String responseBody = EntityUtils.toString(response.getEntity());

Radio Buttons ng-checked with ng-model

I solved my problem simply using ng-init for default selection instead of ng-checked

<div ng-init="person.billing=FALSE"></div>
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="FALSE" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="TRUE" />

Convert an array into an ArrayList

List<Card> list = new ArrayList<Card>(Arrays.asList(hand));

Finding and removing non ascii characters from an Oracle Varchar2

The following also works:

select dump(a,1016), a from (
SELECT REGEXP_REPLACE (
          CONVERT (
             '3735844533120%$03  ',
             'US7ASCII',
             'WE8ISO8859P1'),
          '[^!@/\.,;:<>#$%&()_=[:alnum:][:blank:]]') a
  FROM DUAL);

SQL Error: ORA-00913: too many values

this is a bit late.. but i have seen this problem occurs when you want to insert or delete one line from/to DB but u put/pull more than one line or more than one value ,

E.g:

you want to delete one line from DB with a specific value such as id of an item but you've queried a list of ids then you will encounter the same exception message.

regards.

How to check if an integer is within a range of numbers in PHP?

You could whip up a little helper function to do this:

/**
 * Determines if $number is between $min and $max
 *
 * @param  integer  $number     The number to test
 * @param  integer  $min        The minimum value in the range
 * @param  integer  $max        The maximum value in the range
 * @param  boolean  $inclusive  Whether the range should be inclusive or not
 * @return boolean              Whether the number was in the range
 */
function in_range($number, $min, $max, $inclusive = FALSE)
{
    if (is_int($number) && is_int($min) && is_int($max))
    {
        return $inclusive
            ? ($number >= $min && $number <= $max)
            : ($number > $min && $number < $max) ;
    }

    return FALSE;
}

And you would use it like so:

var_dump(in_range(5, 0, 10));        // TRUE
var_dump(in_range(1, 0, 1));         // FALSE
var_dump(in_range(1, 0, 1, TRUE));   // TRUE
var_dump(in_range(11, 0, 10, TRUE)); // FALSE

// etc...

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

Both of the following work (as discussed here).

exec sp_rename 'ENG_TEst.[[ENG_Test_A/C_TYPE]]]' , 
                'ENG_Test_A/C_TYPE', 'COLUMN'


exec sp_rename 'ENG_TEst."[ENG_Test_A/C_TYPE]"' , 
                'ENG_Test_A/C_TYPE', 'COLUMN'

Truncating a table in a stored procedure

try the below code

execute immediate 'truncate table tablename' ;

How to write a PHP ternary operator

In addition to all the other answers, you could use switch. But it does seem a bit long.

switch ($result->vocation) {
case 1:
    echo 'Sorcerer';
    break;

case 2:
    echo 'Druid';
    break;

case 3:
    echo 'Paladin';
    break;

case 4:
    echo 'Knight';
    break;

case 5:
    echo 'Master Sorcerer';
    break;

case 6:
    echo 'Elder Druid';
    break;

case 7:
    echo 'Royal Paladin';
    break;

default:
    echo 'Elite Knight';
    break;
}

Absolute and Flexbox in React Native

This solution worked for me:

tabBarOptions: {
      showIcon: true,
      showLabel: false,
      style: {
        backgroundColor: '#000',
        borderTopLeftRadius: 40,
        borderTopRightRadius: 40,
        position: 'relative',
        zIndex: 2,
        marginTop: -48
      }
  }

Printing out all the objects in array list

Override toString() method in Student class as below:

   @Override
   public String toString() {
        return ("StudentName:"+this.getStudentName()+
                    " Student No: "+ this.getStudentNo() +
                    " Email: "+ this.getEmail() +
                    " Year : " + this.getYear());
   }

JQuery post JSON object to a server

To send json to the server, you first have to create json

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            name:"Bob",
            ...
        }),
        dataType: 'json'
    });
}

This is how you would structure the ajax request to send the json as a post var.

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        data: { json: JSON.stringify({
            name:"Bob",
            ...
        })},
        dataType: 'json'
    });
}

The json will now be in the json post var.

INSERT INTO @TABLE EXEC @query with SQL Server 2000

DECLARE @q nvarchar(4000)
SET @q = 'DECLARE @tmp TABLE (code VARCHAR(50), mount MONEY)
INSERT INTO @tmp
  (
    code,
    mount
  )
SELECT coa_code,
       amount
FROM   T_Ledger_detail

SELECT *
FROM   @tmp'

EXEC sp_executesql @q

If you want in dynamic query

How do I remove objects from an array in Java?

It depends on what you mean by "remove"? An array is a fixed size construct - you can't change the number of elements in it. So you can either a) create a new, shorter, array without the elements you don't want or b) assign the entries you don't want to something that indicates their 'empty' status; usually null if you are not working with primitives.

In the first case create a List from the array, remove the elements, and create a new array from the list. If performance is important iterate over the array assigning any elements that shouldn't be removed to a list, and then create a new array from the list. In the second case simply go through and assign null to the array entries.

NoClassDefFoundError on Maven dependency

This is due to Morphia jar not being part of your output war/jar. Eclipse or local build includes them as part of classpath, but remote builds or auto/scheduled build don't consider them part of classpath.

You can include dependent jars using plugin.

Add below snippet into your pom's plugins section

    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>

Why is setState in reactjs Async instead of Sync?

Good article here https://github.com/vasanthk/react-bits/blob/master/patterns/27.passing-function-to-setState.md

// assuming this.state.count === 0
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
// this.state.count === 1, not 3

Solution
this.setState((prevState, props) => ({
  count: prevState.count + props.increment
}));

or pass callback this.setState ({.....},callback)

https://medium.com/javascript-scene/setstate-gate-abc10a9b2d82 https://medium.freecodecamp.org/functional-setstate-is-the-future-of-react-374f30401b6b

convert htaccess to nginx

You can easily make a Php script to parse your old htaccess, I am using this one for PRestashop rules :

$content = $_POST['content'];

    $lines   = explode(PHP_EOL, $content);
    $results = '';

    foreach($lines as $line)
    {
        $items = explode(' ', $line);

        $q = str_replace("^", "^/", $items[1]);

        if (substr($q, strlen($q) - 1) !== '$') $q .= '$';

        $buffer = 'rewrite "'.$q.'" "'.$items[2].'" last;';

        $results .= $buffer.PHP_EOL;
    }

    die($results);

CSS to make table 100% of max-width

I have a very well working solution for tables of max-width: 100%. Just use word-break: break-all; for the table cells (except heading cells) to break all long text into several lines:

<!DOCTYPE html>
<html>
<head>
<style>

table {
  max-width: 100%; 
}
table td {
  word-break: break-all;
}

</style>
</head>
<body>

<table border="1">
  <tr>
    <th><strong>Input</strong></th>
    <th><strong>Output</strong></th>
  </tr>
  <tr>
    <td>some text</td>
    <td>12b6459fc6b4cabb4b1990be1a78e4dc5fa79c3a0fe9aa9f0386d673cfb762171a4aaa363b8dac4c33e0ad23e4830888</td>
  </tr>
</table>

</body>
</html>

This will render like this (when the screen width is limited):

PHP 5 disable strict standards error

WordPress

If you work in the wordpress environment, Wordpress sets the error level in file wp-includes/load.php in function wp_debug_mode(). So you have to change the level AFTER this function has been called ( in a file not checked into git so that's development only ), or either modify directly the error_reporting() call

force line break in html table cell

It's hard to answer you without the HTML, but in general you can put:

style="width: 50%;"

On either the table cell, or place a div inside the table cell, and put the style on that.

But one problem is "50% of what?" It's 50% of the parent element which may not be what you want.

Post a copy of your HTML and maybe you'll get a better answer.

Can I run Keras model on gpu?

Sure. I suppose that you have already installed TensorFlow for GPU.

You need to add the following block after importing keras. I am working on a machine which have 56 core cpu, and a gpu.

import keras
import tensorflow as tf


config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} ) 
sess = tf.Session(config=config) 
keras.backend.set_session(sess)

Of course, this usage enforces my machines maximum limits. You can decrease cpu and gpu consumption values.

Convert list to dictionary using linq and not worrying about duplicates

A Linq-solution using Distinct() and and no grouping is:

var _people = personList
    .Select(item => new { Key = item.Key, FirstAndLastName = item.FirstAndLastName })
    .Distinct()
    .ToDictionary(item => item.Key, item => item.FirstFirstAndLastName, StringComparer.OrdinalIgnoreCase);

I don't know if it is nicer than LukeH's solution but it works as well.

How to Add Incremental Numbers to a New Column Using Pandas

import numpy as np

df['New_ID']=np.arange(880,880+len(df.Fruit))
df=df.reindex(columns=['New_ID','ID','Fruit'])

push_back vs emplace_back

In addition to what visitor said :

The function void emplace_back(Type&& _Val) provided by MSCV10 is non conforming and redundant, because as you noted it is strictly equivalent to push_back(Type&& _Val).

But the real C++0x form of emplace_back is really useful: void emplace_back(Args&&...);

Instead of taking a value_type it takes a variadic list of arguments, so that means that you can now perfectly forward the arguments and construct directly an object into a container without a temporary at all.

That's useful because no matter how much cleverness RVO and move semantic bring to the table there is still complicated cases where a push_back is likely to make unnecessary copies (or move). For example, with the traditional insert() function of a std::map, you have to create a temporary, which will then be copied into a std::pair<Key, Value>, which will then be copied into the map :

std::map<int, Complicated> m;
int anInt = 4;
double aDouble = 5.0;
std::string aString = "C++";

// cross your finger so that the optimizer is really good
m.insert(std::make_pair(4, Complicated(anInt, aDouble, aString))); 

// should be easier for the optimizer
m.emplace(4, anInt, aDouble, aString);

So why didn't they implement the right version of emplace_back in MSVC? Actually, it bugged me too a while ago, so I asked the same question on the Visual C++ blog. Here is the answer from Stephan T Lavavej, the official maintainer of the Visual C++ standard library implementation at Microsoft.

Q: Are beta 2 emplace functions just some kind of placeholder right now?

A: As you may know, variadic templates aren't implemented in VC10. We simulate them with preprocessor machinery for things like make_shared<T>(), tuple, and the new things in <functional>. This preprocessor machinery is relatively difficult to use and maintain. Also, it significantly affects compilation speed, as we have to repeatedly include subheaders. Due to a combination of our time constraints and compilation speed concerns, we haven't simulated variadic templates in our emplace functions.

When variadic templates are implemented in the compiler, you can expect that we'll take advantage of them in the libraries, including in our emplace functions. We take conformance very seriously, but unfortunately, we can't do everything all at once.

It's an understandable decision. Everyone who tried just once to emulate variadic template with preprocessor horrible tricks knows how disgusting this stuff gets.

Add Bean Programmatically to Spring Web App Context

Actually AnnotationConfigApplicationContext derived from AbstractApplicationContext, which has empty postProcessBeanFactory method left for override

/**
 * Modify the application context's internal bean factory after its standard
 * initialization. All bean definitions will have been loaded, but no beans
 * will have been instantiated yet. This allows for registering special
 * BeanPostProcessors etc in certain ApplicationContext implementations.
 * @param beanFactory the bean factory used by the application context
 */
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}

To leverage this, Create AnnotationConfigApplicationContextProvider class which may look like following(given for Vertx instance example, you can use MyClass instead)...

public class CustomAnnotationApplicationContextProvider {
private final Vertx vertx;

public CustomAnnotationApplicationContextProvider(Vertx vertx) {
    this.vertx = vertx;
}

/**
 * Register all beans to spring bean factory
 *
 * @param beanFactory, spring bean factory to register your instances
 */
private void configureBeans(ConfigurableListableBeanFactory beanFactory) {
    beanFactory.registerSingleton("vertx", vertx);
}

/**
 * Proxy method to create {@link AnnotationConfigApplicationContext} instance with no params
 *
 * @return {@link AnnotationConfigApplicationContext} instance
 */
public AnnotationConfigApplicationContext get() {
    return new AnnotationConfigApplicationContext() {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}

/**
 * Proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(DefaultListableBeanFactory)} with our logic
 *
 * @param beanFactory bean factory for spring
 * @return
 * @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(DefaultListableBeanFactory)
 */
public AnnotationConfigApplicationContext get(DefaultListableBeanFactory beanFactory) {
    return new AnnotationConfigApplicationContext(beanFactory) {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}

/**
 * Proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(Class[])} with our logic
 *
 * @param annotatedClasses, set of annotated classes for spring
 * @return
 * @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(Class[])
 */
public AnnotationConfigApplicationContext get(Class<?>... annotatedClasses) {
    return new AnnotationConfigApplicationContext(annotatedClasses) {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}

/**
 * proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)} with our logic
 *
 * @param basePackages set of base packages for spring
 * @return
 * @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)
 */
public AnnotationConfigApplicationContext get(String... basePackages) {
    return new AnnotationConfigApplicationContext(basePackages) {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}
}

While creating ApplicationContext you can create it using

Vertx vertx = ...; // either create or for vertx, it'll be passed to main verticle
ApplicationContext context = new CustomAnnotationApplicationContextProvider(vertx).get(ApplicationSpringConfig.class);

Javascript - Replace html using innerHTML

You should chain the replace() together instead of assigning the result and replacing again.

var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
                        .replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
                        .replace(/.bbbbbb/g,'/world\">Helloworld</a>');

See DEMO.

Change placeholder text

This solution uses jQuery. If you want to use same placeholder text for all text inputs, you can use

$('input:text').attr('placeholder','Some New Text');

And if you want different placeholders, you can use the element's id to change placeholder

$('#element1_id').attr('placeholder','Some New Text 1');
$('#element2_id').attr('placeholder','Some New Text 2');

What is a NullReferenceException, and how do I fix it?

While what causes a NullReferenceExceptions and approaches to avoid/fix such an exception have been addressed in other answers, what many programmers haven't learned yet is how to independently debug such exceptions during development.

In Visual Studio this is usually easy thanks to the Visual Studio Debugger.


First, make sure that the correct error is going to be caught - see How do I allow breaking on 'System.NullReferenceException' in VS2010? Note1

Then either Start with Debugging (F5) or Attach [the VS Debugger] to Running Process. On occasion it may be useful to use Debugger.Break, which will prompt to launch the debugger.

Now, when the NullReferenceException is thrown (or unhandled) the debugger will stop (remember the rule set above?) on the line on which the exception occurred. Sometimes the error will be easy to spot.

For instance, in the following line the only code that can cause the exception is if myString evaluates to null. This can be verified by looking at the Watch Window or running expressions in the Immediate Window.

var x = myString.Trim();

In more advanced cases, such as the following, you'll need to use one of the techniques above (Watch or Immediate Windows) to inspect the expressions to determine if str1 was null or if str2 was null.

var x = str1.Trim() + str2.Trim();

Once where the exception is throw has been located, it's usually trivial to reason backwards to find out where the null value was [incorrectly] introduced --

Take the time required to understand the cause of the exception. Inspect for null expressions. Inspect the previous expressions which could have resulted in such null expressions. Add breakpoints and step through the program as appropriate. Use the debugger.


1 If Break on Throws is too aggressive and the debugger stops on an NPE in the .NET or 3rd-party library, Break on User-Unhandled can be used to limit the exceptions caught. Additionally, VS2012 introduces Just My Code which I recommend enabling as well.

If you are debugging with Just My Code enabled, the behavior is slightly different. With Just My Code enabled, the debugger ignores first-chance common language runtime (CLR) exceptions that are thrown outside of My Code and do not pass through My Code

How do I get the dialer to open with phone number displayed?

Okay, it is going to be extremely late answer to this question. But here is just one sample if you want to do it in Kotlin.

val intent = Intent(Intent.ACTION_DIAL)
intent.data = Uri.parse("tel:<number>")
startActivity(intent)

Thought it might help someone.

Check if date is in the past Javascript

_x000D_
_x000D_
$('#datepicker').datepicker().change(evt => {_x000D_
  var selectedDate = $('#datepicker').datepicker('getDate');_x000D_
  var now = new Date();_x000D_
  now.setHours(0,0,0,0);_x000D_
  if (selectedDate < now) {_x000D_
    console.log("Selected date is in the past");_x000D_
  } else {_x000D_
    console.log("Selected date is NOT in the past");_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<input type="text" id="datepicker" name="event_date" class="datepicker">
_x000D_
_x000D_
_x000D_

jQuery - select the associated label element of a input field

As long and your input and label elements are associated by their id and for attributes, you should be able to do something like this:

$('.input').each(function() { 
   $this = $(this);
   $label = $('label[for="'+ $this.attr('id') +'"]');
   if ($label.length > 0 ) {
       //this input has a label associated with it, lets do something!
   }
});

If for is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.

How can I make an svg scale with its parent container?

changing the SVG file was not a fair solution for me so instead, I used relative CSS units.

vh, vw, % are very handy. I used a CSS like height: 2.4vh; to set a dynamic size to my SVG images.

Inverse of matrix in R

You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package

What does "pending" mean for request in Chrome Developer Window?

I had the same issue on OSX Mavericks, it turned out that Sophos anti-virus was blocking certain requests, once I uninstalled it the issue went away.

If you think that it might be caused by an extension one easy way to try and test this is to open chrome with the '--disable-extensions flag to see if it fixes the problem. If that doesn't fix it consider looking beyond the browser to see if any other application might be causing the problem, specifically security apps which can affect requests.

Is it possible to view RabbitMQ message contents directly from the command line?

If you want multiple messages from a queue, say 10 messages, the command to use is:

rabbitmqadmin get queue=<QueueName> ackmode=ack_requeue_true count=10

If you don't want the messages requeued, just change ackmode to ack_requeue_false.

Trim Whitespaces (New Line and Tab space) in a String in Oracle

This how I would implement it:

     REGEXP_REPLACE(text,'(^[[:space:]]*|[[:space:]]*$)')

CURL Command Line URL Parameters

The application/x-www-form-urlencoded Content-type header is not needed. Unless the request handler expects the parameters coming from request body. Try it out:

curl -X DELETE "http://localhost:5000/locations?id=3"

or

curl -X GET "http://localhost:5000/locations?id=3"

Reporting Services export to Excel with Multiple Worksheets

As @huttelihut pointed out, this is now possible as of SQL Server 2008 R2 - Read More Here

Prior to 2008 R2 it does't appear possible but MSDN Social has some suggested workarounds.

how to get yesterday's date in C#

You will get yesterday date by this following code snippet.

DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);

console.log(result) returns [object Object]. How do I get result.name?

Use console.log(JSON.stringify(result)) to get the JSON in a string format.

EDIT: If your intention is to get the id and other properties from the result object and you want to see it console to know if its there then you can check with hasOwnProperty and access the property if it does exist:

var obj = {id : "007", name : "James Bond"};
console.log(obj);                    // Object { id: "007", name: "James Bond" }
console.log(JSON.stringify(obj));    //{"id":"007","name":"James Bond"}
if (obj.hasOwnProperty("id")){
    console.log(obj.id);             //007
}

Unable to run Java code with Intellij IDEA

If you are just opened a new java project then create a new folder src/ in the man project location.

Then cut and paste all your package in that folder.

Then Right click on src directory and select option Mark Directory As > Sources Root.

Set bootstrap modal body height by percentage

You've no doubt solved this by now or decided to do something different, but as it has not been answered & I stumbled across this when looking for something similar I thought I'd share my method.

I've taken to using two div sets. One has hidden-xs and is for sm, md & lg device viewing. The other has hidden-sm, -md, -lg and is only for mobile. Now I have a lot more control over the display in my CSS.

You can see a rough idea in this js fiddle where I set the footer and buttons to be smaller when the resolution is of the -xs size.

  <div class="modal-footer">
      <div class="hidden-xs">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary">Save changes</button>
      </div>
      <div class="hidden-sm hidden-md hidden-lg sml-footer">
    <button type="button" class="btn btn-xs btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-xs btn-primary">Save changes</button>
      </div>
  </div>

Finding duplicate values in MySQL

Try using this query:

SELECT name, COUNT(*) value_count FROM company_master GROUP BY name HAVING value_count > 1;

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

MVC 4 Razor adding input type date

I managed to do it by using the following code.

@Html.TextBoxFor(model => model.EndTime, new { type = "time" })

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

Switch to joda-time and you can do this in three lines

DateTime jodaTime = new DateTime();

DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS");
System.out.println("jodaTime = " + formatter.print(jodaTime));

You also have direct access to the individual fields of the date without using a Calendar.

System.out.println("year = " + jodaTime.getYear());
System.out.println("month = " + jodaTime.getMonthOfYear());
System.out.println("day = " + jodaTime.getDayOfMonth());
System.out.println("hour = " + jodaTime.getHourOfDay());
System.out.println("minute = " + jodaTime.getMinuteOfHour());
System.out.println("second = " + jodaTime.getSecondOfMinute());
System.out.println("millis = " + jodaTime.getMillisOfSecond());

Output is as follows:

jodaTime = 2010-04-16 18:09:26.060

year = 2010
month = 4
day = 16
hour = 18
minute = 9
second = 26
millis = 60

According to http://www.joda.org/joda-time/

Joda-Time is the de facto standard date and time library for Java. From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310).

T-SQL stored procedure that accepts multiple Id values

Try This One:

@list_of_params varchar(20) -- value 1, 2, 5, 7, 20 

SELECT d.[Name]
FROM Department d
where @list_of_params like ('%'+ CONVERT(VARCHAR(10),d.Id)  +'%')

very simple.

getting only name of the class Class.getName()

Get simple name instead of path.

String onlyClassName =  this.getLocalClassName(); 

call above method in onCreate

Android: how to draw a border to a LinearLayout

Do you really need to do that programmatically?

Just considering the title: You could use a ShapeDrawable as android:background…

For example, let's define res/drawable/my_custom_background.xml as:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <corners
      android:radius="2dp"
      android:topRightRadius="0dp"
      android:bottomRightRadius="0dp"
      android:bottomLeftRadius="0dp" />
  <stroke
      android:width="1dp"
      android:color="@android:color/white" />
</shape>

and define android:background="@drawable/my_custom_background".

I've not tested but it should work.

Update:

I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/border"
    android:padding="10dip" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
    [... more TextView ...]
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
</LinearLayout>

and a res/drawable/border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
   <stroke
        android:width="5dip"
        android:color="@android:color/white" />
</shape>

Reported to work on a gingerbread device. Note that you'll need to relate android:padding of the LinearLayout to the android:width shape/stroke's value. Please, do not use @android:color/white in your final application but rather a project defined color.

You could apply android:background="@drawable/border" android:padding="10dip" to each of the LinearLayout from your provided sample.

As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…

Your problem resides clearly in the use of getBorder.set{Width,Height}(100);. Why do you do that in an onClick method?

I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.

To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…

List vs tuple, when to use each?

There's a strong culture of tuples being for heterogeneous collections, similar to what you'd use structs for in C, and lists being for homogeneous collections, similar to what you'd use arrays for. But I've never quite squared this with the mutability issue mentioned in the other answers. Mutability has teeth to it (you actually can't change a tuple), while homogeneity is not enforced, and so seems to be a much less interesting distinction.

how to move elasticsearch data from one server to another

You can take a snapshot of the complete status of your cluster (including all data indices) and restore them (using the restore API) in the new cluster or server.

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

Switching to landscape mode in Android Emulator

The complete listing is buried in the android docs, and i only found it via google / dogpile.

http://developer.android.com/tools/help/emulator.html

That link has the emulator shortcut keys as of right now.

=\

Can I nest a <button> element inside an <a> using HTML5?

Another option is to use the onclick attribute of the button:

<button disabled="disabled" onClick="location.href='www.stackoverflow.com'" >ABC</button>

This works, however, the user won't see the link displayed on hover as they would if it were inside the element.

SET NAMES utf8 in MySQL?

This query should be written before the query which create or update data in the database, this query looks like :

mysql_query("set names 'utf8'");

Note that you should write the encode which you are using in the header for example if you are using utf-8 you add it like this in the header or it will couse a problem with Internet Explorer

so your page looks like this

<html>
    <head>
        <title>page title</title>
        <meta charset="UTF-8" />   
    </head>
    <body>
    <?php
            mysql_query("set names 'utf8'");   
            $sql = "INSERT * FROM ..... ";  
            mysql_query($sql);
    ?>    

    </body>
</html>

Android ImageView's onClickListener does not work

Check if other view has the property match_parent or fill_parent ,those properties may cover your ImageView which has shown in your RelativeLayout.By the way,the accepted answer does not work in my case.

Disable clipboard prompt in Excel VBA on workbook close

Just clear the clipboard before closing.

Application.CutCopyMode=False
ActiveWindow.Close

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

error, string or binary data would be truncated when trying to insert

You simply can't beat SQL Server on this.

You can insert into a new table like this:

select foo, bar
into tmp_new_table_to_dispose_later
from my_table

and compare the table definition with the real table you want to insert the data into.

Sometime it's helpful sometimes it's not.

If you try inserting in the final/real table from that temporary table it may just work (due to data conversion working differently than SSMS for example).

Another alternative is to insert the data in chunks, instead of inserting everything immediately you insert with top 1000 and you repeat the process, till you find a chunk with an error. At least you have better visibility on what's not fitting into the table.

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

If your process gives a huge stdout and no stderr, communicate() might be the wrong way to go due to memory restrictions.

Instead,

process = subprocess.Popen(cmd, shell=True,
                           stdout=subprocess.PIPE, 
                           stderr=subprocess.PIPE)

# wait for the process to terminate
for line in process.stdout: do_something(line)
errcode = process.returncode

might be the way to go.

process.stdout is a file-like object which you can treat as any other such object, mainly:

  • you can read() from it
  • you can readline() from it and
  • you can iterate over it.

The latter is what I do above in order to get its contents line by line.

Difference between using Throwable and Exception in a try catch

Throwable is super class of Exception as well as Error. In normal cases we should always catch sub-classes of Exception, so that the root cause doesn't get lost.

Only special cases where you see possibility of things going wrong which is not in control of your Java code, you should catch Error or Throwable.

I remember catching Throwable to flag that a native library is not loaded.

Is it possible to import modules from all files in a directory, using a wildcard?

This is not exactly what you asked for but, with this method I can Iterate throught componentsList in my other files and use function such as componentsList.map(...) which I find pretty usefull !

import StepOne from './StepOne';
import StepTwo from './StepTwo';
import StepThree from './StepThree';
import StepFour from './StepFour';
import StepFive from './StepFive';
import StepSix from './StepSix';
import StepSeven from './StepSeven';
import StepEight from './StepEight';

const componentsList= () => [
  { component: StepOne(), key: 'step1' },
  { component: StepTwo(), key: 'step2' },
  { component: StepThree(), key: 'step3' },
  { component: StepFour(), key: 'step4' },
  { component: StepFive(), key: 'step5' },
  { component: StepSix(), key: 'step6' },
  { component: StepSeven(), key: 'step7' },
  { component: StepEight(), key: 'step8' }
];

export default componentsList;

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

Changing the default icon in a Windows Forms application

Add your icon as a Resource (Project > yourprojectname Properties > Resources > Pick "Icons from dropdown > Add Resource (or choose Add Existing File from dropdown if you already have the .ico)

Then:

this.Icon = Properties.Resources.youriconname;

Storing integer values as constants in Enum manner in java

You can use ordinal. So PAGE.SIGN_CREATE.ordinal() returns 1.

EDIT:

The only problem with doing this is that if you add, remove or reorder the enum values you will break the system. For many this is not an issue as they will not remove enums and will only add additional values to the end. It is also no worse than integer constants which also require you not to renumber them. However it is best to use a system like:

public enum PAGE{
  SIGN_CREATE0(0), SIGN_CREATE(1) ,HOME_SCREEN(2), REGISTER_SCREEN(3)

  private int id;

  PAGE(int id){
    this.id = id;
  }

  public int getID(){
    return id;
  }

}

You can then use getID. So PAGE.SIGN_CREATE.getID() returns 1.

How to add a margin to a table row <tr>

You can't style the <tr>s themselves, but you can give the <td>s inside the "highlight" <tr>s a style, like this

tr.highlight td {padding-top: 10px; padding-bottom:10px}

How can I add NSAppTransportSecurity to my info.plist file?

try With this --- worked for me in Xcode-beta 4 7.0

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>yourdomain.com</key>
        <dict>
            <!--Include to allow subdomains-->
            <key>NSIncludesSubdomains</key>
            <true/>
            <!--Include to allow HTTP requests-->
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <!--Include to specify minimum TLS version-->
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
        </dict>
    </dict>
</dict>

Also one more option, if you want to disable ATS you can use this :

<key>NSAppTransportSecurity</key>  
 <dict>  
      <key>NSAllowsArbitraryLoads</key><true/>  
 </dict>

But this is not recommended at all. The server should have the SSL certificates and so that there is no privacy leaks.

Axios get in url works but with second parameter as object it doesn't

axios.get accepts a request config as the second parameter (not query string params).

You can use the params config option to set query string params as follows:

axios.get('/api', {
  params: {
    foo: 'bar'
  }
});

Pass array to MySQL stored routine

I'm not sure if this is fully answering the question (it isn't), but it's the solution I came up with for my similar problem. Here I try to just use LOCATE() just once per delimiter.

-- *****************************************************************************
-- test_PVreplace

DROP FUNCTION IF EXISTS test_PVreplace;

delimiter //
CREATE FUNCTION test_PVreplace (
   str TEXT,   -- String to do search'n'replace on
   pv TEXT     -- Parameter/value pairs 'p1=v1|p2=v2|p3=v3'
   )
   RETURNS TEXT

-- Replace specific tags with specific values.

sproc:BEGIN
   DECLARE idx INT;
   DECLARE idx0 INT DEFAULT 1;   -- 1-origined, not 0-origined
   DECLARE len INT;
   DECLARE sPV TEXT;
   DECLARE iPV INT;
   DECLARE sP TEXT;
   DECLARE sV TEXT;

   -- P/V string *must* end with a delimiter.

   IF (RIGHT (pv, 1) <> '|') THEN
      SET pv = CONCAT (pv, '|');
      END IF;

   -- Find all the P/V pairs.

   SELECT LOCATE ('|', pv, idx0) INTO idx;
   WHILE (idx > 0) DO
      SET len = idx - idx0;
      SELECT SUBSTRING(pv, idx0, len) INTO sPV;

      -- Found a P/V pair.  Break it up.

      SELECT LOCATE ('=', sPV) INTO iPV;
      IF (iPV = 0) THEN
         SET sP = sPV;
         SET sV = '';
      ELSE
         SELECT SUBSTRING(sPV, 1, iPV-1) INTO sP;
         SELECT SUBSTRING(sPV, iPV+1) INTO sV;
         END IF;

      -- Do the substitution(s).

      SELECT REPLACE (str, sP, sV) INTO str;

      -- Do next P/V pair.

      SET idx0 = idx + 1;
      SELECT LOCATE ('|', pv, idx0) INTO idx;
      END WHILE;
   RETURN (str);
END//
delimiter ;

SELECT test_PVreplace ('%one% %two% %three%', '%one%=1|%two%=2|%three%=3');
SELECT test_PVreplace ('%one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', NULL);
SELECT test_PVreplace ('%one% %two% %three%', '%one%=%two%|%two%=%three%|%three%=III');

In AVD emulator how to see sdcard folder? and Install apk to AVD?

On linux sdcard image is located in:

~/.android/avd/<avd name>.avd/sdcard.img

You can mount it for example with (assuming /mnt/sdcard is existing directory):

sudo mount sdcard.img -o loop /mnt/sdcard

To install apk file use adb:

adb install your_app.apk

How to upgrade safely php version in wamp server

To add to the above answer (do steps 1-5).

  1. Click on WAMP -> Select PHP -> Versions: Select the new version installed
  2. Check that your PATH folder is updated to new path to PHP so your OS has same PHP version of WAMP.

LINQ equivalent of foreach for IEnumerable<T>

I took Fredrik's method and modified the return type.

This way, the method supports deferred execution like other LINQ methods.

EDIT: If this wasn't clear, any usage of this method must end with ToList() or any other way to force the method to work on the complete enumerable. Otherwise, the action would not be performed!

public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach (T item in enumeration)
    {
        action(item);
        yield return item;
    }
}

And here's the test to help see it:

[Test]
public void TestDefferedExecutionOfIEnumerableForEach()
{
    IEnumerable<char> enumerable = new[] {'a', 'b', 'c'};

    var sb = new StringBuilder();

    enumerable
        .ForEach(c => sb.Append("1"))
        .ForEach(c => sb.Append("2"))
        .ToList();

    Assert.That(sb.ToString(), Is.EqualTo("121212"));
}

If you remove the ToList() in the end, you will see the test failing since the StringBuilder contains an empty string. This is because no method forced the ForEach to enumerate.

Explicitly select items from a list or tuple

Maybe a list comprehension is in order:

L = ['a', 'b', 'c', 'd', 'e', 'f']
print [ L[index] for index in [1,3,5] ]

Produces:

['b', 'd', 'f']

Is that what you are looking for?

How to specify multiple return types using type-hints

Python 3.10 (use |): Example for a function which takes a single argument that is either an int or str and returns either an int or str:

def func(arg: int | str) -> int | str:
              ^^^^^^^^^     ^^^^^^^^^ 
             type of arg   return type

Python 3.5 - 3.9 (use typing.Union):

from typing import Union
def func(arg: Union[int, str]) -> Union[int, str]:
              ^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^^ 
                type of arg         return type

For the special case of X | None you can use Optional[X].

Java JTable setting Column Width

JTable.AUTO_RESIZE_LAST_COLUMN is defined as "During all resize operations, apply adjustments to the last column only" which means you have to set the autoresizemode at the end of your code, otherwise setPreferredWidth() won't affect anything!

So in your case this would be the correct way:

table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(400);
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);

How SQL query result insert in temp table?

You can use select ... into ... to create and populate a temp table and then query the temp table to return the result.

select *
into #TempTable
from YourTable

select *
from #TempTable

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Why is Node.js single threaded?

Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.

And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.

The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.

In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.

What is the difference between OFFLINE and ONLINE index rebuild in SQL Server?

The main differences are:

1) OFFLINE index rebuild is faster than ONLINE rebuild.

2) Extra disk space required during SQL Server online index rebuilds.

3) SQL Server locks acquired with SQL Server online index rebuilds.

  • This schema modification lock blocks all other concurrent access to the table, but it is only held for a very short period of time while the old index is dropped and the statistics updated.

How to implement "Access-Control-Allow-Origin" header in asp.net

From enable-cors.org:

CORS on ASP.NET

If you don't have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:

Response.AppendHeader("Access-Control-Allow-Origin", "*");

See also: Configuring IIS6 / IIS7

I want to load another HTML page after a specific amount of time

Use Javascript's setTimeout:

<body onload="setTimeout(function(){window.location = 'form2.html';}, 5000)">

How does java do modulus calculations with negative numbers?

Since "mathematically" both are correct:

-13 % 64 = -13 (on modulus 64)  
-13 % 64 = 51 (on modulus 64)

One of the options had to be chosen by Java language developers and they chose:

the sign of the result equals the sign of the dividend.

Says it in Java specs:

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3

Get the generated SQL statement from a SqlCommand object?

Modified version of Kon's answer as it only partially works with similar named parameters. The down side of using String Replace function. Other than that, I give him full credit on the solution.

private string GetActualQuery(SqlCommand sqlcmd)
{
    string query = sqlcmd.CommandText;
    string parameters = "";
    string[] strArray = System.Text.RegularExpressions.Regex.Split(query, " VALUES ");

    //Reconstructs the second half of the SQL Command
    parameters = "(";

    int count = 0;
    foreach (SqlParameter p in sqlcmd.Parameters)
    {
        if (count == (sqlcmd.Parameters.Count - 1))
        {
            parameters += p.Value.ToString();
        }
        else
        {
            parameters += p.Value.ToString() + ", ";
        }
        count++;
    }

    parameters += ")";

    //Returns the string recombined.
    return strArray[0] + " VALUES " + parameters;
}

How to properly create composite primary keys - MYSQL

I would not make the primary key of the "info" table a composite of the two values from other tables.

Others can articulate the reasons better, but it feels wrong to have a column that is really made up of two pieces of information. What if you want to sort on the ID from the second table for some reason? What if you want to count the number of times a value from either table is present?

I would always keep these as two distinct columns. You could use a two-column primay key in mysql ...PRIMARY KEY(id_a, id_b)... but I prefer using a two-column unique index, and having an auto-increment primary key field.

How is using OnClickListener interface different via XML and Java code?

Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.

How to output an Excel *.xls file from classic ASP

You must specify the file to be downloaded (attachment) by the client in the http header:

Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader "content-disposition", "attachment: filename=excelTest.xls"

http://classicasp.aspfaq.com/general/how-do-i-prompt-a-save-as-dialog-for-an-accepted-mime-type.html

Difference between Big-O and Little-O Notation

In general

Asymptotic notation is something you can understand as: how do functions compare when zooming out? (A good way to test this is simply to use a tool like Desmos and play with your mouse wheel). In particular:

  • f(n) ? o(n) means: at some point, the more you zoom out, the more f(n) will be dominated by n (it will progressively diverge from it).
  • g(n) ? T(n) means: at some point, zooming out will not change how g(n) compare to n (if we remove ticks from the axis you couldn't tell the zoom level).

Finally h(n) ? O(n) means that function h can be in either of these two categories. It can either look a lot like n or it could be smaller and smaller than n when n increases. Basically, both f(n) and g(n) are also in O(n).

In computer science

In computer science, people will usually prove that a given algorithm admits both an upper O and a lower bound . When both bounds meet that means that we found an asymptotically optimal algorithm to solve that particular problem.

For example, if we prove that the complexity of an algorithm is both in O(n) and (n) it implies that its complexity is in T(n). That's the definition of T and it more or less translates to "asymptotically equal". Which also means that no algorithm can solve the given problem in o(n). Again, roughly saying "this problem can't be solved in less than n steps".

An upper bound of O(n) simply means that even in the worse case, the algorithm will terminate in at most n steps (ignoring all constant factors, both multiplicative and additive). A lower bound of (n) means on the opposite that we built some examples where the problem solved by this algorithm couldn't be solved in less than n steps (again ignoring multiplicative and additive constants). The number of steps is at most n and at least n so this problem complexity is "exactly n". Instead of saying "ignoring constant multiplicative/additive factor" every time we just write T(n) for short.

How to script FTP upload and download?

I was having a similar issue - like the original poster, I wanted to automate a file upload but I couldn't figure out how. Because this is on a register terminal at my family's store, I didn't want to install powershell (although that looks like an easy option), just wanted a simple .bat file to do this. This is pretty much what grawity and another user said; I'm new to this stuff, so here's a more detailed example and explanation (thanks also to http://www.howtogeek.com/howto/windows/how-to-automate-ftp-uploads-from-the-windows-command-line/ who explains how to do it with just one .bat file.)

Essentially you need 2 files - one .bat and one .txt. The .bat tells ftp.exe what switches to use. The .txt gives a list of commands to ftp.exe. In the text file put this:

username
password
cd whereverYouWantToPutTheFile
lcd whereverTheFileComesFrom
put C:\InventoryExport\inventory.test (or your file path)
bye

Save that wherever you want. In the BAT file put:

ftp.exe -s:C:\Windows\System32\test.txt destinationIP
pause

Obviously change the path after the -s: to wherever your text file is. Take out the pause when you're actually running it - it's just so you can see any errors. Of course, you can use "get" or any other ftp command in the .txt file to do whatever you need to do.

I'm not positive that you need the lcd command in the text file, like I said I'm new to using command line for this type of thing, but this is working for me.

No connection could be made because the target machine actively refused it?

For me, I wanted to start the mongo in shell (irrelevant of the exact context of the question, but having the same error message before even starting the mongo in shell)

The process 'MongoDB Service' wasn't running in Services

Start cmd as Administrator and type,

net start MongoDB

Just to see MongoDB is up and running just type mongo, in cmd it will give Mongo version details and Mongo Connection URL

What does the "+=" operator do in Java?

As others have said, it's bitwise XOR. If you want to raise a number to a given power, use Math.pow(a , b), where a is a number and b is the power.

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

JavaScript - get the first day of the week from current date

CMS's answer is correct but assumes that Monday is the first day of the week.
Chandler Zwolle's answer is correct but fiddles with the Date prototype.
Other answers that play with hour/minutes/seconds/milliseconds are wrong.

The function below is correct and takes a date as first parameter and the desired first day of the week as second parameter (0 for Sunday, 1 for Monday, etc.). Note: the hour, minutes and seconds are set to 0 to have the beginning of the day.

_x000D_
_x000D_
function firstDayOfWeek(dateObject, firstDayOfWeekIndex) {_x000D_
_x000D_
    const dayOfWeek = dateObject.getDay(),_x000D_
        firstDayOfWeek = new Date(dateObject),_x000D_
        diff = dayOfWeek >= firstDayOfWeekIndex ?_x000D_
            dayOfWeek - firstDayOfWeekIndex :_x000D_
            6 - dayOfWeek_x000D_
_x000D_
    firstDayOfWeek.setDate(dateObject.getDate() - diff)_x000D_
    firstDayOfWeek.setHours(0,0,0,0)_x000D_
_x000D_
    return firstDayOfWeek_x000D_
}_x000D_
_x000D_
// August 18th was a Saturday_x000D_
let lastMonday = firstDayOfWeek(new Date('August 18, 2018 03:24:00'), 1)_x000D_
_x000D_
// outputs something like "Mon Aug 13 2018 00:00:00 GMT+0200"_x000D_
// (may vary according to your time zone)_x000D_
document.write(lastMonday)
_x000D_
_x000D_
_x000D_

Using IQueryable with Linq

Although Reed Copsey and Marc Gravell already described about IQueryable (and also IEnumerable) enough,mI want to add little more here by providing a small example on IQueryable and IEnumerable as many users asked for it

Example: I have created two table in database

   CREATE TABLE [dbo].[Employee]([PersonId] [int] NOT NULL PRIMARY KEY,[Gender] [nchar](1) NOT NULL)
   CREATE TABLE [dbo].[Person]([PersonId] [int] NOT NULL PRIMARY KEY,[FirstName] [nvarchar](50) NOT NULL,[LastName] [nvarchar](50) NOT NULL)

The Primary key(PersonId) of table Employee is also a forgein key(personid) of table Person

Next i added ado.net entity model in my application and create below service class on that

public class SomeServiceClass
{   
    public IQueryable<Employee> GetEmployeeAndPersonDetailIQueryable(IEnumerable<int> employeesToCollect)
    {
        DemoIQueryableEntities db = new DemoIQueryableEntities();
        var allDetails = from Employee e in db.Employees
                         join Person p in db.People on e.PersonId equals p.PersonId
                         where employeesToCollect.Contains(e.PersonId)
                         select e;
        return allDetails;
    }

    public IEnumerable<Employee> GetEmployeeAndPersonDetailIEnumerable(IEnumerable<int> employeesToCollect)
    {
        DemoIQueryableEntities db = new DemoIQueryableEntities();
        var allDetails = from Employee e in db.Employees
                         join Person p in db.People on e.PersonId equals p.PersonId
                         where employeesToCollect.Contains(e.PersonId)
                         select e;
        return allDetails;
    }
}

they contains same linq. It called in program.cs as defined below

class Program
{
    static void Main(string[] args)
    {
        SomeServiceClass s= new SomeServiceClass(); 

        var employeesToCollect= new []{0,1,2,3};

        //IQueryable execution part
        var IQueryableList = s.GetEmployeeAndPersonDetailIQueryable(employeesToCollect).Where(i => i.Gender=="M");            
        foreach (var emp in IQueryableList)
        {
            System.Console.WriteLine("ID:{0}, EName:{1},Gender:{2}", emp.PersonId, emp.Person.FirstName, emp.Gender);
        }
        System.Console.WriteLine("IQueryable contain {0} row in result set", IQueryableList.Count());

        //IEnumerable execution part
        var IEnumerableList = s.GetEmployeeAndPersonDetailIEnumerable(employeesToCollect).Where(i => i.Gender == "M");
        foreach (var emp in IEnumerableList)
        {
           System.Console.WriteLine("ID:{0}, EName:{1},Gender:{2}", emp.PersonId, emp.Person.FirstName, emp.Gender);
        }
        System.Console.WriteLine("IEnumerable contain {0} row in result set", IEnumerableList.Count());

        Console.ReadKey();
    }
}

The output is same for both obviously

ID:1, EName:Ken,Gender:M  
ID:3, EName:Roberto,Gender:M  
IQueryable contain 2 row in result set  
ID:1, EName:Ken,Gender:M  
ID:3, EName:Roberto,Gender:M  
IEnumerable contain 2 row in result set

So the question is what/where is the difference? It does not seem to have any difference right? Really!!

Let's have a look on sql queries generated and executed by entity framwork 5 during these period

IQueryable execution part

--IQueryableQuery1 
SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE ([Extent1].[PersonId] IN (0,1,2,3)) AND (N'M' = [Extent1].[Gender])

--IQueryableQuery2
SELECT 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT 
    COUNT(1) AS [A1]
    FROM [dbo].[Employee] AS [Extent1]
    WHERE ([Extent1].[PersonId] IN (0,1,2,3)) AND (N'M' = [Extent1].[Gender])
)  AS [GroupBy1]

IEnumerable execution part

--IEnumerableQuery1
SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE [Extent1].[PersonId] IN (0,1,2,3)

--IEnumerableQuery2
SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE [Extent1].[PersonId] IN (0,1,2,3)

Common script for both execution part

/* these two query will execute for both IQueryable or IEnumerable to get details from Person table
   Ignore these two queries here because it has nothing to do with IQueryable vs IEnumerable
--ICommonQuery1 
exec sp_executesql N'SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[FirstName] AS [FirstName], 
[Extent1].[LastName] AS [LastName]
FROM [dbo].[Person] AS [Extent1]
WHERE [Extent1].[PersonId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1

--ICommonQuery2
exec sp_executesql N'SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[FirstName] AS [FirstName], 
[Extent1].[LastName] AS [LastName]
FROM [dbo].[Person] AS [Extent1]
WHERE [Extent1].[PersonId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=3
*/

So you have few questions now, let me guess those and try to answer them

Why are different scripts generated for same result?

Lets find out some points here,

all queries has one common part

WHERE [Extent1].[PersonId] IN (0,1,2,3)

why? Because both function IQueryable<Employee> GetEmployeeAndPersonDetailIQueryable and IEnumerable<Employee> GetEmployeeAndPersonDetailIEnumerable of SomeServiceClass contains one common line in linq queries

where employeesToCollect.Contains(e.PersonId)

Than why is the AND (N'M' = [Extent1].[Gender]) part is missing in IEnumerable execution part, while in both function calling we used Where(i => i.Gender == "M") inprogram.cs`

Now we are in the point where difference came between IQueryable and IEnumerable

What entity framwork does when an IQueryable method called, it tooks linq statement written inside the method and try to find out if more linq expressions are defined on the resultset, it then gathers all linq queries defined until the result need to fetch and constructs more appropriate sql query to execute.

It provide a lots of benefits like,

  • only those rows populated by sql server which could be valid by the whole linq query execution
  • helps sql server performance by not selecting unnecessary rows
  • network cost get reduce

like here in example sql server returned to application only two rows after IQueryable execution` but returned THREE rows for IEnumerable query why?

In case of IEnumerable method, entity framework took linq statement written inside the method and constructs sql query when result need to fetch. it does not include rest linq part to constructs the sql query. Like here no filtering is done in sql server on column gender.

But the outputs are same? Because 'IEnumerable filters the result further in application level after retrieving result from sql server

SO, what should someone choose? I personally prefer to define function result as IQueryable<T> because there are lots of benefit it has over IEnumerable like, you could join two or more IQueryable functions, which generate more specific script to sql server.

Here in example you can see an IQueryable Query(IQueryableQuery2) generates a more specific script than IEnumerable query(IEnumerableQuery2) which is much more acceptable in my point of view.

A cron job for rails: best practices?

you can use resque and resque-schedular gem for creating cron, this is very easy to do.

https://github.com/resque/resque

https://github.com/resque/resque-scheduler

When to use an interface instead of an abstract class and vice versa?

When to do what is a very simple thing if you have the concept clear in your mind.

Abstract classes can be Derived whereas Interfaces can be Implemented. There is some difference between the two. When you derive an Abstract class, the relationship between the derived class and the base class is 'is a' relationship. e.g., a Dog is an Animal, a Sheep is an Animal which means that a Derived class is inheriting some properties from the base class.

Whereas for implementation of interfaces, the relationship is "can be". e.g., a Dog can be a spy dog. A dog can be a circus dog. A dog can be a race dog. Which means that you implement certain methods to acquire something.

I hope I am clear.

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

Complementing @Bob Jarvis and @dmikam answer, Postgres don't perform a good plan when you don't use LATERAL, below a simulation, in both cases the query data results are the same, but the cost are very different

Table structure

CREATE TABLE ITEMS (
    N INTEGER NOT NULL,
    S TEXT NOT NULL
);

INSERT INTO ITEMS
  SELECT
    (random()*1000000)::integer AS n,
    md5(random()::text) AS s
  FROM
    generate_series(1,1000000);

CREATE INDEX N_INDEX ON ITEMS(N);

Performing JOIN with GROUP BY in subquery without LATERAL

EXPLAIN 
SELECT 
    I.*
FROM ITEMS I
INNER JOIN (
    SELECT 
        COUNT(1), n
    FROM ITEMS
    GROUP BY N
) I2 ON I2.N = I.N
WHERE I.N IN (243477, 997947);

The results

Merge Join  (cost=0.87..637500.40 rows=23 width=37)
  Merge Cond: (i.n = items.n)
  ->  Index Scan using n_index on items i  (cost=0.43..101.28 rows=23 width=37)
        Index Cond: (n = ANY ('{243477,997947}'::integer[]))
  ->  GroupAggregate  (cost=0.43..626631.11 rows=861418 width=12)
        Group Key: items.n
        ->  Index Only Scan using n_index on items  (cost=0.43..593016.93 rows=10000000 width=4)

Using LATERAL

EXPLAIN 
SELECT 
    I.*
FROM ITEMS I
INNER JOIN LATERAL (
    SELECT 
        COUNT(1), n
    FROM ITEMS
    WHERE N = I.N
    GROUP BY N
) I2 ON 1=1 --I2.N = I.N
WHERE I.N IN (243477, 997947);

Results

Nested Loop  (cost=9.49..1319.97 rows=276 width=37)
  ->  Bitmap Heap Scan on items i  (cost=9.06..100.20 rows=23 width=37)
        Recheck Cond: (n = ANY ('{243477,997947}'::integer[]))
        ->  Bitmap Index Scan on n_index  (cost=0.00..9.05 rows=23 width=0)
              Index Cond: (n = ANY ('{243477,997947}'::integer[]))
  ->  GroupAggregate  (cost=0.43..52.79 rows=12 width=12)
        Group Key: items.n
        ->  Index Only Scan using n_index on items  (cost=0.43..52.64 rows=12 width=4)
              Index Cond: (n = i.n)

My Postgres version is PostgreSQL 10.3 (Debian 10.3-1.pgdg90+1)

How can I check if a background image is loaded?

There are no JS callbacks for CSS assets.

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Vava's answer is on the mark. If you use jQuery, then the $.each() function takes care of this, hence it is safer to use.

$.each(evtListeners, function(index, elem) {
    // your code
});

GDB: Listing all mapped memory regions for a crashed process

You can also use info files to list all the sections of all the binaries loaded in process binary.

How to Alter Constraint

No. We cannot alter the constraint, only thing we can do is drop and recreate it

ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]

Foreign Key Constraint

Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade

Primary Key constraint

Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)

Entity Framework .Remove() vs. .DeleteObject()

If you really want to use Deleted, you'd have to make your foreign keys nullable, but then you'd end up with orphaned records (which is one of the main reasons you shouldn't be doing that in the first place). So just use Remove()

ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

A thing worth noting is that setting .State = EntityState.Deleted does not trigger automatically detected change. (archive)

git index.lock File exists when I try to commit, but cannot delete the file

On Linux, Unix, Git Bash, or Cygwin, try:

rm -f .git/index.lock

On Windows Command Prompt, try:

del .git\index.lock


For Windows:

  • From a PowerShell console opened as administrator, try

    rm -Force ./.git/index.lock
    
  • If that does not work, you must kill all git.exe processes

    taskkill /F /IM git.exe
    

    SUCCESS: The process "git.exe" with PID 20448 has been terminated.
    SUCCESS: The process "git.exe" with PID 11312 has been terminated.
    SUCCESS: The process "git.exe" with PID 23868 has been terminated.
    SUCCESS: The process "git.exe" with PID 27496 has been terminated.
    SUCCESS: The process "git.exe" with PID 33480 has been terminated.
    SUCCESS: The process "git.exe" with PID 28036 has been terminated. \

    rm -Force ./.git/index.lock
    

How to assign a value to a TensorFlow variable?

So i had a adifferent case where i needed to assign values before running a session, So this was the easiest way to do that:

other_variable = tf.get_variable("other_variable", dtype=tf.int32,
  initializer=tf.constant([23, 42]))

here i'm creating a variable as well as assigning it values at the same time

How to stop C++ console application from exiting immediately?

If you are using Visual Studio and you are starting the console application out of the IDE:

pressing CTRL-F5 (start without debugging) will start the application and keep the console window open until you press any key.

How can I merge properties of two JavaScript objects dynamically?

Prototype has this:

Object.extend = function(destination,source) {
    for (var property in source)
        destination[property] = source[property];
    return destination;
}

obj1.extend(obj2) will do what you want.

Using Java with Nvidia GPUs (CUDA)

First of all, you should be aware of the fact that CUDA will not automagically make computations faster. On the one hand, because GPU programming is an art, and it can be very, very challenging to get it right. On the other hand, because GPUs are well-suited only for certain kinds of computations.

This may sound confusing, because you can basically compute anything on the GPU. The key point is, of course, whether you will achieve a good speedup or not. The most important classification here is whether a problem is task parallel or data parallel. The first one refers, roughly speaking, to problems where several threads are working on their own tasks, more or less independently. The second one refers to problems where many threads are all doing the same - but on different parts of the data.

The latter is the kind of problem that GPUs are good at: They have many cores, and all the cores do the same, but operate on different parts of the input data.

You mentioned that you have "simple math but with huge amount of data". Although this may sound like a perfectly data-parallel problem and thus like it was well-suited for a GPU, there is another aspect to consider: GPUs are ridiculously fast in terms of theoretical computational power (FLOPS, Floating Point Operations Per Second). But they are often throttled down by the memory bandwidth.

This leads to another classification of problems. Namely whether problems are memory bound or compute bound.

The first one refers to problems where the number of instructions that are done for each data element is low. For example, consider a parallel vector addition: You'll have to read two data elements, then perform a single addition, and then write the sum into the result vector. You will not see a speedup when doing this on the GPU, because the single addition does not compensate for the efforts of reading/writing the memory.

The second term, "compute bound", refers to problems where the number of instructions is high compared to the number of memory reads/writes. For example, consider a matrix multiplication: The number of instructions will be O(n^3) when n is the size of the matrix. In this case, one can expect that the GPU will outperform a CPU at a certain matrix size. Another example could be when many complex trigonometric computations (sine/cosine etc) are performed on "few" data elements.

As a rule of thumb: You can assume that reading/writing one data element from the "main" GPU memory has a latency of about 500 instructions....

Therefore, another key point for the performance of GPUs is data locality: If you have to read or write data (and in most cases, you will have to ;-)), then you should make sure that the data is kept as close as possible to the GPU cores. GPUs thus have certain memory areas (referred to as "local memory" or "shared memory") that usually is only a few KB in size, but particularly efficient for data that is about to be involved in a computation.

So to emphasize this again: GPU programming is an art, that is only remotely related to parallel programming on the CPU. Things like Threads in Java, with all the concurrency infrastructure like ThreadPoolExecutors, ForkJoinPools etc. might give the impression that you just have to split your work somehow and distribute it among several processors. On the GPU, you may encounter challenges on a much lower level: Occupancy, register pressure, shared memory pressure, memory coalescing ... just to name a few.

However, when you have a data-parallel, compute-bound problem to solve, the GPU is the way to go.


A general remark: Your specifically asked for CUDA. But I'd strongly recommend you to also have a look at OpenCL. It has several advantages. First of all, it's an vendor-independent, open industry standard, and there are implementations of OpenCL by AMD, Apple, Intel and NVIDIA. Additionally, there is a much broader support for OpenCL in the Java world. The only case where I'd rather settle for CUDA is when you want to use the CUDA runtime libraries, like CUFFT for FFT or CUBLAS for BLAS (Matrix/Vector operations). Although there are approaches for providing similar libraries for OpenCL, they can not directly be used from Java side, unless you create your own JNI bindings for these libraries.


You might also find it interesting to hear that in October 2012, the OpenJDK HotSpot group started the project "Sumatra": http://openjdk.java.net/projects/sumatra/ . The goal of this project is to provide GPU support directly in the JVM, with support from the JIT. The current status and first results can be seen in their mailing list at http://mail.openjdk.java.net/mailman/listinfo/sumatra-dev


However, a while ago, I collected some resources related to "Java on the GPU" in general. I'll summarize these again here, in no particular order.

(Disclaimer: I'm the author of http://jcuda.org/ and http://jocl.org/ )

(Byte)code translation and OpenCL code generation:

https://github.com/aparapi/aparapi : An open-source library that is created and actively maintained by AMD. In a special "Kernel" class, one can override a specific method which should be executed in parallel. The byte code of this method is loaded at runtime using an own bytecode reader. The code is translated into OpenCL code, which is then compiled using the OpenCL compiler. The result can then be executed on the OpenCL device, which may be a GPU or a CPU. If the compilation into OpenCL is not possible (or no OpenCL is available), the code will still be executed in parallel, using a Thread Pool.

https://github.com/pcpratts/rootbeer1 : An open-source library for converting parts of Java into CUDA programs. It offers dedicated interfaces that may be implemented to indicate that a certain class should be executed on the GPU. In contrast to Aparapi, it tries to automatically serialize the "relevant" data (that is, the complete relevant part of the object graph!) into a representation that is suitable for the GPU.

https://code.google.com/archive/p/java-gpu/ : A library for translating annotated Java code (with some limitations) into CUDA code, which is then compiled into a library that executes the code on the GPU. The Library was developed in the context of a PhD thesis, which contains profound background information about the translation process.

https://github.com/ochafik/ScalaCL : Scala bindings for OpenCL. Allows special Scala collections to be processed in parallel with OpenCL. The functions that are called on the elements of the collections can be usual Scala functions (with some limitations) which are then translated into OpenCL kernels.

Language extensions

http://www.ateji.com/px/index.html : A language extension for Java that allows parallel constructs (e.g. parallel for loops, OpenMP style) which are then executed on the GPU with OpenCL. Unfortunately, this very promising project is no longer maintained.

http://www.habanero.rice.edu/Publications.html (JCUDA) : A library that can translate special Java Code (called JCUDA code) into Java- and CUDA-C code, which can then be compiled and executed on the GPU. However, the library does not seem to be publicly available.

https://www2.informatik.uni-erlangen.de/EN/research/JavaOpenMP/index.html : Java language extension for for OpenMP constructs, with a CUDA backend

Java OpenCL/CUDA binding libraries

https://github.com/ochafik/JavaCL : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings

http://jogamp.org/jocl/www/ : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings

http://www.lwjgl.org/ : Java bindings for OpenCL: Auto-generated low-level bindings and object-oriented convenience classes

http://jocl.org/ : Java bindings for OpenCL: Low-level bindings that are a 1:1 mapping of the original OpenCL API

http://jcuda.org/ : Java bindings for CUDA: Low-level bindings that are a 1:1 mapping of the original CUDA API

Miscellaneous

http://sourceforge.net/projects/jopencl/ : Java bindings for OpenCL. Seem to be no longer maintained since 2010

http://www.hoopoe-cloud.com/ : Java bindings for CUDA. Seem to be no longer maintained


adding css file with jquery

Just my couple cents... sometimes it's good to be sure there are no any duplicates... so we have the next function in the utils library:

jQuery.loadCSS = function(url) {
    if (!$('link[href="' + url + '"]').length)
        $('head').append('<link rel="stylesheet" type="text/css" href="' + url + '">');
}

How to use:

$.loadCSS('css/style2.css');

Axios having CORS issue

CORS issue can be simply resolved by following this:

Create a new shortcut of Google Chrome(update browser installation path accordingly) with following value:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:\chrome\temp"

Bash command line and input limit

There is a buffer limit of something like 1024. The read will simply hang mid paste or input. To solve this use the -e option.

http://linuxcommand.org/lc3_man_pages/readh.html

-e use Readline to obtain the line in an interactive shell

Change your read to read -e and annoying line input hang goes away.

deleting folder from java

The javadoc for File.delete()

public boolean delete()

Deletes the file or directory denoted by this abstract pathname. If this pathname >denotes a directory, then the directory must be empty in order to be deleted.

So a folder has to be empty or deleting it will fail. Your code currently fills the folder list with the top most folder first, followed by its sub folders. Since you iterrate through the list in the same way it will try to delete the top most folder before deleting its subfolders, this will fail.

Changing these line

    for(String filePath : folderList) {
        File tempFile = new File(filePath);
        tempFile.delete();
    }

to this

    for(int i = folderList.size()-1;i>=0;i--) {
        File tempFile = new File(folderList.get(i));
        tempFile.delete();
    }

should cause your code to delete the sub folders first.

The delete operation also returns false when it fails, so you can check this value to do some error handling if necessary.

How to get a JavaScript object's class?

For Javascript Classes in ES6 you can use object.constructor. In the example class below the getClass() method returns the ES6 class as you would expect:

var Cat = class {

    meow() {

        console.log("meow!");

    }

    getClass() {

        return this.constructor;

    }

}

var fluffy = new Cat();

...

var AlsoCat = fluffy.getClass();
var ruffles = new AlsoCat();

ruffles.meow();    // "meow!"

If you instantiate the class from the getClass method make sure you wrap it in brackets e.g. ruffles = new ( fluffy.getClass() )( args... );

How can I replace a newline (\n) using sed?

tr '\n' ' ' 

is the command.

Simple and easy to use.

MySQL FULL JOIN?

MySQL lacks support for FULL OUTER JOIN.

So if you want to emulate a Full join on MySQL take a look here .

A commonly suggested workaround looks like this:

SELECT  t_13.value AS val13, t_17.value AS val17
FROM    t_13
LEFT JOIN
        t_17
ON      t_13.value = t_17.value
UNION ALL
SELECT  t_13.value AS val13, t_17.value AS val17
FROM    t_13
RIGHT JOIN
        t_17
ON      t_13.value = t_17.value
WHERE   t_13.value IS NULL
ORDER BY
        COALESCE(val13, val17)
LIMIT 30

Div Height in Percentage

There is the semicolon missing (;) after the "50%"

but you should also notice that the percentage of your div is connected to the div that contains it.

for instance:

<div id="wrapper">
  <div class="container">
   adsf
  </div>
</div>

#wrapper {
  height:100px;
}
.container
{
  width:80%;
  height:50%;
  background-color:#eee;
}

here the height of your .container will be 50px. it will be 50% of the 100px from the wrapper div.

if you have:

adsf

#wrapper {
  height:400px;
}
.container
{
  width:80%;
  height:50%;
  background-color:#eee;
}

then you .container will be 200px. 50% of the wrapper.

So you may want to look at the divs "wrapping" your ".container"...

Dataset - Vehicle make/model/year (free)

These guys have an API that will give the results. It's also free to use.

http://www.carqueryapi.com

Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.

"%%" and "%/%" for the remainder and the quotient

In R, you can assign your own operators using %[characters]%. A trivial example:

'%p%' <- function(x, y){x^2 + y}

2 %p% 3 # result: 7

While I agree with BlueTrin that %% is pretty standard, I have a suspicion %/% may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/% means do a special sort of division (integer division)

Regex pattern to match at least 1 number and 1 character in a string

If you need the digit to be at the end of any word, this worked for me:

/\b([a-zA-Z]+[0-9]+)\b/g
  • \b word boundary
  • [a-zA-Z] any letter
  • [0-9] any number
  • "+" unlimited search (show all results)

Android SQLite: Update Statement

You can try:

db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");

Or

ContentValues newValues = new ContentValues();
newValues.put("YOUR_COLUMN", "newValue");

db.update("YOUR_TABLE", newValues, "id=6", null);

Or

ContentValues newValues = new ContentValues();
newValues.put("YOUR_COLUMN", "newValue");

String[] args = new String[]{"user1", "user2"};
db.update("YOUR_TABLE", newValues, "name=? OR name=?", args);

How to keep console window open

Put a Console.Read() as the last line in your program. That will prevent it from closing until you press a key

static void Main(string[] args)
{
    StringAddString s = new StringAddString();
    Console.Read();            
}

Export/import jobs in Jenkins

Importing Jobs Manually: Alternate way

Upload the Jobs on to Git (Version Control) Basically upload config.xml of the Job.

If Linux Servers:

cd /var/lib/jenkins/jobs/<Job name> 
Download the config.xml from Git

Restart the Jenkins

Build the full path filename in Python

Just use os.path.join to join your path with the filename and extension. Use sys.argv to access arguments passed to the script when executing it:

#!/usr/bin/env python3
# coding: utf-8

# import netCDF4 as nc
import numpy as np
import numpy.ma as ma
import csv as csv

import os.path
import sys

basedir = '/data/reu_data/soil_moisture/'
suffix = 'nc'


def read_fid(filename):
    fid = nc.MFDataset(filename,'r')
    fid.close()
    return fid

def read_var(file, varname):
    fid = nc.Dataset(file, 'r')
    out = fid.variables[varname][:]
    fid.close()
    return out


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Please specify a year')

    else:
        filename = os.path.join(basedir, '.'.join((sys.argv[1], suffix)))
        time = read_var(ncf, 'time')
        lat = read_var(ncf, 'lat')
        lon = read_var(ncf, 'lon')
        soil = read_var(ncf, 'soilw')

Simply run the script like:

   # on windows-based systems
   python script.py year

   # on unix-based systems
   ./script.py year

SQL Server Express CREATE DATABASE permission denied in database 'master'

What login are you connecting to SQL Server as? You need to connect with a login that has sufficient privileges to create a database. Network Service is probably not good enough, unless you go into SQL Server and add them as a login with sufficient rights.

DOM element to corresponding vue.js component

  • this.$el - points to the root element of the component
  • this.$refs.<ref name> + <div ref="<ref name>" ... - points to nested element

use $el/$refs only after mounted() step of vue lifecycle

<template>
    <div>
        root element
        <div ref="childElement">child element</div>
    </div>
</template>

<script>
    export default {
        mounted() {
            let rootElement = this.$el;
            let childElement = this.$refs.childElement;

            console.log(rootElement);
            console.log(childElement);
        }
    }
</script>

<style scoped>
</style>

enter image description here

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

Here is a C function that handles positive OR negative integer OR fractional values for BOTH OPERANDS

#include <math.h>
float mod(float a, float N) {return a - N*floor(a/N);} //return in range [0, N)

This is surely the most elegant solution from a mathematical standpoint. However, I'm not sure if it is robust in handling integers. Sometimes floating point errors creep in when converting int -> fp -> int.

I am using this code for non-int s, and a separate function for int.

NOTE: need to trap N = 0!

Tester code:

#include <math.h>
#include <stdio.h>

float mod(float a, float N)
{
    float ret = a - N * floor (a / N);

    printf("%f.1 mod %f.1 = %f.1 \n", a, N, ret);

    return ret;
}

int main (char* argc, char** argv)
{
    printf ("fmodf(-10.2, 2.0) = %f.1  == FAIL! \n\n", fmodf(-10.2, 2.0));

    float x;
    x = mod(10.2f, 2.0f);
    x = mod(10.2f, -2.0f);
    x = mod(-10.2f, 2.0f);
    x = mod(-10.2f, -2.0f);

    return 0;
}

(Note: You can compile and run it straight out of CodePad: http://codepad.org/UOgEqAMA)

Output:

fmodf(-10.2, 2.0) = -0.20 == FAIL!

10.2 mod 2.0 = 0.2
10.2 mod -2.0 = -1.8
-10.2 mod 2.0 = 1.8
-10.2 mod -2.0 = -0.2

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

If your SQL Server is on one domain controller and you are trying to connect to it from another domain controller then you will get this error when

IntegratedSecurity = true;

This will happen even if you include a valid SQL Server username and password in your connection string as they will automatically be over-written with your windows login and password. Integrated security means simply - use your windows credentials for login verification to SQL Server. So, if you are logged in to a different domain controller then it will fail. In the case where you are on two different domain controllers then you have no choice but to use

IntegratedSecurity = false;

Now, when Integrated security is false SQL Server will use the SQL Server login and password provided in your connection string. For this to work, the SQL Server instance has to have its authentication mode configured to mixed mode, being, SQL Server and Windows Authentication mode.

To verify or change this setting in SQL Server you can open the SQL Server Management Studio and right-click on your server name and then select Properties. On the pop-up that appears select Security and you will see where to alter this setting if you need to.

Better way to represent array in java properties file

Actually all answers are wrong

Easy: foo.[0]filename

Correct way of looping through C++ arrays

you need to understand difference between std::array::size and sizeof() operator. if you want loop to array elements in conventional way then you could use std::array::size. this will return number of elements in array but if you keen to use C++11 then prefer below code

for(const string &text : texts)
    cout << "value of text: " << text << endl;

Can I get JSON to load into an OrderedDict?

The normally used load command will work if you specify the object_pairs_hook parameter:

import json
from  collections import OrderedDict
with open('foo.json', 'r') as fp:
    metrics_types = json.load(fp, object_pairs_hook=OrderedDict)

d3.select("#element") not working when code above the html element

just add your <script src="./custom.js"></script> before </bod> tag. that is supply time to d3.select(#chart) detect your #chart element in html body

Docker-Compose can't connect to Docker Daemon

in my case it is because the ubuntu permission,

  1. List item

check permission by

docker info 

if they print problem permission, enter image description here then use

sudo chmod -R 777 /var/run/docker.sock

Twitter Bootstrap dropdown menu

It actually requires inclusion of Twitter Bootstrap's dropdown.js

http://getbootstrap.com/2.3.2/components.html