Programs & Examples On #Batching

Hibernate Error executing DDL via JDBC Statement

I have got this error when trying to create JPA entity with the name "User" (in Postgres) that is reserved. So the way it is resolved is to change the table name by @Table annotation:

@Entity
@Table(name="users")
public class User {..}

Or change the table name manually.

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

It's pretty simple. You're trying to test the wrapper component generated by calling connect()(MyPlainComponent). That wrapper component expects to have access to a Redux store. Normally that store is available as context.store, because at the top of your component hierarchy you'd have a <Provider store={myStore} />. However, you're rendering your connected component by itself, with no store, so it's throwing an error.

You've got a few options:

  • Create a store and render a <Provider> around your connected component
  • Create a store and directly pass it in as <MyConnectedComponent store={store} /> , as the connected component will also accept "store" as a prop
  • Don't bother testing the connected component. Export the "plain", unconnected version, and test that instead. If you test your plain component and your mapStateToProps function, you can safely assume the connected version will work correctly.

You probably want to read through the "Testing" page in the Redux docs: https://redux.js.org/recipes/writing-tests.

edit:

After actually seeing that you posted source, and re-reading the error message, the real problem is not with the SportsTopPane component. The problem is that you're trying to "fully" render SportsTopPane, which also renders all of its children, rather than doing a "shallow" render like you were in the first case. The line searchComponent = <SportsDatabase sportsWholeFramework="desktop" />; is rendering a component that I assume is also connected, and therefore expects a store to be available in React's "context" feature.

At this point, you have two new options:

  • Only do "shallow" rendering of SportsTopPane, so that you're not forcing it to fully render its children
  • If you do want to do "deep" rendering of SportsTopPane, you'll need to provide a Redux store in context. I highly suggest you take a look at the Enzyme testing library, which lets you do exactly that. See http://airbnb.io/enzyme/docs/api/ReactWrapper/setContext.html for an example.

Overall, I would note that you might be trying to do too much in this one component and might want to consider breaking it into smaller pieces with less logic per component.

node and Error: EMFILE, too many open files

You're reading too many files. Node reads files asynchronously, it'll be reading all files at once. So you're probably reading the 10240 limit.

See if this works:

var fs = require('fs')
var events = require('events')
var util = require('util')
var path = require('path')

var FsPool = module.exports = function(dir) {
    events.EventEmitter.call(this)
    this.dir = dir;
    this.files = [];
    this.active = [];
    this.threads = 1;
    this.on('run', this.runQuta.bind(this))
};
// So will act like an event emitter
util.inherits(FsPool, events.EventEmitter);

FsPool.prototype.runQuta = function() {
    if(this.files.length === 0 && this.active.length === 0) {
        return this.emit('done');
    }
    if(this.active.length < this.threads) {
        var name = this.files.shift()

        this.active.push(name)
        var fileName = path.join(this.dir, name);
        var self = this;
        fs.stat(fileName, function(err, stats) {
            if(err)
                throw err;
            if(stats.isFile()) {
                fs.readFile(fileName, function(err, data) {
                    if(err)
                        throw err;
                    self.active.splice(self.active.indexOf(name), 1)
                    self.emit('file', name, data);
                    self.emit('run');

                });
            } else {
                self.active.splice(self.active.indexOf(name), 1)
                self.emit('dir', name);
                self.emit('run');
            }
        });
    }
    return this
};
FsPool.prototype.init = function() {
    var dir = this.dir;
    var self = this;
    fs.readdir(dir, function(err, files) {
        if(err)
            throw err;
        self.files = files
        self.emit('run');
    })
    return this
};
var fsPool = new FsPool(__dirname)

fsPool.on('file', function(fileName, fileData) {
    console.log('file name: ' + fileName)
    console.log('file data: ', fileData.toString('utf8'))

})
fsPool.on('dir', function(dirName) {
    console.log('dir name: ' + dirName)

})
fsPool.on('done', function() {
    console.log('done')
});
fsPool.init()

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

For update() and saveOrUpdate() methods, id generator value should be there in the database. For the save() method, id generator is not required.

Efficient way to do batch INSERTS with JDBC

You can use this rewriteBatchedStatements parameter to make the batch insert even faster.

you can read here about the param: MySQL and JDBC with rewriteBatchedStatements=true

proper hibernate annotation for byte[]

i fixed My issue by adding the annotation of @Lob which will create the byte[] in oracle as blob , but this annotation will create the field as oid which not work properly , To make byte[] created as bytea i made customer Dialect for postgres as below

Public class PostgreSQLDialectCustom extends PostgreSQL82Dialect {
    public PostgreSQLDialectCustom() {
        System.out.println("Init PostgreSQLDialectCustom");
        registerColumnType( Types.BLOB, "bytea" );

      }

    @Override
    public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
    if (sqlTypeDescriptor.getSqlType() == java.sql.Types.BLOB) {
      return BinaryTypeDescriptor.INSTANCE;
    }
    return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
  }
 }

Also need to override parameter for the Dialect

spring.jpa.properties.hibernate.dialect=com.ntg.common.DBCompatibilityHelper.PostgreSQLDialectCustom

more hint can be found her : https://dzone.com/articles/postgres-and-oracle

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You can find your sample code completely here: http://www.java2s.com/Code/Java/Hibernate/OneToManyMappingbasedonSet.htm

Have a look and check the differences. specially the even_id in :

<set name="attendees" cascade="all">
    <key column="event_id"/>
    <one-to-many class="Attendee"/>
</set> 

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

This happened if you change something in data set using native sql query but persisted object for same data set is present in session cache. Use session.evict(yourObject);

Send file using POST from a Python script

Looks like python requests does not handle extremely large multi-part files.

The documentation recommends you look into requests-toolbelt.

Here's the pertinent page from their documentation.

How to check if an email address exists without sending an email?

"Can you tell if an email customer / user enters is correct & exists?"

Actually these are two separate things. It might exist but might not be correct.

Sometimes you have to take the user inputs at the face value. There are many ways to defeat the system otherwise.

Post parameter is always null

Try creating a class to serve as the data model, then send a JSON object with properties matching the properties of your data model class. (Note: I have tested this and it works with the newest MVC 4 RC 2012 that I just downloaded today).

public HttpResponseMessage Post(ValueModel model)
{
    return Request.CreateResponse<string>(HttpStatusCode.OK, "Value Recieved: " + model.Value);
}

public class ValueModel
{
    public string Value { get; set; }
}

The below JSON object is sent in HTTP-POST body, content-type is application/json

{ "value": "In MVC4 Beta you could map to simple types like string, but testing with RC 2012 I have only been able to map to DataModels and only JSON (application/json) and url-encoded (application/x-www-form-urlencoded body formats have worked. XML is not working for some reason" }

I believe the reason why you have to create a data model class is because simple values are assumed to be from the url parameters, and a single complex value is assumed to be from the body. They do have the [FromBody] and [FromUrl] attributes, but using [FromBody] string value still did not work for me. Seems like they are still working out a lot of bugs so I'm sure this will change in the future.

Edit: Got XML to work in the body. The default XML serializer was changed to DataContractSerializer instead of XmlSerializer. Putting the following line in my Global.asax file fixed this issue (reference)

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

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

The location of jfxrt.jar in Oracle Java 7 is:

<JRE_HOME>/lib/jfxrt.jar

The location of jfxrt.jar in Oracle Java 8 is:

<JRE_HOME>/lib/ext/jfxrt.jar

The <JRE_HOME> will depend on where you installed the Oracle Java and may differ between Linux distributions and installations.

jfxrt.jar is not in the Linux OpenJDK 7 (which is what you are using).


An open source package which provides JavaFX 8 for Debian based systems such as Ubuntu is available. To install this package it is necessary to install both the Debian OpenJDK 8 package and the Debian OpenJFX package. I don't run Debian, so I'm not sure where the Debian OpenJFX package installs jfxrt.jar.


Use Oracle Java 8.

With Oracle Java 8, JavaFX is both included in the JDK and is on the default classpath. This means that JavaFX classes will automatically be found both by the compiler during the build and by the runtime when your users use your application. So using Oracle Java 8 is currently the best solution to your issue.

OpenJDK for Java 8 could include JavaFX (as JavaFX for Java 8 is now open source), but it will depend on the OpenJDK package assemblers as to whether they choose to include JavaFX 8 with their distributions. I hope they do, as it should help remove the confusion you experienced in your question and it also provides a great deal more functionality in OpenJDK.

My understanding is that although JavaFX has been included with the standard JDK since version JDK 7u6

Yes, but only the Oracle JDK.

The JavaFX version bundled with Java 7 was not completely open source so it could not be included in the OpenJDK (which is what you are using).

In you need to use Java 7 instead of Java 8, you could download the Oracle JDK for Java 7 and use that. Then JavaFX will be included with Java 7. Due to the way Oracle configured Java 7, JavaFX won't be on the classpath. If you use Java 7, you will need to add it to your classpath and use appropriate JavaFX packaging tools to allow your users to run your application. Some tools such as e(fx)clipse and NetBeans JavaFX project type will take care of classpath issues and packaging tasks for you.

Test class with a new() call in it with Mockito

I happened to be in a particular situation where my usecase resembled the one of Mureinik but I ended-up using the solution of Tomasz Nurkiewicz.

Here is how:

class TestedClass extends AARRGGHH {
    public LoginContext login(String user, String password) {
        LoginContext lc = new LoginContext("login", callbackHandler);
        lc.doThis();
        lc.doThat();
        return lc;
    }
}

Now, PowerMockRunner failed to initialize TestedClass because it extends AARRGGHH, which in turn does more contextual initialization... You see where this path was leading me: I would have needed to mock on several layers. Clearly a HUGE smell.

I found a nice hack with minimal refactoring of TestedClass: I created a small method

LoginContext initLoginContext(String login, CallbackHandler callbackHandler) {
    new lc = new LoginContext(login, callbackHandler);
}

The scope of this method is necessarily package.

Then your test stub will look like:

LoginContext lcMock = mock(LoginContext.class)
TestedClass testClass = spy(new TestedClass(withAllNeededArgs))
doReturn(lcMock)
    .when(testClass)
    .initLoginContext("login", callbackHandler)

and the trick is done...

Read a file line by line with VB.NET

Like this... I used it to read Chinese characters...

Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String

Do
   a = reader.ReadLine
   '
   ' Code here
   '
Loop Until a Is Nothing

reader.Close()

How to find Google's IP address?

nslookup google.com is the easiest way. Works on Linux and Windows.

If your issue is that your DNS server is not returning a response for google.com, use a different DNS server, such as a public one. For instance, you could do:

nslookup
>server 8.8.8.8
>google.com

For a more thorough solution to getting around annoying Internet filters, look into using Tor.

Assign null to a SqlParameter

            dynamic psd = DBNull.Value;

            if (schedule.pushScheduleDate > DateTime.MinValue)
            {
                psd = schedule.pushScheduleDate;
            }


            sql.DBController.RunGeneralStoredProcedureNonQuery("SchedulePush",
                     new string[] { "@PushScheduleDate"},
                     new object[] { psd }, 10, "PushCenter");

How to process each output line in a loop?

Often the order of the processing does not matter. GNU Parallel is made for this situation:

grep xyz abc.txt | parallel echo do stuff to {}

If you processing is more like:

grep xyz abc.txt | myprogram_reading_from_stdin

and myprogram is slow then you can run:

grep xyz abc.txt | parallel --pipe myprogram_reading_from_stdin

Redirect pages in JSP?

Hello there: If you need more control on where the link should redirect to, you could use this solution.

Ie. If the user is clicking in the CHECKOUT link, but you want to send him/her to checkout page if its registered(logged in) or registration page if he/she isn't.

You could use JSTL core LIKE:

<!--include the library-->
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<%--create a var to store link--%>
<core:set var="linkToRedirect">
  <%--test the condition you need--%>
  <core:choose>
    <core:when test="${USER IS REGISTER}">
      checkout.jsp
    </core:when>
    <core:otherwise>
      registration.jsp
    </core:otherwise>
  </core:choose>
</core:set>

EXPLAINING: is the same as...

 //pseudo code
 if(condition == true)
   set linkToRedirect = checkout.jsp
 else
   set linkToRedirect = registration.jsp

THEN: in simple HTML...

<a href="your.domain.com/${linkToRedirect}">CHECKOUT</a>

Finding all the subsets of a set

You dont have to mess with recursion and other complex algorithms. You can find all subsets using bit patterns (decimal to binary) of all numbers between 0 and 2^(N-1). Here N is cardinality or number-of-items in that set. The technique is explained here with an implementation and demo.

http://codeding.com/?article=12

How to hide a <option> in a <select> menu with CSS?

Late to the game, but most of these seem quite complicated.

Here's how I did it:

var originalSelect = $('#select-2').html();

// filter select-2 on select-1 change
$('#select-1').change(function (e) {

    var selected = $(this).val();

    // reset select ready for filtering
    $('#select-2').html(originalCourseSelect);

    if (selected) {
        // filter
        $('#select-2 option').not('.t' + selected).remove();
    }

});

markup of select-1:

<select id='select-1'>
<option value=''>Please select</option>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>

markup of select-2:

<select id='select-2'>
<option class='t1'>One</option>
<option class='t2'>Two</option>
<option>Always visible</option>
</select>

How to trigger a phone call when clicking a link in a web page on mobile phone

Clickable smartphone link code:

The following link can be used to make a clickable phone link. You can copy the code below and paste it into your webpage, then edit with your phone number. This code may not work on all phones but does work for iPhone, Droid / Android, and Blackberry.

<a href="tel:1-847-555-5555">1-847-555-5555</a>

Phone number links can be used with the dashes, as shown above, or without them as well as in the following example:

<a href="tel:18475555555">1-847-555-5555</a>

It is also possible to use any text in the link as long as the phone number is set up with the "tel:18475555555" as in this example:

<a href="tel:18475555555">Click Here To Call Support 1-847-555-5555</a>

Below is a clickable telephone hyperlink you can check out. In most non-phone browsers this link will give you a "The webpage cannot be displayed" error or nothing will happen.

NOTE: The iPhone Safari browser will automatically detect a phone number on a page and will convert the text into a call link without using any of the code on this page.

WTAI smartphone link code: The WTAI or "Wireless Telephony Application Interface" link code is shown below. This code is considered to be the correct mobile phone protocol and will work on smartphones like Droid, however, it may not work for Apple Safari on iPhone and the above code is recommended.

<a href="wtai://wp/mc;18475555555">Click Here To Call Support 1-847-555-5555</a> 

pandas loc vs. iloc vs. at vs. iat?

loc: only work on index
iloc: work on position
at: get scalar values. It's a very fast loc
iat: Get scalar values. It's a very fast iloc

Also,

at and iat are meant to access a scalar, that is, a single element in the dataframe, while loc and iloc are ments to access several elements at the same time, potentially to perform vectorized operations.

http://pyciencia.blogspot.com/2015/05/obtener-y-filtrar-datos-de-un-dataframe.html

How to use HTTP GET in PowerShell?

In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:

$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"

R - argument is of length zero in if statement

I spent an entire day bashing my head against this, the solution turned out to be simple..

R isn't zero-index.

Every programming language that I've used before has it's data start at 0, R starts at 1. The result is an off-by-one error but in the opposite direction of the usual. going out of bounds on a data structure returns null and comparing null in an if statement gives the argument is of length zero error. The confusion started because the dataset doesn't contain any null, and starting at position [0] like any other pgramming language turned out to be out of bounds.

Perhaps starting at 1 makes more sense to people with no programming experience (the target market for R?) but for a programmer is a real head scratcher if you're unaware of this.

How to assign the output of a Bash command to a variable?

In this specific case, note that bash has a variable called PWD that contains the current directory: $PWD is equivalent to `pwd`. (So do other shells, this is a standard feature.) So you can write your script like this:

#!/bin/bash
until [ "$PWD" = "/" ]; do
  echo "$PWD"
  ls && cd .. && ls 
done

Note the use of double quotes around the variable references. They are necessary if the variable (here, the current directory) contains whitespace or wildcards (\[?*), because the shell splits the result of variable expansions into words and performs globbing on these words. Always double-quote variable expansions "$foo" and command substitutions "$(foo)" (unless you specifically know you have not to).

In the general case, as other answers have mentioned already:

  • You can't use whitespace around the equal sign in an assignment: var=value, not var = value
  • The $ means “take the value of this variable”, so you don't use it when assigning: var=value, not $var=value.

fast way to copy formatting in excel

Just use the NumberFormat property after the Value property: In this example the Ranges are defined using variables called ColLetter and SheetRow and this comes from a for-next loop using the integer i, but they might be ordinary defined ranges of course.

TransferSheet.Range(ColLetter & SheetRow).Value = Range(ColLetter & i).Value TransferSheet.Range(ColLetter & SheetRow).NumberFormat = Range(ColLetter & i).NumberFormat

Delete files or folder recursively on Windows CMD

RMDIR path_to_folder /S

ex. RMDIR "C:\tmp" /S

Note that you'll be prompted if you're really going to delete the "C:\tmp" folder. Combining it with /Q switch will remove the folder silently (ex. RMDIR "C:\tmp" /S /Q)

Pandas join issue: columns overlap but no suffix specified

The .join() function is using the index of the passed as argument dataset, so you should use set_index or use .merge function instead.

Please find the two examples that should work in your case:

join_df = LS_sgo.join(MSU_pi.set_index('mukey'), on='mukey', how='left')

or

join_df = df_a.merge(df_b, on='mukey', how='left')

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

The basic idea of using ICollection is a provide an interface to readonly-access to some finite amount of data. In fact you have a ICollection.Count property. IEnumerable is more suitable for some chain of the data where you read till some logical point, some condition esplicitly specified by consumer or till the end of the enumeration.

What does the CSS rule "clear: both" do?

When you want one element placed at the bottom other element you use this code in CSS. It is used for floats.

If you float content you can float left or right... so in a common layout you might have a left nav, a content div and a footer.

To ensure the footer stays below both of these floats (if you have floated left and right) then you put the footer as clear: both.

This way it will stay below both floats.

(If you are only clearing left then you only really need to clear: left;.)

Go through this tutorial:

React : difference between <Route exact path="/" /> and <Route path="/" />

Take a look here: https://reacttraining.com/react-router/core/api/Route/exact-bool

exact: bool

When true, will only match if the path matches the location.pathname exactly.

**path**    **location.pathname**   **exact**   **matches?**

/one        /one/two                true        no
/one        /one/two                false       yes

Remove title in Toolbar in appcompat-v7

The correct way to hide/change the Toolbar Title is this:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);

This because when you call setSupportActionBar(toolbar);, then the getSupportActionBar() will be responsible of handling everything to the Action Bar, not the toolbar object.

See here

Android device chooser - My device seems offline

Go to DDMS->Devices->Click on View Menu Down arrow on right side -> select "reset adb" option it will work

In Android Studio: open the Android Device Monitor (Tools->Android) and click on the arrow on the 'Devices' tab to reset the adb

reset adb

PHPExcel Make first row bold

$objPHPExcel->getActiveSheet()->getStyle("A1:".$objPHPExcel->getActiveSheet()->getHighestDataColumn()."1")->getFont()->setBold(true);

I found this to be a working solution, you can replace the two instances of 1 with the row number. The HighestDataColumn function returns for example C or Z, it gives you the last/highest column that's in the sheet containing any data. There is also getHighestColumn(), that one would include cells that are empty but have styling or are part of other functionality.

How do you read a file into a list in Python?

The pythonic way to read a file and put every lines in a list:

from __future__ import with_statement #for python 2.5
with open('C:/path/numbers.txt', 'r') as f:
    lines = f.readlines()

Then, assuming that each lines contains a number,

numbers =[int(e.strip()) for e in lines]

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

The problem has been resolved by running the following in elevated command prompt:

command :

cd C:\Windows\System32\
regtlib msdatsrc.tlb

or

cd C:\Windows\SysWOW64\
regtlib msdatsrc.tlb

I hope this helps.

How to insert TIMESTAMP into my MySQL table?

The DEFAULT value of a column in MySql is used only if it isn't provided a value for that column. So if you

INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', '', '$comments')

You are not using the DEFAULT value for the column date, but you are providing an empty string, so you get an error, because you can't store an empty string in a DATETIME column. The same thing apply if you use NULL, because again NULL is a value. However, if you remove the column from the list of the column you are inserting, MySql will use the DEFAULT value specified for that column (or the data type default one)

Is it possible to import a whole directory in sass using @import?

If you are using Sass in a Rails project, the sass-rails gem, https://github.com/rails/sass-rails, features glob importing.

@import "foo/*"     // import all the files in the foo folder
@import "bar/**/*"  // import all the files in the bar tree

To answer the concern in another answer "If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity."

Some would argue that organizing your files into directories can REDUCE complexity.

My organization's project is a rather complex app. There are 119 Sass files in 17 directories. These correspond roughly to our views and are mainly used for adjustments, with the heavy lifting being handled by our custom framework. To me, a few lines of imported directories is a tad less complex than 119 lines of imported filenames.

To address load order, we place files that need to load first – mixins, variables, etc. — in an early-loading directory. Otherwise, load order is and should be irrelevant... if we are doing things properly.

Modulo operator with negative values

a % b

in c++ default:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

in python:

-7 % 3 => 2
7 % -3 => -2

in c++ to python:

(b + (a%b)) % b

How to create a link to another PHP page

Just try like this:

HTML in PHP :

$link_address1 = 'index.php';
echo "<a href='".$link_address1."'>Index Page</a>";

$link_address2 = 'page2.php';
echo "<a href='".$link_address2."'>Page 2</a>";

Easiest way

$link_address1 = 'index.php';
echo "<a href='$link_address1'>Index Page</a>";

$link_address2 = 'page2.php';
echo "<a href='$link_address2'>Page 2</a>";

How to refresh an access form

No, it is like I want to run Form_Load of Form A,if it is possible

-- Varun Mahajan

The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:

Form B:

Sub RunFormALoad()
   Forms!FormA.ToDoOnLoad
End Sub

Form A:

Public Sub Form_Load()
    ToDoOnLoad
End Sub    

Sub ToDoOnLoad()
    txtText = "Hi"
End Sub

Remove files from Git commit

Now that Apple has non-cosensually updated all MacOS users to zsh, the correct answer doesn't work anymore.

git reset --soft HEAD^
zsh: no matches found: HEAD^

You can prevent the shell from treating the ^ as a special character by single quoting it.

git reset --soft 'HEAD^'

Alternatively you can disable this behavior in your shell. by updating your ~/.zshrc with

unsetopt nomatch

Get div to take up 100% body height, minus fixed-height header and footer

The new, modern way to do this is to calculate the vertical height by subtracting the height of both the header and the footer from the vertical-height of the viewport.

//CSS
header { 
  height: 50px;
}
footer { 
  height: 50px;
}
#content { 
  height: calc(100vh - 50px - 50px);
}

ORA-12560: TNS:protocol adaptor error

I have solved the problem the easy way. My oracle was running just fine in the past. After I installed MS SQL Server was when I noticed this problem. I just uninstalled MS SQL Server on my machine then the problem was gone. Make sure you restart your computer after that. Now I can connect to Oracle database through SQLPlus again. My guess is that there's some conflict between the two. Hope this helps.

How can change width of dropdown list?

This:

<select style="width: XXXpx;">

XXX = Any Number

Works great in Google Chrome v70.0.3538.110

How to dynamically create columns in datatable and assign values to it?

If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

  • Create Data table object.
  • Add columns into that data table object.
  • Add Rows with values into the object.

For eg.

Dim dt As New DataTable

dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))

dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")

How to create many labels and textboxes dynamically depending on the value of an integer variable?

You can try this:

int cleft = 1;
intaleft = 1;
private void button2_Click(object sender, EventArgs e) 
{
     TextBox txt = new TextBox();
     this.Controls.Add(txt);
     txt.Top = cleft * 40;
     txt.Size = new Size(200, 16);
     txt.Left = 150;
     cleft = cleft + 1;
     Label lbl = new Label();
     this.Controls.Add(lbl);
     lbl.Top = aleft * 40;
     lbl.Size = new Size(100, 16);
     lbl.ForeColor = Color.Blue;
     lbl.Text = "BoxNo/CardNo";
     lbl.Left = 70;
     aleft = aleft + 1;
     return;
}
private void btd_Click(object sender, EventArgs e)
{ 
    //Here you Delete Text Box One By One(int ix for Text Box)
    for (int ix = this.Controls.Count - 2; ix >= 0; ix--)
    //Here you Delete Lable One By One(int ix for Lable)
    for (int x = this.Controls.Count - 2; x >= 0; x--)
    {
        if (this.Controls[ix] is TextBox) 
        this.Controls[ix].Dispose();
        if (this.Controls[x] is Label) 
        this.Controls[x].Dispose();
        return;
    }
}

Fastest way to flatten / un-flatten nested JSON objects

You can try out the package jpflat.

It flattens, inflates, resolves promises, flattens arrays, has customizable path creation and customizable value serialization.

The reducers and serializers receive the whole path as an array of it's parts, so more complex operations can be done to the path instead of modifying a single key or changing the delimiter.

Json path is the default, hence "jp"flat.

https://www.npmjs.com/package/jpflat

let flatFoo = await require('jpflat').flatten(foo)

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

How to generate a number of most distinctive colors in R?

You can use colorRampPalette from base or RColorBrewer package:

With colorRampPalette, you can specify colours as follows:

colorRampPalette(c("red", "green"))(5)
# [1] "#FF0000" "#BF3F00" "#7F7F00" "#3FBF00" "#00FF00"

You can alternatively provide hex codes as well:

colorRampPalette(c("#3794bf", "#FFFFFF", "#df8640"))(5)
# [1] "#3794BF" "#9BC9DF" "#FFFFFF" "#EFC29F" "#DF8640"
# Note that the mid color is the mid value...

With RColorBrewer you could use colors from pre-existing palettes:

require(RColorBrewer)
brewer.pal(9, "Set1")
# [1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00" "#FFFF33" "#A65628" "#F781BF"
# [9] "#999999"

Look at RColorBrewer package for other available palettes. Hope this helps.

Mapping a JDBC ResultSet to an object

Use Statement Fetch Size , if you are retrieving more number of records. like this.

Statement statement = connection.createStatement();
statement.setFetchSize(1000); 

Apart from that i dont see an issue with the way you are doing in terms of performance

In terms of Neat. Always use seperate method delegate to map the resultset to POJO object. which can be reused later in the same class

like

private User mapResultSet(ResultSet rs){
     User user = new User();
     // Map Results
     return user;
}

If you have the same name for both columnName and object's fieldName , you could also write reflection utility to load the records back to POJO. and use MetaData to read the columnNames . but for small scale projects using reflection is not an problem. but as i said before there is nothing wrong with the way you are doing.

How can I export data to an Excel file

I used interop to open Excel and to modify the column widths once the data was done. If you use interop to spit the data into a new Excel workbook (if this is what you want), it will be terribly slow. Instead, I generated a .CSV, then opened the .CSV in Excel. This has its own problems, but I've found this the quickest method.

First, convert the .CSV:

// Convert array data into CSV format.
// Modified from http://csharphelper.com/blog/2018/04/write-a-csv-file-from-an-array-in-c/.
private string GetCSV(List<string> Headers, List<List<double>> Data)
{
    // Get the bounds.
    var rows = Data[0].Count;
    var cols = Data.Count;
    var row = 0;

    // Convert the array into a CSV string.
    StringBuilder sb = new StringBuilder();

    // Add the first field in this row.
    sb.Append(Headers[0]);

    // Add the other fields in this row separated by commas.
    for (int col = 1; col < cols; col++)
        sb.Append("," + Headers[col]);

    // Move to the next line.
    sb.AppendLine();

    for (row = 0; row < rows; row++)
    {
        // Add the first field in this row.
        sb.Append(Data[0][row]);

        // Add the other fields in this row separated by commas.
        for (int col = 1; col < cols; col++)
            sb.Append("," + Data[col][row]);

        // Move to the next line.
        sb.AppendLine();
    }

    // Return the CSV format string.
    return sb.ToString();
}

Then, export it to Excel:

public void ExportToExcel()
{
    // Initialize app and pop Excel on the screen.
    var excelApp = new Excel.Application { Visible = true };

    // I use unix time to give the files a unique name that's almost somewhat useful.
    DateTime dateTime = DateTime.UtcNow;
    long unixTime = ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
    var path = @"C:\Users\my\path\here + unixTime + ".csv";

    var csv = GetCSV();
    File.WriteAllText(path, csv);

    // Create a new workbook and get its active sheet.
    excelApp.Workbooks.Open(path);

    var workSheet = (Excel.Worksheet)excelApp.ActiveSheet;

    // iterate over each value and throw it in the chart
    for (var column = 0; column < Data.Count; column++)
    {
        ((Excel.Range)workSheet.Columns[column + 1]).AutoFit();
    }

    currentSheet = workSheet;
}

You'll have to install some stuff, too...

  1. Right click on the solution from solution explorer and select "Manage NuGet Packages." - add Microsoft.Office.Interop.Excel

  2. It might actually work right now if you created the project the way interop wants you to. If it still doesn't work, I had to create a new project in a different category. Under New > Project, select Visual C# > Windows Desktop > Console App. Otherwise, the interop tools won't work.

In case I forgot anything, here's my 'using' statements:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;

How to configure Docker port mapping to use Nginx as an upstream proxy?

Using docker links, you can link the upstream container to the nginx container. An added feature is that docker manages the host file, which means you'll be able to refer to the linked container using a name rather than the potentially random ip.

How to show an alert box in PHP?

Try this:

Define a funciton:

<?php
function phpAlert($msg) {
    echo '<script type="text/javascript">alert("' . $msg . '")</script>';
}
?>

Call it like this:

<?php phpAlert(   "Hello world!\\n\\nPHP has got an Alert Box"   );  ?>

Java/Groovy - simple date reformatting

oldDate is not in the format of the SimpleDateFormat you are using to parse it.

Try this format: dd-MMM-yyyy - It matches what you're trying to parse.

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

In my case I had two issues...

1) no listener at all because of running app from another entry file and this run script was deleted from package.json "scripts"

enter image description here

2) Case sensitive problem with 'Sequelize' instead of 'sequelize'

enter image description here

Stretch horizontal ul to fit width of div

This is the easiest way to do it: http://jsfiddle.net/thirtydot/jwJBd/

(or with table-layout: fixed for even width distribution: http://jsfiddle.net/thirtydot/jwJBd/59/)

This won't work in IE7.

#horizontal-style {
    display: table;
    width: 100%;
    /*table-layout: fixed;*/
}
#horizontal-style li {
    display: table-cell;
}
#horizontal-style a {
    display: block;
    border: 1px solid red;
    text-align: center;
    margin: 0 5px;
    background: #999;
}

Old answer before your edit: http://jsfiddle.net/thirtydot/DsqWr/

Apple Mach-O Linker Error when compiling for device

Changing "Build Active Architectures Only" to Yes in CordovaLib.xcodeproj -> Build Settings did the trick for me. earlier the app was running on simulator, but not on the device.

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

The supplied link has a very simply example of the n + 1 problem. If you apply it to Hibernate it's basically talking about the same thing. When you query for an object, the entity is loaded but any associations (unless configured otherwise) will be lazy loaded. Hence one query for the root objects and another query to load the associations for each of these. 100 objects returned means one initial query and then 100 additional queries to get the association for each, n + 1.

http://pramatr.com/2009/02/05/sql-n-1-selects-explained/

matplotlib get ylim values

 ymin, ymax = axes.get_ylim()

If you are using the plt api directly, you can avoid calls to axes altogether:

def myplotfunction(title, values, errors, plot_file_name):

    # plot errorbars
    indices = range(0, len(values))
    fig = plt.figure()
    plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')

    plt.ylim([-0.5, len(values) - 0.5])
    plt.xlabel('My x-axis title')
    plt.ylabel('My y-axis title')

    # title
    plt.title(title)

    # save as file
    plt.savefig(plot_file_name)

   # close figure
    plt.close(fig)

What CSS selector can be used to select the first div within another div

The MOST CORRECT answer to your question is...

#content > div:first-of-type { /* css */ }

This will apply the CSS to the first div that is a direct child of #content (which may or may not be the first child element of #content)

Another option:

#content > div:nth-of-type(1) { /* css */ }

Access multiple viewchildren using @viewchild

Use @ViewChildren from @angular/core to get a reference to the components

template

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>

component

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

l?i?v?e? ?d?e?m?o?

How does database indexing work?

Just think of Database Index as Index of a book.

If you have a book about dogs and you want to find an information about let's say, German Shepherds, you could of course flip through all the pages of the book and find what you are looking for - but this of course is time consuming and not very fast.

Another option is that, you could just go to the Index section of the book and then find what you are looking for by using the Name of the entity you are looking ( in this instance, German Shepherds) and also looking at the page number to quickly find what you are looking for.

In Database, the page number is referred to as a pointer which directs the database to the address on the disk where entity is located. Using the same German Shepherd analogy, we could have something like this (“German Shepherd”, 0x77129) where 0x77129 is the address on the disk where the row data for German Shepherd is stored.

In short, an index is a data structure that stores the values for a specific column in a table so as to speed up query search.

How to calculate percentage with a SQL statement

SELECT Grade, GradeCount / SUM(GradeCount)
FROM (SELECT Grade, COUNT(*) As GradeCount
      FROM myTable
      GROUP BY Grade) Grades

How do I set the selected item in a comboBox to match my string using C#?

Assuming that your combobox isn't databound you would need to find the object's index in the "items" collection on your form and then set the "selectedindex" property to the appropriate index.

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

Keep in mind that the IndexOf function may throw an argumentexception if the item isn't found.

Can you hide the controls of a YouTube embed without enabling autoplay?

use autoplay=0

autoplay takes 2 values.

Values: 0 or 1. Default is 0. Sets whether or not the initial video will autoplay when the player loads.

the important part

autoplay=0&showinfo=0&controls=0

Here is the demo for ur problem FIDDLE

How to create localhost database using mysql?

removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

curl: (35) SSL connect error

If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).

Django set field value after a form is initialized

Just change your Form.data field:

class ChooseProjectForm(forms.Form):
    project = forms.ModelChoiceField(queryset=project_qs)
    my_projects = forms.BooleanField()

    def __init__(self, *args, **kwargs):
        super(ChooseProjectForm, self).__init__(*args, **kwargs)
        self.data = self.data.copy()  # IMPORTANT, self.data is immutable
        # any condition:
        if self.data.get('my_projects'):
            my_projects = self.fields['project'].queryset.filter(my=True)
            self.fields['project'].queryset = my_projects
            self.fields['project'].initial = my_projects.first().pk
            self.fields['project'].empty_label = None  # disable "-----"
            self.data.update(project=my_projects.first().pk)  # Update Form data
            self.fields['project'].widget = forms.HiddenInput()  # Hide if you want

Upgrading PHP in XAMPP for Windows?

  1. Go to phpinfo(), press ctrl+f, and type thread to check the value.
  2. If it is enabled download the non thread safe version, otherwise download the thread safe version from here (zip).
  3. Extract it, and rename the folder to php.
  4. Go to your xampp folder rename the default php folder to something else.
  5. Copy the extracted (renamed php) folder in xampp directory.
  6. Copy the php.ini file from default/old php folder (That you renamed) and paste it into the new php folder.
  7. Restart xampp server and you're good to go.

How to delete selected text in the vi editor

Highlighting with your mouse only highlights characters on the terminal. VI doesn't really get this information, so you have to highlight differently.

Press 'v' to enter a select mode, and use arrow keys to move that around. To delete, press x. To select lines at a time, press shift+v. To select blocks, try ctrl+v. That's good for, say, inserting lots of comment lines in front of your code :).

I'm OK with VI, but it took me a while to improve. My work mates recommended me this cheat sheet. I keep a printout on the wall for those odd moments when I forget something.

Happy hacking!

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

Unix tail equivalent command in Windows Powershell

I took @hajamie's solution and wrapped it up into a slightly more convenient script wrapper.

I added an option to start from an offset before the end of the file, so you can use the tail-like functionality of reading a certain amount from the end of the file. Note the offset is in bytes, not lines.

There's also an option to continue waiting for more content.

Examples (assuming you save this as TailFile.ps1):

.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000
.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000 -Follow:$true
.\TailFile.ps1 -File .\path\to\myfile.log -Follow:$true

And here is the script itself...

param (
    [Parameter(Mandatory=$true,HelpMessage="Enter the path to a file to tail")][string]$File = "",
    [Parameter(Mandatory=$true,HelpMessage="Enter the number of bytes from the end of the file")][int]$InitialOffset = 10248,
    [Parameter(Mandatory=$false,HelpMessage="Continuing monitoring the file for new additions?")][boolean]$Follow = $false
)

$ci = get-childitem $File
$fullName = $ci.FullName

$reader = new-object System.IO.StreamReader(New-Object IO.FileStream($fullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [IO.FileShare]::ReadWrite))
#start at the end of the file
$lastMaxOffset = $reader.BaseStream.Length - $InitialOffset

while ($true)
{
    #if the file size has not changed, idle
    if ($reader.BaseStream.Length -ge $lastMaxOffset) {
        #seek to the last max offset
        $reader.BaseStream.Seek($lastMaxOffset, [System.IO.SeekOrigin]::Begin) | out-null

        #read out of the file until the EOF
        $line = ""
        while (($line = $reader.ReadLine()) -ne $null) {
            write-output $line
        }

        #update the last max offset
        $lastMaxOffset = $reader.BaseStream.Position
    }

    if($Follow){
        Start-Sleep -m 100
    } else {
        break;
    }
}

ImportError: No module named dateutil.parser

In Ubuntu 18.04 for Python2:

sudo apt-get install python-dateutil

How do I build JSON dynamically in javascript?

First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".

With that pedantry out of the way, I think that you're asking how to set object and array properties.

// make an empty object
var myObject = {};

// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];

// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';

myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';

myObject.not_a_list = '11';

That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.

Redirect HTTP to HTTPS on default virtual host without ServerName

Both works fine. But according to the Apache docs you should avoid using mod_rewrite for simple redirections, and use Redirect instead. So according to them, you should preferably do:

<VirtualHost *:80>
    ServerName www.example.com
    Redirect / https://www.example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
</VirtualHost>

The first / after Redirect is the url, the second part is where it should be redirected.

You can also use it to redirect URLs to a subdomain: Redirect /one/ http://one.example.com/

Should URL be case sensitive?

For websites hosted in a Linux server, URL is case sensitive. http://www.google.com/about and http://www.google.com/About will be redirected to different locations. While in a Windows Server, URL is case-insensitive, as in naming a FOLDER and will be redirected to same location.

Why do table names in SQL Server start with "dbo"?

If you are using Sql Server Management Studio, you can create your own schema by browsing to Databases - Your Database - Security - Schemas.

To create one using a script is as easy as (for example):

CREATE SCHEMA [EnterSchemaNameHere] AUTHORIZATION [dbo]

You can use them to logically group your tables, for example by creating a schema for "Financial" information and another for "Personal" data. Your tables would then display as:

Financial.BankAccounts Financial.Transactions Personal.Address

Rather than using the default schema of dbo.

Why are my PowerShell scripts not running?

Also it's worth knowing that you may need to include .\ in front of the script name. For example:

.\scriptname.ps1

A valid provisioning profile for this executable was not found for debug mode

Changing the provisioning profile to automatic then running prompted Xcode to "fix" the issue. I then changed back to my original provisioning profile and everything worked fine.

Deserialize Java 8 LocalDateTime with JacksonMapper

The date time you're passing is not a iso local date time format.

Change to

@Column(name = "start_date")
@DateTimeFormat(iso = DateTimeFormatter.ISO_LOCAL_DATE_TIME)
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startDate;

and pass date string in the format '2011-12-03T10:15:30'.

But if you still want to pass your custom format, use just have to specify the right formatter.

Change to

@Column(name = "start_date")
@DateTimeFormat(iso = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startDate;

I think your problem is the @DateTimeFormat has no effect at all. As the jackson is doing the deseralization and it doesnt know anything about spring annotation and I dont see spring scanning this annotation in the deserialization context.

Alternatively, you can try setting the formatter while registering the java time module.

LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);

Here is the test case with the deseralizer which works fine. May be try to get rid of that DateTimeFormat annotation altogether.

@RunWith(JUnit4.class)
public class JacksonLocalDateTimeTest {

    private ObjectMapper objectMapper;

    @Before
    public void init() {
        JavaTimeModule module = new JavaTimeModule();
        LocalDateTimeDeserializer localDateTimeDeserializer =  new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
        objectMapper = Jackson2ObjectMapperBuilder.json()
                .modules(module)
                .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .build();
    }

    @Test
    public void test() throws IOException {
        final String json = "{ \"date\": \"2016-11-08 12:00\" }";
        final JsonType instance = objectMapper.readValue(json, JsonType.class);

        assertEquals(LocalDateTime.parse("2016-11-08 12:00",DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") ), instance.getDate());
    }
}


class JsonType {
    private LocalDateTime date;

    public LocalDateTime getDate() {
        return date;
    }

    public void setDate(LocalDateTime date) {
        this.date = date;
    }
}

Make a negative number positive

if(arr[i]<0)

Math.abs(arr[i]);  //1st way (taking absolute value)

arr[i]=-(arr[i]); //2nd way (taking -ve of -ve no. yields a +ve no.)

arr[i]= ~(arr[i]-1);   //3rd way (taking negation)

Remove last 3 characters of string or number in javascript

Here is an approach using str.slice(0, -n). Where n is the number of characters you want to truncate.

_x000D_
_x000D_
var str = 1437203995000;_x000D_
str = str.toString();_x000D_
console.log("Original data: ",str);_x000D_
str = str.slice(0, -3);_x000D_
str = parseInt(str);_x000D_
console.log("After truncate: ",str);
_x000D_
_x000D_
_x000D_

How to reload or re-render the entire page using AngularJS

For the record, to force angular to re-render the current page, you can use:

$route.reload();

According to AngularJS documentation:

Causes $route service to reload the current route even if $location hasn't changed.

As a result of that, ngView creates new scope, reinstantiates the controller.

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

lock_guard and unique_lock are pretty much the same thing; lock_guard is a restricted version with a limited interface.

A lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.

So you always use lock_guard, unless you need the capabilities of unique_lock. A condition_variable needs a unique_lock.

How to copy a string of std::string type in C++?

You shouldn't use strcpy() to copy a std::string, only use it for C-Style strings.

If you want to copy a to b then just use the = operator.

string a = "text";
string b = "image";
b = a;

Could not find a version that satisfies the requirement <package>

Use Command Prompt, and then select Run as administrator.

Upgrade the pip version

To upgrade PIP, type this command, and then press Enter:-

python.exe -m pip install --upgrade pip

Go Back to python path C:\Users\Jack\AppData\Local\Programs\Python\Python37\Scripts

Type jupyter notebook

You will be redirected to http://localhost:8888/undefined/tree - Jupyter Home Page

Hope it helps !!!!!!!!!!!

When restoring a backup, how do I disconnect all active connections?

This code worked for me, it kills all existing connections of a database. All you have to do is change the line Set @dbname = 'databaseName' so it has your database name.

Use Master
Go

Declare @dbname sysname

Set @dbname = 'databaseName'

Declare @spid int
Select @spid = min(spid) from master.dbo.sysprocesses
where dbid = db_id(@dbname)
While @spid Is Not Null
Begin
        Execute ('Kill ' + @spid)
        Select @spid = min(spid) from master.dbo.sysprocesses
        where dbid = db_id(@dbname) and spid > @spid
End

after this I was able to restore it

How to get current time and date in C++?

You can try the following cross-platform code to get current date/time:

#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>

// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
    // for more information about date/time format
    strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);

    return buf;
}

int main() {
    std::cout << "currentDateTime()=" << currentDateTime() << std::endl;
    getchar();  // wait for keyboard input
}

Output:

currentDateTime()=2012-05-06.21:47:59

Please visit here for more information about date/time format

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

Comparing strings, c++

.compare() returns an integer, which is a measure of the difference between the two strings.

  • A return value of 0 indicates that the two strings compare as equal.
  • A positive value means that the compared string is longer, or the first non-matching character is greater.
  • A negative value means that the compared string is shorter, or the first non-matching character is lower.

operator== simply returns a boolean, indicating whether the strings are equal or not.

If you don't need the extra detail, you may as well just use ==.

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

Make sure pom.xml exist in the directory, when using the mvn spring-boot:run command. No need to add any thing in the pom.xml file.

Accessing JSON object keys having spaces

The way to do this is via the bracket notation.

_x000D_
_x000D_
var test = {_x000D_
    "id": "109",_x000D_
    "No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
_x000D_
_x000D_

For more info read out here:

How to restrict the selectable date ranges in Bootstrap Datepicker?

The example above can be simplify a bit. Additionally you can put date manually from keyboard instead of selecting it via datepicker only. When clearing the value you need to handle also 'on clearDate' action to remove startDate/endDate boundary:

JS file:

$(".from_date").datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
}).on('changeDate', function (selected) {
    var startDate = new Date(selected.date.valueOf());
    $('.to_date').datepicker('setStartDate', startDate);
}).on('clearDate', function (selected) {
    $('.to_date').datepicker('setStartDate', null);
});

$(".to_date").datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
}).on('changeDate', function (selected) {
    var endDate = new Date(selected.date.valueOf());
    $('.from_date').datepicker('setEndDate', endDate);
}).on('clearDate', function (selected) {
    $('.from_date').datepicker('setEndDate', null);
});

HTML:

<input class="from_date" placeholder="Select start date" type="text" name="from_date">
<input class="to_date" placeholder="Select end date" type="text" name="to_date">

How to re-render flatlist?

Put variables that will be changed by your interaction at extraData

You can be creative.

For example if you are dealing with a changing list with checkboxes on them.

<FlatList
      data={this.state.data.items}
      extraData={this.state.data.items.length * (this.state.data.done.length + 1) }
      renderItem={({item}) => <View>  

onclick on a image to navigate to another page using Javascript

Because it makes these things so easy, you could consider using a JavaScript library like jQuery to do this:

<script>
    $(document).ready(function() {
        $('img.thumbnail').click(function() {
            window.location.href = this.id + '.html';
        });
    });
</script>

Basically, it attaches an onClick event to all images with class thumbnail to redirect to the corresponding HTML page (id + .html). Then you only need the images in your HTML (without the a elements), like this:

<img src="bottle.jpg" alt="bottle" class="thumbnail" id="bottle" />
<img src="glass.jpg" alt="glass" class="thumbnail" id="glass" />

(Deep) copying an array using jQuery

$.extend(true, [], [['a', ['c']], 'b'])

That should do it for you.

Make DateTimePicker work as TimePicker only in WinForms

A snippet out of the MSDN:

'The following code sample shows how to create a DateTimePicker that enables users to choose a time only.'

timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Time;
timePicker.ShowUpDown = true;

Multiple conditions in WHILE loop

You need to change || to && so that both conditions must be true to enter the loop.

while(myChar != 'n' && myChar != 'N')

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

Fully change package name including company domain

To rename the package name in Android studio, Click on the setting icon in the project section and untick the Compact empty Middle Packages, after that the package will split into multiple folder names, then right click on the folder you need to change the name, click on refactor-> Rename-> Type the name you want to change in -> Refactor -> Refactor Directory, then import R.java file in the whole project. Working for me.

IPython/Jupyter Problems saving notebook as PDF

For Ubuntu users, an answer can be found here. I also quote it:

The most probable cause, is that you have not installed the appropriate dependencies. Your Ubuntu system has to have some packages installed regarding conversion of LaTeX and XeTeX files, in order to save your notebook as PDF. You can install them by:

sudo apt-get install texlive texlive-xetex texlive-generic-extra texlive-generic-recommended pandoc

Also, nbconvert is another dependency that is usually automatically installed with jupyter. But you can install it just to be sure, while having your virtual environment activated:

pip install -U nbconvert

SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

I assume your column type is STRING (CHAR, VARCHAR, etc) and sorting procedure is sorting it as a string. What you need to do is to convert value into numeric value. How to do it will depend on SQL system you use.

How can I make a thumbnail <img> show a full size image when clicked?

That sort of functionality is going to require some Javascript, but it is probably possible just to use CSS (in browsers other than IE6&7).

Change <br> height using CSS

_x000D_
_x000D_
#biglinebreakid {_x000D_
  line-height: 450%;_x000D_
  // 9x the normal height of a line break!_x000D_
}_x000D_
.biglinebreakclass {_x000D_
  line-height: 1em;_x000D_
  // you could even use calc!_x000D_
}
_x000D_
This is a small line_x000D_
<br />_x000D_
break. Whereas, this is a BIG line_x000D_
<br />_x000D_
<br id="biglinebreakid" />_x000D_
break! You can use any CSS selectors you want for things like this line_x000D_
<br />_x000D_
<br class="biglinebreakclass" />_x000D_
break!
_x000D_
_x000D_
_x000D_

php resize image on upload

You can use Imagine library also. It uses GD and Imagick.

htaccess redirect to https://www

This is the best way I found for Proxy and not proxy users

RewriteEngine On

### START WWW & HTTPS

# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

### END WWW & HTTPS

PHPExcel - creating multiple sheets by iteration

Complementing the coment of @Mark Baker.
Do as follow:

$titles = array('title 1', 'title 2');
$sheet = 0;
foreach($array as $value){
    if($sheet > 0){
        $objPHPExcel->createSheet();
        $sheet = $objPHPExcel->setActiveSheetIndex($sheet);
        $sheet->setTitle("$value");
        //Do you want something more here
    }else{
        $objPHPExcel->setActiveSheetIndex(0)->setTitle("$value");
    }
    $sheet++;
}  

This worked for me. And hope it works for those who need! :)

How to access List elements

Tried list[:][0] to show all first member of each list inside list is not working. Result is unknowingly will same as list[0][:]

So i use list comprehension like this:

[i[0] for i in list] which return first element value for each list inside list.

Can typescript export a function?

If you are using this for Angular, then export a function via a named export. Such as:

function someFunc(){}

export { someFunc as someFuncName }

otherwise, Angular will complain that object is not a function.

Visual Studio: How to break on handled exceptions?

With a solution open, go to the Debug - Exceptions (Ctrl+D,E) menu option. From there you can choose to break on Thrown or User-unhandled exceptions.

EDIT: My instance is set up with the C# "profile" perhaps it isn't there for other profiles?

Perform Segue programmatically and pass parameters to the destination view

Old question but here's the code on how to do what you are asking. In this case I am passing data from a selected cell in a table view to another view controller.

in the .h file of the trget view:

@property(weak, nonatomic)  NSObject* dataModel;

in the .m file:

@synthesize dataModel;

dataModel can be string, int, or like in this case it's a model that contains many items

- (void)someMethod {
     [self performSegueWithIdentifier:@"loginMainSegue" sender:self];
 }

OR...

- (void)someMethod {
    UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeController"];
    [self.navigationController pushViewController: myController animated:YES];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"storyDetailsSegway"]) {
        UITableViewCell *cell = (UITableViewCell *) sender;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        NSDictionary *storiesDict =[topStories objectAtIndex:[indexPath row]];
        StoryModel *storyModel = [[StoryModel alloc] init];
        storyModel = storiesDict;
        StoryDetails *controller = (StoryDetails *)segue.destinationViewController;
        controller.dataModel= storyModel;
    }
}

Command output redirect to file and terminal

Yes, if you redirect the output, it won't appear on the console. Use tee.

ls 2>&1 | tee /tmp/ls.txt

Excel: replace part of cell's string value

You have a character = STQ8QGpaM4CU6149665!7084880820, and you have a another column = 7084880820.

If you want to get only this in excel using the formula: STQ8QGpaM4CU6149665!, use this:

=REPLACE(H11,SEARCH(J11,H11),LEN(J11),"")

H11 is an old character and for starting number use search option then for no of character needs to replace use len option then replace to new character. I am replacing this to blank.

Convert byte to string in Java

System.out.println(new String(new byte[]{ (byte)0x63 }, "US-ASCII"));

Note especially that converting bytes to Strings always involves an encoding. If you do not specify it, you'll be using the platform default encoding, which means the code can break when running in different environments.

How to select first child with jQuery?

As @Roko mentioned you can do this in multiple ways.

1.Using the jQuery first-child selector - SnoopCode

   $(document).ready(function(){
    $(".alldivs onediv:first-child").css("background-color","yellow");
        }
  1. Using jQuery eq Selector - SnoopCode

     $( "body" ).find( "onediv" ).eq(1).addClass( "red" );
    
  2. Using jQuery Id Selector - SnoopCode

       $(document).ready(function(){
         $("#div1").css("background-color: red;");
       });
    

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

Xcode 6 iPhone Simulator Application Support location

In Swift 4 or Swift 5 you can use NSHomeDirectory().

The easiest way in Xcode 10 (or Xcode 11) is to pause your app (like when it hits a breakpoint) and run this line in the debugger console:

po NSHomeDirectory()

po stands for print object and prints most things

How do I execute a file in Cygwin?

Apparently, gcc doesn't behave like the one described in The C Programming language, where it says that the command cc helloworld.c produces a file called a.out which can be run by typing a.out on the prompt.

A Unix hasn't behaved in that way by default (so you can just write the executable name without ./ at the front) in a long time. It's called a.exe, because else Windows won't execute it, as it gets file types from the extension.

Getting all selected checkboxes in an array

You could try something like this:

$('input[type="checkbox"]').change(function(){
       var checkedValue = $('input:checkbox:checked').map(function(){
                return this.value;
            }).get();         
            alert(checkedValue);   //display selected checkbox value     
 })

Here

$('input[type="checkbox"]').change(function() call when any checkbox checked or unchecked, after this
$('input:checkbox:checked').map(function()  looping on all checkbox,

Adding a JAR to an Eclipse Java library

As of Helios Service Release 2, there is no longer support for JAR files.You can add them, but Eclipse will not recognize them as libraries, therefore you can only "import" but can never use.

Python foreach equivalent

Sure. A for loop.

for f in pets:
    print f

How to display special characters in PHP

You can have a mix of PHP and HTML in your PHP files... just do something like this...

<?php
$string = htmlentities("Résumé");
?>

<html>
<head></head>
<body>
<p><?= $string ?></p>
</body>
</html>

That should output Résumé just how you want it to.

If you don't have short tags enabled, replace the <?= $string ?> with <?php echo $string; ?>

Object reference not set to an instance of an object.

I know this was posted about a year ago, but this is for users for future reference.

I came across similar issue. In my case (i will try to be brief, please do let me know if you would like more detail), i was trying to check if a string was empty or not (string is the subject of an email). It always returned the same error message no matter what i did. I knew i was doing it right but it still kept throwing the same error message. Then it dawned in me that, i was checking if the subject (string) of an email (instance/object), what if the email(instance) was already a null at the first place. How could i check for a subject of an email, if the email is already a null..i checked if the the email was empty, it worked fine.

while checking for the subject(string) i used IsNullorWhiteSpace(), IsNullOrEmpty() methods.

if (email == null)
{     
     break;    
}
else
{    
     // your code here    
}

Add a thousands separator to a total with Javascript or jQuery?

I know this is an uber old post and has good answers, BUT if anyone is interested, there is a jQuery plugin which simplifies number formatting (thousands formatting, number of decimal places, custom thousands separator, etc) by making an include and a simple call. Has lots of features and documentation is enough. It's called jQuery Number.

You just include it:

<script type="text/javascript" src="jquery/jquery.number.min.js"></script>

And then use it:

On an automatic formatting HTML input: $('input.number').number( true, 2 );

or

On a JS call: $.number( 5020.2364, 2 ); // Outputs: 5,020.24

Hopefully this helps someone.

Get current date, given a timezone in PHP?

Set the default time zone first and get the date then, the date will be in the time zone you specify :

<?php 
 date_default_timezone_set('America/New_York');
 $date= date('m-d-Y') ;
 ?>

http://php.net/manual/en/function.date-default-timezone-set.php

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

Update

This answer is, as I write this, nearly eight years old, and about five years stale. But it's still (as I write this) the "accepted" answer, because it answered the question when it was asked.

The newer answer, that applies to the newer Android Studio tools, can be found here: https://stackoverflow.com/a/35828035/62 -- it's a great answer with screen shots. If you're using Android Studio, ignore the Eclipse answer below.

Original Eclipse-based Answer

I was searching for the answer to this question, and was unsatisfied with the above answers. But then I found the answer, so here it is for future reference:

To summarize (and clarify), in Eclipse, go to "Debug Configurations". You can find that in the drop-down under the "debug" icon. Select "target", and select a preferred emulator target to launch. Then under "additional emulator command line options," add this:

-partition-size 1024

Then CLOSE the emulator (and remove any devices), and click the debug icon, which will launch the preferred emulator you selected. This is important: Eclipse needs to launch the debugger, not AVD.

That fixed the problem for me.

Query to list all stored procedures

As Mike stated, the best way is to use information_schema. As long as you're not in the master database, system stored procedures won't be returned.

SELECT * 
  FROM DatabaseName.INFORMATION_SCHEMA.ROUTINES
 WHERE ROUTINE_TYPE = 'PROCEDURE'

If for some reason you had non-system stored procedures in the master database, you could use the query (this will filter out MOST system stored procedures):

SELECT * 
  FROM [master].INFORMATION_SCHEMA.ROUTINES
 WHERE ROUTINE_TYPE = 'PROCEDURE' 
   AND LEFT(ROUTINE_NAME, 3) NOT IN ('sp_', 'xp_', 'ms_')

JQuery .on() method with multiple event handlers to one selector

Also, if you had multiple event handlers attached to the same selector executing the same function, you could use

$('table.planning_grid').on('mouseenter mouseleave', function() {
    //JS Code
});

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

I think the above answer posted by Jeremy Thompson is the correct one, but I don't have enough street cred to comment. Once I updated nuget and powershellget, Install-Module was available for me.

Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force 
Install-PackageProvider -Name Powershellget -Force

What is interesting is that the version numbers returned by get-packageprovider didn't change after the update.

Git error on git pull (unable to update local ref)

What worked for me was:

git config --global fetch.prune true

Now it keeps on running prune automatically.

How to change xampp localhost to another folder ( outside xampp folder)?

@Hooman: actually with the latest versions of Xampp you don't need to know where the configuration or log files are; in the Control panel you have log and config buttons for each tool (php, mysql, tomcat...) and clicking them offers to open all the relevant file (you can even change the default editing application with the general Config button at the top right). Well done for whoever designed it!

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

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

How to delete a module in Android Studio

The most reliable way I have found to do this it to go to project structure and remove it from dependencies and remove it from your setting.gradle file.

It will appear as if it is fully deleted at his point but it is not. If you try to re add the module it will say that it already exist in the project.

The final step is to go to the location of your project using file explorer etc and delete the module.

This work 100% of the time on studio 1.3.1

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

If you want to allow Html tags only for few textbox in mvc

You can do one thing

in controller

 [ValidateInput(false)]
public ActionResult CreateNewHtml()  //view
{
    return View();
}
[ValidateInput(false)]
[HttpPost]
public ActionResult CreateNewHtml(cbs obj)//view cbs is database class
{
    repo.AddHtml(obj);
    return View();
}

How to get everything after last slash in a URL?

One more (idio(ma)tic) way:

URL.split("/")[-1]

Pandas: Looking up the list of sheets in an excel file

This is the fastest way I have found, inspired by @divingTobi's answer. All The answers based on xlrd, openpyxl or pandas are slow for me, as they all load the whole file first.

from zipfile import ZipFile
from bs4 import BeautifulSoup  # you also need to install "lxml" for the XML parser

with ZipFile(file) as zipped_file:
    summary = zipped_file.open(r'xl/workbook.xml').read()
soup = BeautifulSoup(summary, "xml")
sheets = [sheet.get("name") for sheet in soup.find_all("sheet")]

Laravel Eloquent: Ordering results of all()

You could still use sortBy (at the collection level) instead of orderBy (at the query level) if you still want to use all() since it returns a collection of objects.

Ascending Order

$results = Project::all()->sortBy("name");

Descending Order

$results = Project::all()->sortByDesc("name");

Check out the documentation about Collections for more details.

https://laravel.com/docs/5.1/collections

Showing alert in angularjs when user leaves a page

As you've discovered above, you can use a combination of window.onbeforeunload and $locationChangeStart to message the user. In addition, you can utilize ngForm.$dirty to only message the user when they have made changes.

I've written an angularjs directive that you can apply to any form that will automatically watch for changes and message the user if they reload the page or navigate away. @see https://github.com/facultymatt/angular-unsavedChanges

Hopefully you find this directive useful!

Has Facebook sharer.php changed to no longer accept detailed parameters?

I review your url in use:

https://www.facebook.com/sharer/sharer.php?s=100&p[title]=EXAMPLE&p[summary]=EXAMPLE&p[url]=EXAMPLE&p[images][0]=EXAMPLE

and see this differences:

  1. The sharer URL not is same.
  2. The strings are in different order. ( Do not know if this affects ).

I use this URL string:

http://www.facebook.com/sharer.php?s=100&p[url]=http://www.example.com/&p[images][0]=/images/image.jpg&p[title]=Title&p[summary]=Summary

In the "title" and "summary" section, I use the php function urlencode(); like this:

<?php echo urlencode($detail->title); ?>

And working fine for me.

What does this GCC error "... relocation truncated to fit..." mean?

Remember to tackle error messages in order. In my case, the error above this one was "undefined reference", and I visually skipped over it to the more interesting "relocation truncated" error. In fact, my problem was an old library that was causing the "undefined reference" message. Once I fixed that, the "relocation truncated" went away also.

How to create a fixed sidebar layout with Bootstrap 4?

Updated 2020

Here's an updated answer for the latest Bootstrap 4.0.0. This version has classes that will help you create a sticky or fixed sidebar without the extra CSS....

Use sticky-top:

<div class="container">
    <div class="row py-3">
        <div class="col-3 order-2" id="sticky-sidebar">
            <div class="sticky-top">
                ...
            </div>
        </div>
        <div class="col" id="main">
            <h1>Main Area</h1>
            ...   
        </div>
    </div>
</div>

Demo: https://codeply.com/go/O9GMYBer4l

or, use position-fixed:

<div class="container-fluid">
    <div class="row">
        <div class="col-3 px-1 bg-dark position-fixed" id="sticky-sidebar">
            ...
        </div>
        <div class="col offset-3" id="main">
            <h1>Main Area</h1>
            ...
        </div>
    </div>
</div>

Demo: https://codeply.com/p/0Co95QlZsH

Also see:
Fixed and scrollable column in Bootstrap 4 flexbox
Bootstrap col fixed position
How to use CSS position sticky to keep a sidebar visible with Bootstrap 4
Create a responsive navbar sidebar "drawer" in Bootstrap 4?

Focusable EditText inside ListView

Just try this

android:windowSoftInputMode="adjustNothing"

in the

activity

section of your manifest. Yes, it adjusts nothings, which means the editText will stay where it is when IME is opening. But that's just an little inconvenience that still completely solves the problem of losing focus.

MongoDB SELECT COUNT GROUP BY

Additionally if you need to restrict the grouping you can use:

db.events.aggregate( 
    {$match: {province: "ON"}},
    {$group: {_id: "$date", number: {$sum: 1}}}  
)

Is there a Python equivalent to Ruby's string interpolation?

I've developed the interpy package, that enables string interpolation in Python.

Just install it via pip install interpy. And then, add the line # coding: interpy at the beginning of your files!

Example:

#!/usr/bin/env python
# coding: interpy

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n#{name}."

How to Upload Image file in Retrofit 2

Retrofit 2.0 solution

@Multipart
@POST(APIUtils.UPDATE_PROFILE_IMAGE_URL)
public Call<CommonResponse> requestUpdateImage(@PartMap Map<String, RequestBody> map);

and

    Map<String, RequestBody> params = new HashMap<>();

    params.put("newProfilePicture" + "\"; filename=\"" + FilenameUtils.getName(file.getAbsolutePath()), RequestBody.create(MediaType.parse("image/jpg"), file));



 Call<CommonResponse> call = request.requestUpdateImage(params);

you can use
image/jpg image/png image/gif

ngrok command not found

In shorts,ngrok should be in same directory in which you are running ngrok command.

How to avoid HTTP error 429 (Too Many Requests) python

Another workaround would be to spoof your IP using some sort of Public VPN or Tor network. This would be assuming the rate-limiting on the server at IP level.

There is a brief blog post demonstrating a way to use tor along with urllib2:

http://blog.flip-edesign.com/?p=119

TypeScript: correct way to do string equality?

If you know x and y are both strings, using === is not strictly necessary, but is still good practice.

Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string rather than an actual string, which may complicate things.

Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===. Just go with that.

How do I make an Event in the Usercontrol and have it handled in the Main Form?

For those looking to do this in VB, here's how I got mine to work with a checkbox.

Background: I was trying to make my own checkbox that is a slider/switch control. I've only included the relevant code for this question.

In User control MyCheckbox.ascx

<asp:CheckBox ID="checkbox" runat="server" AutoPostBack="true" />

In User control MyCheckbox.ascx.vb

Create an EventHandler (OnCheckChanged). When an event fires on the control (ID="checkbox") inside your usercontrol (MyCheckBox.ascx), then fire your EventHandler (OnCheckChanged).

Public Event OnCheckChanged As EventHandler

Private Sub checkbox_CheckedChanged(sender As Object, e As EventArgs) Handles checkbox.CheckedChanged
    RaiseEvent OnCheckChanged(Me, e)
End Sub

In Page MyPage.aspx

<uc:MyCheckbox runat="server" ID="myCheck" OnCheckChanged="myCheck_CheckChanged" />

Note: myCheck_CheckChanged didn't fire until I added the Handles clause below

In Page MyPage.aspx.vb

Protected Sub myCheck_CheckChanged (sender As Object, e As EventArgs) Handles scTransparentVoting.OnCheckChanged
    'Do some page logic here
End Sub

How to display a PDF via Android web browser without "downloading" first

String format = "https://drive.google.com/viewerng/viewer?embedded=true&url=%s";
String fullPath = String.format(Locale.ENGLISH, format, "PDF_URL_HERE");
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(fullPath));
startActivity(browserIntent);

what is numeric(18, 0) in sql server 2008 r2

The first value is the precision and the second is the scale, so 18,0 is essentially 18 digits with 0 digits after the decimal place. If you had 18,2 for example, you would have 18 digits, two of which would come after the decimal...

example of 18,2: 1234567890123456.12

There is no functional difference between numeric and decimal, other that the name and I think I recall that numeric came first, as in an earlier version.

And to answer, "can I add (-10) in that column?" - Yes, you can.

What is "String args[]"? parameter in main method Java

The String[] args parameter is an array of Strings passed as parameters when you are running your application through command line in the OS.

So, imagine you have compiled and packaged a myApp.jar Java application. You can run your app by double clicking it in the OS, of course, but you could also run it using command line way, like (in Linux, for example):

user@computer:~$ java -jar myApp.jar

When you call your application passing some parameters, like:

user@computer:~$ java -jar myApp.jar update notify

The java -jar command will pass your Strings update and notify to your public static void main() method.

You can then do something like:

System.out.println(args[0]); //Which will print 'update'
System.out.println(args[1]); //Which will print 'notify'

When to use single quotes, double quotes, and backticks in MySQL

The string literals in MySQL and PHP are the same.

A string is a sequence of bytes or characters, enclosed within either single quote (“'”) or double quote (“"”) characters.

So if your string contains single quotes, then you could use double quotes to quote the string, or if it contains double quotes, then you could use single quotes to quote the string. But if your string contains both single quotes and double quotes, you need to escape the one that used to quote the string.

Mostly, we use single quotes for an SQL string value, so we need to use double quotes for a PHP string.

$query = "INSERT INTO table (id, col1, col2) VALUES (NULL, 'val1', 'val2')";

And you could use a variable in PHP's double-quoted string:

$query = "INSERT INTO table (id, col1, col2) VALUES (NULL, '$val1', '$val2')";

But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)

How to disable copy/paste from/to EditText

Here is a hack to disable "paste" popup. You have to override EditText method:

@Override
public int getSelectionStart() {
    for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
        if (element.getMethodName().equals("canPaste")) {
            return -1;
        }
    }
    return super.getSelectionStart();
}

Similar can be done for the other actions.

Iterate over model instance field names and values in template

Below is mine, inspired by shacker's get_all_fields. It gets a dict of one model instance, if encounter relation field, then asign the field value a dict recursively.

def to_dict(obj, exclude=[]):
    """???? dict, ?????? model instance ??.
    """
    tree = {}
    for field in obj._meta.fields + obj._meta.many_to_many:
        if field.name in exclude or \
           '%s.%s' % (type(obj).__name__, field.name) in exclude:
            continue

        try :
            value = getattr(obj, field.name)
        except obj.DoesNotExist:
            value = None

        if type(field) in [ForeignKey, OneToOneField]:
            tree[field.name] = to_dict(value, exclude=exclude)
        elif isinstance(field, ManyToManyField):
            vs = []
            for v in value.all():
                vs.append(to_dict(v, exclude=exclude))
            tree[field.name] = vs
        elif isinstance(field, DateTimeField):
            tree[field.name] = str(value)
        elif isinstance(field, FileField):
            tree[field.name] = {'url': value.url}
        else:
            tree[field.name] = value

    return tree

This function is mainly used to dump a model instance to json data:

def to_json(self):
    tree = to_dict(self, exclude=('id', 'User.password'))
    return json.dumps(tree, ensure_ascii=False)

How can I select an element in a component template?

Angular 4+: Use renderer.selectRootElement with a CSS selector to access the element.

I've got a form that initially displays an email input. After the email is entered, the form will be expanded to allow them to continue adding information relating to their project. However, if they are not an existing client, the form will include an address section above the project information section.

As of now, the data entry portion has not been broken up into components, so the sections are managed with *ngIf directives. I need to set focus on the project notes field if they are an existing client, or the first name field if they are new.

I tried the solutions with no success. However, Update 3 in this answer gave me half of the eventual solution. The other half came from MatteoNY's response in this thread. The result is this:

import { NgZone, Renderer } from '@angular/core';

constructor(private ngZone: NgZone, private renderer: Renderer) {}

setFocus(selector: string): void {
    this.ngZone.runOutsideAngular(() => {
        setTimeout(() => {
            this.renderer.selectRootElement(selector).focus();
        }, 0);
    });
}

submitEmail(email: string): void {
    // Verify existence of customer
    ...
    if (this.newCustomer) {
        this.setFocus('#firstname');
    } else {
        this.setFocus('#description');
    }
}

Since the only thing I'm doing is setting the focus on an element, I don't need to concern myself with change detection, so I can actually run the call to renderer.selectRootElement outside of Angular. Because I need to give the new sections time to render, the element section is wrapped in a timeout to allow the rendering threads time to catch up before the element selection is attempted. Once all that is setup, I can simply call the element using basic CSS selectors.

I know this example dealt primarily with the focus event, but it's hard for me that this couldn't be used in other contexts.

UPDATE: Angular dropped support for Renderer in Angular 4 and removed it completely in Angular 9. This solution should not be impacted by the migration to Renderer2. Please refer to this link for additional information: Renderer migration to Renderer2

how to always round up to the next integer

This will also work:

c = (count - 1) / 10 + 1;

LINQ syntax where string value is not null or empty

This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.

The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.

Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)

Bash command to sum a column of numbers

If you have ruby installed

cat FileWithColumnOfNumbers.txt | xargs ruby -e "puts ARGV.map(&:to_i).inject(&:+)"

Initializing default values in a struct

An explicit default initialization can help:

struct foo {
    bool a {};
    bool b {};
    bool c {};
 } bar;

Behavior bool a {} is same as bool b = bool(); and return false.

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_

ResourceDictionary in a separate assembly

Resource-Only DLL is an option for you. But it is not required necessarily unless you want to modify resources without recompiling applications. Have just one common ResourceDictionary file is also an option. It depends how often you change resources and etc.

<ResourceDictionary Source="pack://application:,,,/
     <MyAssembly>;component/<FolderStructureInAssembly>/<ResourceFile.xaml>"/>

MyAssembly - Just assembly name without extension

FolderStructureInAssembly - If your resources are in a folde, specify folder structure

When you are doing this it's better to aware of siteOfOrigin as well.

WPF supports two authorities: application:/// and siteoforigin:///. The application:/// authority identifies application data files that are known at compile time, including resource and content files. The siteoforigin:/// authority identifies site of origin files. The scope of each authority is shown in the following figure.

enter image description here

Pass data from Activity to Service using an Intent

If you bind your service, you will get the Extra in onBind(Intent intent).

Activity:

 Intent intent = new Intent(this, LocationService.class);                                                                                     
 intent.putExtra("tour_name", mTourName);                    
 bindService(intent, mServiceConnection, BIND_AUTO_CREATE); 

Service:

@Override
public IBinder onBind(Intent intent) {
    mTourName = intent.getStringExtra("tour_name");
    return mBinder;
}

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

When you start it up it shows you. But I don't know if it is something you can do or not on your host. If you have access to the command line and can restart the service, you will get something like:

    2016-11-15T12:57:09.182-0500 I CONTROL  [initandlisten]
 MongoDB starting : pid=16448 port=27017 dbpath=C:\data\db\ 

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Can I use VARCHAR as the PRIMARY KEY?

It is ok for sure. With just few hundred of entries, it will be fast.

You can add an unique id as as primary key (int autoincrement) ans set your coupon_code as unique. So if you need to do request in other tables it's better to use int than varchar

Multiple "order by" in LINQ

Using non-lambda, query-syntax LINQ, you can do this:

var movies = from row in _db.Movies 
             orderby row.Category, row.Name
             select row;

[EDIT to address comment] To control the sort order, use the keywords ascending (which is the default and therefore not particularly useful) or descending, like so:

var movies = from row in _db.Movies 
             orderby row.Category descending, row.Name
             select row;

Radio Buttons "Checked" Attribute Not Working

also try this way

$('input:radio[name="name"][id="abcd'+no+'"]').attr("checked", "checked");

if there is <form /> tag then ("checked", true) otherwise ("checked", "checked")

Deserialize JSON array(or list) in C#

I was having the similar issue and solved by understanding the Classes in asp.net C#

I want to read following JSON string :

[
    {
        "resultList": [
            {
                "channelType": "",
                "duration": "2:29:30",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1204,
                "language": "Hindi",
                "name": "The Great Target",
                "productId": 1204,
                "productMasterId": 1203,
                "productMasterName": "The Great Target",
                "productName": "The Great Target",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2005",
                "showGoodName": "Movies ",
                "views": 8333
            },
            {
                "channelType": "",
                "duration": "2:30:30",
                "episodeno": 0,
                "genre": "Romance",
                "genreList": [
                    "Romance"
                ],
                "genres": [
                    {
                        "personName": "Romance"
                    }
                ],
                "id": 1144,
                "language": "Hindi",
                "name": "Mere Sapnon Ki Rani",
                "productId": 1144,
                "productMasterId": 1143,
                "productMasterName": "Mere Sapnon Ki Rani",
                "productName": "Mere Sapnon Ki Rani",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "1997",
                "showGoodName": "Movies ",
                "views": 6482
            },
            {
                "channelType": "",
                "duration": "2:34:07",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1520,
                "language": "Telugu",
                "name": "Satyameva Jayathe",
                "productId": 1520,
                "productMasterId": 1519,
                "productMasterName": "Satyameva Jayathe",
                "productName": "Satyameva Jayathe",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2004",
                "showGoodName": "Movies ",
                "views": 9910
            }
        ],
        "resultSize": 1171,
        "pageIndex": "1"
    }
]

My asp.net c# code looks like following

First, Class3.cs page created in APP_Code folder of Web application

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;

/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{

    public List<ListWrapper_Main> ResultList_Main { get; set; }

    public class ListWrapper_Main
    {
        public List<ListWrapper> ResultList { get; set; }

        public string resultSize { get; set; }
        public string pageIndex { get; set; }
    }

    public class ListWrapper
    {
        public string channelType { get; set; }
        public string duration { get; set; }
        public int episodeno { get; set; }
        public string genre { get; set; }
        public string[] genreList { get; set; }
        public List<genres_cls> genres { get; set; }
        public int id { get; set; }
        public string imageUrl { get; set; }
        //public string imageurl { get; set; }
        public string language { get; set; }
        public string name { get; set; }
        public int productId { get; set; }
        public int productMasterId { get; set; }
        public string productMasterName { get; set; }
        public string productName { get; set; }
        public int productTypeId { get; set; }
        public string productTypeName { get; set; }
        public decimal rating { get; set; }
        public string releaseYear { get; set; }
        //public string releaseyear { get; set; }
        public string showGoodName { get; set; }
        public string views { get; set; }
    }
    public class genres_cls
    {
        public string personName { get; set; }
    }

}

Then, Browser page that reads the string/JSON string listed above and displays/Deserialize the JSON objects and displays the data

JavaScriptSerializer ser = new JavaScriptSerializer();


        string final_sb = sb.ToString();

        List<Class3.ListWrapper_Main> movieInfos = ser.Deserialize<List<Class3.ListWrapper_Main>>(final_sb.ToString());

        foreach (var itemdetail in movieInfos)
        {

            foreach (var itemdetail2 in itemdetail.ResultList)
            {
                Response.Write("channelType=" + itemdetail2.channelType + "<br/>");
                Response.Write("duration=" + itemdetail2.duration + "<br/>");
                Response.Write("episodeno=" + itemdetail2.episodeno + "<br/>");
                Response.Write("genre=" + itemdetail2.genre + "<br/>");

                string[] genreList_arr = itemdetail2.genreList;
                for (int i = 0; i < genreList_arr.Length; i++)
                    Response.Write("genreList1=" + genreList_arr[i].ToString() + "<br>");

                foreach (var genres1 in itemdetail2.genres)
                {
                    Response.Write("genres1=" + genres1.personName + "<br>");
                }

                Response.Write("id=" + itemdetail2.id + "<br/>");
                Response.Write("imageUrl=" + itemdetail2.imageUrl + "<br/>");
                //Response.Write("imageurl=" + itemdetail2.imageurl + "<br/>");
                Response.Write("language=" + itemdetail2.language + "<br/>");
                Response.Write("name=" + itemdetail2.name + "<br/>");
                Response.Write("productId=" + itemdetail2.productId + "<br/>");
                Response.Write("productMasterId=" + itemdetail2.productMasterId + "<br/>");
                Response.Write("productMasterName=" + itemdetail2.productMasterName + "<br/>");
                Response.Write("productName=" + itemdetail2.productName + "<br/>");
                Response.Write("productTypeId=" + itemdetail2.productTypeId + "<br/>");
                Response.Write("productTypeName=" + itemdetail2.productTypeName + "<br/>");
                Response.Write("rating=" + itemdetail2.rating + "<br/>");
                Response.Write("releaseYear=" + itemdetail2.releaseYear + "<br/>");
                //Response.Write("releaseyear=" + itemdetail2.releaseyear + "<br/>");
                Response.Write("showGoodName=" + itemdetail2.showGoodName + "<br/>");
                Response.Write("views=" + itemdetail2.views + "<br/><br>");
                //Response.Write("resultSize" + itemdetail2.resultSize + "<br/>");
                //  Response.Write("pageIndex" + itemdetail2.pageIndex + "<br/>");


            }



            Response.Write("resultSize=" + itemdetail.resultSize + "<br/><br>");
            Response.Write("pageIndex=" + itemdetail.pageIndex + "<br/><br>");

        }

'sb' is the actual string, i.e. JSON string of data mentioned very first on top of this reply

This is basically - web application asp.net c# code....

N joy...

How do you tell if caps lock is on using JavaScript?

So I found this page and didn't really like the solutions I found so I figured one out and am offering it up to all of you. For me, it only matters if the caps lock is on if I'm typing letters. This code solved the problem for me. Its quick and easy and gives you a capsIsOn variable to reference whenever you need it.

_x000D_
_x000D_
let capsIsOn=false;_x000D_
let capsChecked=false;_x000D_
_x000D_
let capsCheck=(e)=>{_x000D_
    let letter=e.key;_x000D_
    if(letter.length===1 && letter.match(/[A-Za-z]/)){_x000D_
        if(letter!==letter.toLowerCase()){_x000D_
          capsIsOn=true;_x000D_
          console.log('caps is on');_x000D_
        }else{_x000D_
          console.log('caps is off');_x000D_
        }_x000D_
        capsChecked=true;_x000D_
        window.removeEventListener("keyup",capsCheck);_x000D_
    }else{_x000D_
      console.log("not a letter, not capsCheck was performed");_x000D_
    }_x000D_
_x000D_
}_x000D_
_x000D_
window.addEventListener("keyup",capsCheck);_x000D_
_x000D_
window.addEventListener("keyup",(e)=>{_x000D_
  if(capsChecked && e.keyCode===20){_x000D_
    capsIsOn=!capsIsOn;_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

UnicodeDecodeError, invalid continuation byte

This happened to me also, while i was reading text containing Hebrew from a .txt file.

I clicked: file -> save as and I saved this file as a UTF-8 encoding

Google Maps API - Get Coordinates of address

Althugh you asked for Google Maps API, I suggest an open source, working, legal, free and crowdsourced API by Open street maps

https://nominatim.openstreetmap.org/search?q=Mumbai&format=json

Here is the API documentation for reference.

Edit: It looks like there are discrepancies occasionally, at least in terms of postal codes, when compared to the Google Maps API, and the latter seems to be more accurate. This was the case when validating addresses in Canada with the Canada Post search service, however, it might be true for other countries too.

installation app blocked by play protect

Not the solution, but you can use debug key for signing release builds to avoid blocking the installation from Google Play Protect. It looks like Play Protect doesn't warn for builds signed with automatically generated debug.keystore.

Note that your debug builds are not unsigned, they are just signed with a debug key.

Of course, you cannot use the build for production distribution (Google Play, Amazon, etc.), but it's still worth for pre-production internal testing which requires a high-frequency feedback loop.

You can add a task to build release with debug.keystore by adding the configuration in build.gradle, something like:

android {
  buildTypes {
    // add after the `release` definition
    releaseDebugKey { initWith release }
  }

  signingConfigs {
    // use debug.keystore for releaseDebugKey builds
    releaseDebugKey { initWith debug }
  }
}

then execute ./gradlew assembleReleaseDebugKey to build a release build with debug key.

How do I remove a single file from the staging area (undo git add)?

I think you probably got confused with the concept of index, as @CB Bailey commented:

The staging area is the index.

You can simply consider staging directory and index as the same thing.
So, just like @Tim Henigan's answer, I guess:

you simply want to "undo" the git add that was done for that file.



Here is my answer:

Commonly, there are two ways to undo a stage operation, as other answers already mentioned:

git reset HEAD <file>

and

git rm --cached <file>

But what is the difference?

Assume the file has been staged and exists in working directory too, use git rm --cached <file> if you want to remove it from staging directory, and keep the file in working directory. But notice that this operation will not only remove the file from staging directory but also mark the file as deleted in staging directory, if you use

git status

after this operation, you will see this :

        deleted:    <file>

It's a record of removing the file from staging directory. If you don't want to keep that record and just simply want to undo a previous stage operation of a file, use git reset HEAD <file> instead.


-------- END OF ANSWER --------

PS: I have noticed some answers mentioned:

git checkout -- <file>

This command is for the situation when the file has been staged, but the file has been modified in working directory after it was staged, use this operation to restore the file in working directory from staging directory. In other words, after this operation, changes happen in your working directory, NOT your staging directory.

Cannot make a static reference to the non-static method fxn(int) from the type Two

Since the main method is static and the fxn() method is not, you can't call the method without first creating a Two object. So either you change the method to:

public static int fxn(int y) {
    y = 5;
    return y;
}

or change the code in main to:

Two two = new Two();
x = two.fxn(x);

Read more on static here in the Java Tutorials.

Getting only hour/minute of datetime

Try this:

String hourMinute = DateTime.Now.ToString("HH:mm");

Now you will get the time in hour:minute format.

How do I avoid the specification of the username and password at every git push?

All this arises because git does not provide an option in clone/pull/push/fetch commands to send the credentials through a pipe. Though it gives credential.helper, it stores on the file system or creates a daemon etc. Often, the credentials of GIT are system level ones and onus to keep them safe is on the application invoking the git commands. Very unsafe indeed.

Here is what I had to work around. 1. Git version (git --version) should be greater than or equal to 1.8.3.

GIT CLONE

For cloning, use "git clone URL" after changing the URL from the format, http://{myuser}@{my_repo_ip_address}/{myrepo_name.git} to http://{myuser}:{mypwd}@{my_repo_ip_address}/{myrepo_name.git}

Then purge the repository of the password as in the next section.

PURGING

Now, this would have gone and

  1. written the password in git remote origin. Type "git remote -v" to see the damage. Correct this by setting the remote origin URL without password. "git remote set_url origin http://{myuser}@{my_repo_ip_address}/{myrepo_name.git}"
  2. written the password in .git/logs in the repository. Replace all instances of pwd using a unix command like find .git/logs -exec sed -i 's/{my_url_with_pwd}//g' {} \; Here, {my_url_with_pwd} is the URL with password. Since the URL has forward slashes, it needs to be escaped by two backward slashes. For ex, for the URL http://kris:[email protected]/proj.git -> http:\\/\\/kris:[email protected]\\/proj.git

If your application is using Java to issue these commands, use ProcessBuilder instead of Runtime. If you must use Runtime, use getRunTime().exec which takes String array as arguments with /bin/bash and -c as arguments rather then the one which takes a single String as argument.

GIT FETCH/PULL/PUSH

  1. set password in the git remote url as : "git remote set_url origin http://{myuser}:{mypwd}@{my_repo_ip_address}/{myrepo_name.git}"
  2. Issue the command git fetch/push/pull. You will not then be prompted for the password.
  3. Do the purging as in the previous section. Do not miss it.

How to check whether a Storage item is set?

The shortest way is to use default value, if key is not in storage:

var sValue = localStorage['my.token'] || ''; /* for strings */
var iValue = localStorage['my.token'] || 0; /* for integers */

Inserting a value into all possible locations in a list

If l is your list and X is your value:

for i in range(len(l) + 1):
    print l[:i] + [X] + l[i:]

How to use multiple databases in Laravel

Actually, DB::connection('name')->select(..) doesnt work for me, because 'name' has to be in double quotes: "name"

Still, the select query is executed on my default connection. Still trying to figure out, how to convince Laravel to work the way it is intended: change the connection.

Edit: I figured it out. After debugging Laravels DatabaseManager it turned out my database.php (config file) (inside $this->app) was wrong. In the section "connections" I had stuff like "database" with values of the one i copied it from. In clear terms, instead of

env('DB_DATABASE', 'name')

I needed to place something like

'myNewName'

since all connections were listed with the same values for the database, username, password, etc. which of course makes little sense if I want to access at least another database name

Therefore, every time I wanted to select something from another database I always ended up in my default database

Python Checking a string's first and last character

When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

Run Java with the command-line option -Xmx, which sets the maximum size of the heap.

See here for details.

How to read single Excel cell value

It is better to use .Value2() instead of .Value(). This is faster and gives the exact value in the cell. For certain type of data, truncation can be observed when .Value() is used.

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

Flushing footer to bottom of the page, twitter bootstrap

The only one that worked for me!:

html {
  position: relative;
  min-height: 100%;
  padding-bottom:90px;
}
body {
  margin-bottom: 90px;
}
footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 90px;
}

login to remote using "mstsc /admin" with password

the command posted by Milad and Sandy did not work for me with mstsc. i had to add TERMSRV to the /generic switch. i found this information here: https://gist.github.com/jdforsythe/48a022ee22c8ec912b7e

cmdkey /generic:TERMSRV/<server> /user:<username> /pass:<password>

i could then use mstsc /v:<server> without getting prompted for the login.

Does IE9 support console.log, and is it a real function?

In Internet Explorer 9 (and 8), the console object is only exposed when the developer tools are opened for a particular tab. If you hide the developer tools window for that tab, the console object remains exposed for each page you navigate to. If you open a new tab, you must also open the developer tools for that tab in order for the console object to be exposed.

The console object is not part of any standard and is an extension to the Document Object Model. Like other DOM objects, it is considered a host object and is not required to inherit from Object, nor its methods from Function, like native ECMAScript functions and objects do. This is the reason apply and call are undefined on those methods. In IE 9, most DOM objects were improved to inherit from native ECMAScript types. As the developer tools are considered an extension to IE (albeit, a built-in extension), they clearly didn't receive the same improvements as the rest of the DOM.

For what it's worth, you can still use some Function.prototype methods on console methods with a little bind() magic:

var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"

How to override Bootstrap's Panel heading background color?

You can simply add an id attribute to the panel. Like this

<div class="panel-heading" id="mypanelId">Hello world </div>

Then in your custom CSS file:

#mypanelId{
    background-image: none;
    background: rgba(22, 20, 100, 0.8);
    color: white;
     }

Get Date in YYYYMMDD format in windows batch file

If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.

First of all, where you're going wrong is the offset.

It should look more like this...

set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%

If the date was Tue 12/02/2013 then it would display it as 2013/02/12.

To remove the slashes, the code would look more like

set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%

which would output 20130212

And a hint for doing it in the future, if mydate equals something like %date:~10,4%%date:~7,2% or the like, you probably forgot a tilde (~).

How could I use requests in asyncio?

Requests does not currently support asyncio and there are no plans to provide such support. It's likely that you could implement a custom "Transport Adapter" (as discussed here) that knows how to use asyncio.

If I find myself with some time it's something I might actually look into, but I can't promise anything.

Border for an Image view in Android?

ImageView in xml file

<ImageView
            android:id="@+id/myImage"
            android:layout_width="100dp"
            android:layout_height="100dp"

            android:padding="1dp"
            android:scaleType="centerCrop"
            android:cropToPadding="true"
            android:background="@drawable/border_image"

            android:src="@drawable/ic_launcher" />

save below code with the name of border_image.xml and it should be in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:angle="270"
        android:endColor="#ffffff"
        android:startColor="#ffffff" />

    <corners android:radius="0dp" />

    <stroke
        android:width="0.7dp"
        android:color="#b4b4b4" />
</shape>

if you want to give rounded corner to the border of image then you may change a line in border.xml file

<corners android:radius="4dp" />

how to bypass Access-Control-Allow-Origin?

Okay, but you all know that the * is a wildcard and allows cross site scripting from every domain?

You would like to send multiple Access-Control-Allow-Origin headers for every site that's allowed to - but unfortunately its officially not supported to send multiple Access-Control-Allow-Origin headers, or to put in multiple origins.

You can solve this by checking the origin, and sending back that one in the header, if it is allowed:

$origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = [
    'http://mysite1.com',
    'https://www.mysite2.com',
    'http://www.mysite2.com',
];

if (in_array($origin, $allowed_domains)) {
    header('Access-Control-Allow-Origin: ' . $origin);
}

Thats much safer. You might want to edit the matching and change it to a manual function with some regex, or something like that. At least this will only send back 1 header, and you will be sure its the one that the request came from. Please do note that all HTTP headers can be spoofed, but this header is for the client's protection. Don't protect your own data with those values. If you want to know more, read up a bit on CORS and CSRF.

Why is it safer?

Allowing access from other locations then your own trusted site allows for session highjacking. I'm going to go with a little example - image Facebook allows a wildcard origin - this means that you can make your own website somewhere, and make it fire AJAX calls (or open iframes) to facebook. This means you can grab the logged in info of the facebook of a visitor of your website. Even worse - you can script POST requests and post data on someone's facebook - just while they are browsing your website.

Be very cautious when using the ACAO headers!

How should I store GUID in MySQL tables?

if you have a char/varchar value formatted as the standard GUID, you can simply store it as BINARY(16) using the simple CAST(MyString AS BINARY16), without all those mind-boggling sequences of CONCAT + SUBSTR.

BINARY(16) fields are compared/sorted/indexed much faster than strings, and also take two times less space in the database

How do you revert to a specific tag in Git?

Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname to display the commit it points to.

In your case you have at least these two alternatives:

  1. Reset the current branch to specific tag:

    git reset --hard tagname
    
  2. Generate revert commit on top to get you to the state of the tag:

    git revert tag
    

This might introduce some conflicts if you have merge commits though.

How do I POST JSON data with cURL?

I know, a lot has been answered to this question but wanted to share where I had the issue of:

curl -X POST http://your-server-end-point -H "Content-Type: application/json" -d @path-of-your-json-file.json

See, I did everything right, Only one thing - "@" I missed before the JSON file path.

I found one relevant go-to document on internet - https://gist.github.com/subfuzion/08c5d85437d5d4f00e58

Hope that might help the few. thanks

Run exe file with parameters in a batch file

If you need to see the output of the execute, use CALL together with or instead of START.

Example:

CALL "C:\Program Files\Certain Directory\file.exe" -param PAUSE

This will run the file.exe and print back whatever it outputs, in the same command window. Remember the PAUSE after the call or else the window may close instantly.

What does the M stand for in C# Decimal literal notation?

From C# specifications:

var f = 0f; // float
var d = 0d; // double
var m = 0m; // decimal (money)
var u = 0u; // unsigned int
var l = 0l; // long
var ul = 0ul; // unsigned long

Note that you can use an uppercase or lowercase notation.

CSS background-image-opacity?

Try this trick .. use css shadow with (inset) option and make the deep 200px for example

Code:

box-shadow: inset 0px 0px 277px 3px #4c3f37;

.

Also for all browsers:

-moz-box-shadow: inset 0px 0px 47px 3px #4c3f37;
-webkit-box-shadow: inset 0px 0px 47px 3px #4c3f37;
box-shadow: inset 0px 0px 277px 3px #4c3f37;

and increase number to make fill your box :)

Enjoy!

How can I format a list to print each element on a separate line in python?

You can just use a simple loop: -

>>> mylist = ['10', '12', '14']
>>> for elem in mylist:
        print elem 

10
12
14

How to get name of calling function/method in PHP?

You can also use the info provided by a php exception, it's an elegant solution:


function GetCallingMethodName(){
    $e = new Exception();
    $trace = $e->getTrace();
    //position 0 would be the line that called this function so we ignore it
    $last_call = $trace[1];
    print_r($last_call);
}

function firstCall($a, $b){
    theCall($a, $b);
}

function theCall($a, $b){
    GetCallingMethodName();
}

firstCall('lucia', 'php');

And you get this... (voilà!)

Array
(
    [file] => /home/lufigueroa/Desktop/test.php
    [line] => 12
    [function] => theCall
    [args] => Array
        (
            [0] => lucia
            [1] => php
        )

)

Wait until all promises complete even if some rejected

Benjamin's answer offers a great abstraction for solving this issue, but I was hoping for a less abstracted solution. The explicit way to to resolve this issue is to simply call .catch on the internal promises, and return the error from their callback.

let a = new Promise((res, rej) => res('Resolved!')),
    b = new Promise((res, rej) => rej('Rejected!')),
    c = a.catch(e => { console.log('"a" failed.'); return e; }),
    d = b.catch(e => { console.log('"b" failed.'); return e; });

Promise.all([c, d])
  .then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
  .catch(err => console.log('Catch', err));

Promise.all([a.catch(e => e), b.catch(e => e)])
  .then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
  .catch(err => console.log('Catch', err));

Taking this one step further, you could write a generic catch handler that looks like this:

const catchHandler = error => ({ payload: error, resolved: false });

then you can do

> Promise.all([a, b].map(promise => promise.catch(catchHandler))
    .then(results => console.log(results))
    .catch(() => console.log('Promise.all failed'))
< [ 'Resolved!',  { payload: Promise, resolved: false } ]

The problem with this is that the caught values will have a different interface than the non-caught values, so to clean this up you might do something like:

const successHandler = result => ({ payload: result, resolved: true });

So now you can do this:

> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler))
    .then(results => console.log(results.filter(result => result.resolved))
    .catch(() => console.log('Promise.all failed'))
< [ 'Resolved!' ]

Then to keep it DRY, you get to Benjamin's answer:

const reflect = promise => promise
  .then(successHandler)
  .catch(catchHander)

where it now looks like

> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler))
    .then(results => console.log(results.filter(result => result.resolved))
    .catch(() => console.log('Promise.all failed'))
< [ 'Resolved!' ]

The benefits of the second solution are that its abstracted and DRY. The downside is you have more code, and you have to remember to reflect all your promises to make things consistent.

I would characterize my solution as explicit and KISS, but indeed less robust. The interface doesn't guarantee that you know exactly whether the promise succeeded or failed.

For example you might have this:

const a = Promise.resolve(new Error('Not beaking, just bad'));
const b = Promise.reject(new Error('This actually didnt work'));

This won't get caught by a.catch, so

> Promise.all([a, b].map(promise => promise.catch(e => e))
    .then(results => console.log(results))
< [ Error, Error ]

There's no way to tell which one was fatal and which was wasn't. If that's important then you're going to want to enforce and interface that tracks whether it was successful or not (which reflect does).

If you just want to handle errors gracefully, then you can just treat errors as undefined values:

> Promise.all([a.catch(() => undefined), b.catch(() => undefined)])
    .then((results) => console.log('Known values: ', results.filter(x => typeof x !== 'undefined')))
< [ 'Resolved!' ]

In my case, I don't need to know the error or how it failed--I just care whether I have the value or not. I'll let the function that generates the promise worry about logging the specific error.

const apiMethod = () => fetch()
  .catch(error => {
    console.log(error.message);
    throw error;
  });

That way, the rest of the application can ignore its error if it wants, and treat it as an undefined value if it wants.

I want my high level functions to fail safely and not worry about the details on why its dependencies failed, and I also prefer KISS to DRY when I have to make that tradeoff--which is ultimately why I opted to not use reflect.

Hive insert query like SQL

Yes we can use Insert query in hive.

hive> create table test (id int, name string);

INSERT: INSERT...VALUES is available starting in version 0.14.

hive> insert into table test values (1,'mytest');

This is going to work for insert. We have to use values keyword.

Note: User cannot insert data into a complex datatype column (array, map, struct, union) using the INSERT INTO...VALUES clause.

Disable ONLY_FULL_GROUP_BY

I'm using doctrine and I have added the driverOptions in my doctrine.local.php :

return array(
'doctrine' => array(
    'connection' => array(
        'orm_default' => array(
            'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
            'params' => array(
                'host' => 'localhost',
                'port' => '3306',
                'user' => 'myusr',
                'password' => 'mypwd',
                'dbname' => 'mydb',
                'driverOptions' => array(
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))"
                ),
            ),
        ),
    ),
));

In phpmyadmin the user needs SUPER activated in the privileges.