Not able to pip install pickle in python 3.6
$ pip install pickle5
import pickle5 as pickle
pb = pickle.PickleBuffer(b"foo")
data = pickle.dumps(pb, protocol=5)
assert pickle.loads(data) == b"foo"
This package backports all features and APIs added in the pickle module in Python 3.8.3, including the PEP 574 additions. It should work with Python 3.5, 3.6 and 3.7.
Basic usage is similar to the pickle module, except that the module to be imported is pickle5:
https://pypi.org/project/pickle5/
Pandas dataframe groupby plot
Simple plot,
you can use:
df.plot(x='Date',y='adj_close')
Or you can set the index to be Date
beforehand, then it's easy to plot the column you want:
df.set_index('Date', inplace=True)
df['adj_close'].plot()
If you want a chart with one series by ticker
on it
You need to groupby before:
df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)
If you want a chart with individual subplots:
grouped = df.groupby('ticker')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
Format y axis as percent
For those who are looking for the quick one-liner:
plt.gca().set_yticklabels(['{:.0f}%'.format(x*100) for x in plt.gca().get_yticks()])
Or if you are using Latex as the axis text formatter, you have to add one backslash '\'
plt.gca().set_yticklabels(['{:.0f}\%'.format(x*100) for x in plt.gca().get_yticks()])
Toolbar Navigation Hamburger Icon missing
You can try to make your own drawable for the hamburger icon like this.
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:fillColor="#ffffff"
android:pathData="M3,18h18v-2L3,16v2zM3,13h18v-2L3,11v2zM3,6v2h18L21,6L3,6z" />
</vector>
Then in your fragment/activity,
getSupportActionBar().setHomeAsUpIndicator(R.drawable.as_above);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
For other drawables, this might help: https://github.com/google/material-design-icons/blob/master/navigation/drawable-anydpi-v21/
Creating lowpass filter in SciPy - understanding methods and units
A few comments:
- The Nyquist frequency is half the sampling rate.
- You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.
- One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.
Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
Change grid interval and specify tick labels in Matplotlib
A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.
import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
fig, ax = plt.subplots(figsize=(10, 8))
# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)
# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))
# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')
Name [jdbc/mydb] is not bound in this Context
You need a ResourceLink in your META-INF/context.xml
file to make the global resource available to the web application.
<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
type="javax.sql.DataSource" />
Python handling socket.error: [Errno 104] Connection reset by peer
There is a way to catch the error directly in the except clause with ConnectionResetError, better to isolate the right error.
This example also catches the timeout.
from urllib.request import urlopen
from socket import timeout
url = "http://......"
try:
string = urlopen(url, timeout=5).read()
except ConnectionResetError:
print("==> ConnectionResetError")
pass
except timeout:
print("==> Timeout")
pass
select from one table, insert into another table oracle sql query
From the oracle documentation, the below query explains it better
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
You can read this link
Your query would be as follows
//just the concept
INSERT INTO quotedb
(COLUMN_NAMES) //seperated by comma
SELECT COLUMN_NAMES FROM tickerdb,quotedb WHERE quotedb.ticker = tickerdb.ticker
Note: Make sure the columns in insert and select are in right position as per your requirement
Hope this helps!
VBA paste range
This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:
'**
'Copies a table from one place to another
'TargetRange: where to put the new LayoutTable
'typee: If it is an Instalation Layout table(1) or Package Layout table(2)
'**
Sub CopyLayout(TargetRange As Range, typee As Integer)
Application.ScreenUpdating = False
Dim ncolumn As Integer
Dim nrow As Integer
SheetLayout.Activate
If (typee = 1) Then 'is installation
Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
ElseIf (typee = 2) Then 'is package
Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
End If
Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
If typee = 1 Then
nrow = SheetLayout.Range("installationlayout").Rows.Count
ncolumn = SheetLayout.Range("installationlayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
ElseIf typee = 2 Then
nrow = SheetLayout.Range("PackageLayout").Rows.Count
ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
End If
Range("A1").Select 'Deselect the created table
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
'**
'Receives the Pasted Table Range and rearranjes it's properties
'accordingly to the original CopiedTable
'typee: If it is an Instalation Layout table(1) or Package Layout table(2)
'**
Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
Dim R As Long, C As Long
For R = 1 To RowCount
PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
If R >= 2 And R < RowCount Then
PastedTable.Rows(R).Group 'Main group of the table
End If
If R = 2 Then
PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
ElseIf (R = 4 And typee = 1) Then
PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
End If
Next R
For C = 1 To ColumnCount
PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
Next C
End Function
Sub test ()
Call CopyLayout(Sheet2.Range("A18"), 2)
end sub
Getting data from Yahoo Finance
As from the answer from BrianC use the YQL console.
But after selecting the "Show Community Tables" go to the bottom of the tables list and expand yahoo where you find plenty of yahoo.finance tables:
Stock Quotes:
- yahoo.finance.quotes
- yahoo.finance.historicaldata
Fundamental analysis:
- yahoo.finance.keystats
- yahoo.finance.balancesheet
- yahoo.finance.incomestatement
- yahoo.finance.analystestimates
- yahoo.finance.dividendhistory
Technical analysis:
- yahoo.finance.historicaldata
- yahoo.finance.quotes
- yahoo.finance.quant
- yahoo.finance.option*
General financial information:
- yahoo.finance.industry
- yahoo.finance.sectors
- yahoo.finance.isin
- yahoo.finance.quoteslist
- yahoo.finance.xchange
2/Nov/2017: Yahoo finance has apparently killed this API, for more info and alternative resources see https://news.ycombinator.com/item?id=15616880
What does "|=" mean? (pipe equal operator)
|=
reads the same way as +=
.
notification.defaults |= Notification.DEFAULT_SOUND;
is the same as
notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;
where |
is the bit-wise OR operator.
All operators are referenced here.
A bit-wise operator is used because, as is frequent, those constants enable an int to carry flags.
If you look at those constants, you'll see that they're in powers of two :
public static final int DEFAULT_SOUND = 1;
public static final int DEFAULT_VIBRATE = 2; // is the same than 1<<1 or 10 in binary
public static final int DEFAULT_LIGHTS = 4; // is the same than 1<<2 or 100 in binary
So you can use bit-wise OR to add flags
int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // same as 001 | 010, producing 011
so
myFlags |= DEFAULT_LIGHTS;
simply means we add a flag.
And symmetrically, we test a flag is set using &
:
boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;
Matplotlib 2 Subplots, 1 Colorbar
This topic is well covered but I still would like to propose another approach in a slightly different philosophy.
It is a bit more complex to set-up but it allow (in my opinion) a bit more flexibility. For example, one can play with the respective ratios of each subplots / colorbar:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
# Define number of rows and columns you want in your figure
nrow = 2
ncol = 3
# Make a new figure
fig = plt.figure(constrained_layout=True)
# Design your figure properties
widths = [3,4,5,1]
gs = GridSpec(nrow, ncol + 1, figure=fig, width_ratios=widths)
# Fill your figure with desired plots
axes = []
for i in range(nrow):
for j in range(ncol):
axes.append(fig.add_subplot(gs[i, j]))
im = axes[-1].pcolormesh(np.random.random((10,10)))
# Shared colorbar
axes.append(fig.add_subplot(gs[:, ncol]))
fig.colorbar(im, cax=axes[-1])
plt.show()
Open application after clicking on Notification
See below code. I am using that and it is opening my HomeActivity.
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
Intent notificationIntent = new Intent(context, HomeActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
Importing xsd into wsdl
import vs. include
The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import
statement with an include
statement).
Another area of confusion is how to specify the location or path of the included .xsd
file: An XSD import statement has an optional attribute named schemaLocation
but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.
When you do chose to use an external .xsd
file for your WSDL, the schemaLocation
attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:
WSDL:
xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>
XSD:
<xsd:schema targetNamespace="urn:listing3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xmlbeans-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-sources-xmlbeans</id>
<phase>generate-sources</phase>
<goals>
<goal>xmlbeans</goal>
</goals>
</execution>
</executions>
<version>2.3.3</version>
<inherited>true</inherited>
<configuration>
<schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
</configuration>
</plugin>
You can read more on this in this great IBM article. It has typos such as xsd:import
instead of xs:import
but otherwise it's fine.
how to send an array in url request
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
@RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
Very Simple, Very Smooth, JavaScript Marquee
Why write custom jQuery code for Marquee... just use a plugin for jQuery - marquee() and use it like in the example below:
First include :
<script type='text/javascript' src='//cdn.jsdelivr.net/jquery.marquee/1.3.1/jquery.marquee.min.js'></script>
and then:
//proporcional speed counter (for responsive/fluid use)
var widths = $('.marquee').width()
var duration = widths * 7;
$('.marquee').marquee({
//speed in milliseconds of the marquee
duration: duration, // for responsive/fluid use
//duration: 8000, // for fixed container
//gap in pixels between the tickers
gap: $('.marquee').width(),
//time in milliseconds before the marquee will start animating
delayBeforeStart: 0,
//'left' or 'right'
direction: 'left',
//true or false - should the marquee be duplicated to show an effect of continues flow
duplicated: true
});
If you can make it simpler and better I dare you all people :). Don't make your life more difficult than it should be. More about this plugin and its functionalities at: http://aamirafridi.com/jquery/jquery-marquee-plugin
HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace
In Windows Vista and later the HTTP WCF service stuff would cause the exception you mentioned because a restricted account does not have right for that. That is the reason why it worked when you ran it as administrator.
Every sensible developer must use a RESTRICTED account rather than as an Administrator, yet many people go the wrong way and that is precisely why there are so many applications out there that DEMAND admin permissions when they are not really required. Working the lazy way results in lazy solutions. I hope you still work in a restricted account (my congratulations).
There is a tool out there (from 2008 or so) called NamespaceManagerTool if I remember correctly that is supposed to grant the restricted user permissions on these service URLs that you define for WCF. I haven't used that though...
Foreach value from POST from form
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need
How to get a complete list of ticker symbols from Yahoo Finance?
There is a nice C# wrapper for the Yahoo.Finance API at http://code.google.com/p/yahoo-finance-managed/ that will get you there. Unfortunately there is no direct way to download the ticker list but the following creates the list by iterating through the alphabetical groups:
AlphabeticIDIndexDownload dl1 = new AlphabeticIDIndexDownload();
dl1.Settings.TopIndex = null;
Response<AlphabeticIDIndexResult> resp1 = dl1.Download();
writeStream.WriteLine("Id|Isin|Name|Exchange|Type|Industry");
foreach (var alphabeticalIndex in resp1.Result.Items)
{
AlphabeticalTopIndex topIndex = (AlphabeticalTopIndex) alphabeticalIndex;
dl1.Settings.TopIndex = topIndex;
Response<AlphabeticIDIndexResult> resp2 = dl1.Download();
foreach (var index in resp2.Result.Items)
{
IDSearchDownload dl2 = new IDSearchDownload();
Response<IDSearchResult> resp3 = dl2.Download(index);
int i = 0;
foreach (var item in resp3.Result.Items)
{
writeStream.WriteLine(item.ID + "|" + item.ISIN + "|" + item.Name + "|" + item.Exchange + "|" + item.Type + "|" + item.Industry);
}
}
}
It gave me a list of about 75,000 securities in about 4 mins.
Start service in Android
startService(new Intent(this, MyService.class));
Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
...
<service
android:name=".MyService"
android:label="My Service" >
</service>
</application>
plot with custom text for x axis points
This worked for me. Each month on X axis
str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)
JTable won't show column headers
As said in previous answers the 'normal' way is to add it to a JScrollPane, but sometimes you don't want it to scroll (don't ask me when:)). Then you can add the TableHeader yourself. Like this:
JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable();
tablePanel.add(table, BorderLayout.CENTER);
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);
How to send parameters from a notification-click to an activity?
After doing some search i got solution from android developer guide
PendingIntent contentIntent ;
Intent intent = new Intent(this,TestActivity.class);
intent.putExtra("extra","Test");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ArticleDetailedActivity.class);
contentIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
To Get Intent extra value in Test Activity class you need to write following code :
Intent intent = getIntent();
String extra = intent.getStringExtra("extra") ;
Can I add a UNIQUE constraint to a PostgreSQL table, after it's already created?
If you had a table that already had a existing constraints based on lets say: name and lastname and you wanted to add one more unique constraint, you had to drop the entire constrain by:
ALTER TABLE your_table DROP CONSTRAINT constraint_name;
Make sure tha the new constraint you wanted to add is unique/ not null ( if its Microsoft Sql, it can contain only one null value) across all data on that table, and then you could re-create it.
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n);
C# How can I check if a URL exists/is valid?
This solution seems easy to follow:
public static bool isValidURL(string url) {
WebRequest webRequest = WebRequest.Create(url);
WebResponse webResponse;
try
{
webResponse = webRequest.GetResponse();
}
catch //If exception thrown then couldn't get response from address
{
return false ;
}
return true ;
}
How to delete and recreate from scratch an existing EF Code First database
Let me help in updating the answers here since new users will find it useful.
I believe the aim is to delete the database itself and recreate it using EF Code First approach.
1.Open your project in Visual Studio using the ".sln" extention.
2.Select Server Explorer( it is oftentimes on the left)
3.Select SQL Server Object Explorer.
4.The database you want to delete would be listed under any of the localDB. Right-Click it and select delete.
Javascript .querySelector find <div> by innerTEXT
Here's the XPath approach but with a minimum of XPath jargon.
Regular selection based on element attribute values (for comparison):
// for matching <element class="foo bar baz">...</element> by 'bar'
var things = document.querySelectorAll('[class*="bar"]');
for (var i = 0; i < things.length; i++) {
things[i].style.outline = '1px solid red';
}
XPath selection based on text within element.
// for matching <element>foo bar baz</element> by 'bar'
var things = document.evaluate('//*[contains(text(),"bar")]',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0; i < things.snapshotLength; i++) {
things.snapshotItem(i).style.outline = '1px solid red';
}
And here's with case-insensitivity since text is more volatile:
// for matching <element>foo bar baz</element> by 'bar' case-insensitively
var things = document.evaluate('//*[contains(translate(text(),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"),"bar")]',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0; i < things.snapshotLength; i++) {
things.snapshotItem(i).style.outline = '1px solid red';
}
Example use of "continue" statement in Python?
It is not absolutely necessary since it can be done with IFs but it's more readable and also less expensive in run time.
I use it in order to skip an iteration in a loop if the data does not meet some requirements:
# List of times at which git commits were done.
# Formatted in hour, minutes in tuples.
# Note the last one has some fantasy.
commit_times = [(8,20), (9,30), (11, 45), (15, 50), (17, 45), (27, 132)]
for time in commit_times:
hour = time[0]
minutes = time[1]
# If the hour is not between 0 and 24
# and the minutes not between 0 and 59 then we know something is wrong.
# Then we don't want to use this value,
# we skip directly to the next iteration in the loop.
if not (0 <= hour <= 24 and 0 <= minutes <= 59):
continue
# From here you know the time format in the tuples is reliable.
# Apply some logic based on time.
print("Someone commited at {h}:{m}".format(h=hour, m=minutes))
Output:
Someone commited at 8:20
Someone commited at 9:30
Someone commited at 11:45
Someone commited at 15:50
Someone commited at 17:45
As you can see, the wrong value did not make it after the continue
statement.
Concat all strings inside a List<string> using LINQ
This is for a string array:
string.Join(delimiter, array);
This is for a List<string>:
string.Join(delimiter, list.ToArray());
And this is for a list of custom objects:
string.Join(delimiter, list.Select(i => i.Boo).ToArray());
Threading pool similar to the multiprocessing Pool?
The overhead of creating the new processes is minimal, especially when it's just 4 of them. I doubt this is a performance hot spot of your application. Keep it simple, optimize where you have to and where profiling results point to.
C# IPAddress from string
You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.
Have you tried using System.Net.IPAddress just in case?
System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1"); //127.0.0.1 as an example
The docs on Microsoft's site have a complete example which works fine on my machine.
How to Publish Web with msbuild?
You must set your environments
- < WebSite name>
- < domain>
and reference my blog.(sorry post was Korean)
- http://xyz37.blog.me/50124665657
http://blog.naver.com/PostSearchList.nhn?SearchText=webdeploy&blogId=xyz37&x=25&y=7
@ECHO OFF
:: http://stackoverflow.com/questions/5598668/valid-parameters-for-msdeploy-via-msbuild
::-DeployOnBuild -True
:: -False
::
::-DeployTarget -MsDeployPublish
:: -Package
::
::-Configuration -Name of a valid solution configuration
::
::-CreatePackageOnPublish -True
:: -False
::
::-DeployIisAppPath -<Web Site Name>/<Folder>
::
::-MsDeployServiceUrl -Location of MSDeploy installation you want to use
::
::-MsDeployPublishMethod -WMSVC (Web Management Service)
:: -RemoteAgent
::
::-AllowUntrustedCertificate (used with self-signed SSL certificates) -True
:: -False
::
::-UserName
::-Password
SETLOCAL
IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v2.0.50727" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v2.0.50727"
IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v3.5" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v3.5"
IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v4.0.30319" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v4.0.30319"
SET targetFile=<web site fullPath ie. .\trunk\WebServer\WebServer.csproj
SET configuration=Release
SET msDeployServiceUrl=https://<domain>:8172/MsDeploy.axd
SET msDeploySite="<WebSite name>"
SET userName="WebDeploy"
SET password=%USERNAME%
SET platform=AnyCPU
SET msbuild=%FXPath%\MSBuild.exe /MaxCpuCount:%NUMBER_OF_PROCESSORS% /clp:ShowCommandLine
%MSBuild% %targetFile% /p:configuration=%configuration%;Platform=%platform% /p:DeployOnBuild=True /p:DeployTarget=MsDeployPublish /p:CreatePackageOnPublish=False /p:DeployIISAppPath=%msDeploySite% /p:MSDeployPublishMethod=WMSVC /p:MsDeployServiceUrl=%msDeployServiceUrl% /p:AllowUntrustedCertificate=True /p:UserName=%USERNAME% /p:Password=%password% /p:SkipExtraFilesOnServer=True /p:VisualStudioVersion=12.0
IF NOT "%ERRORLEVEL%"=="0" PAUSE
ENDLOCAL
Check if list<t> contains any of another list
You could use a nested Any()
for this check which is available on any Enumerable
:
bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x));
Faster performing on larger collections would be to project parameters
to source
and then use Intersect
which internally uses a HashSet<T>
so instead of O(n^2) for the first approach (the equivalent of two nested loops) you can do the check in O(n) :
bool hasMatch = parameters.Select(x => x.source)
.Intersect(myStrings)
.Any();
Also as a side comment you should capitalize your class names and property names to conform with the C# style guidelines.
Split Div Into 2 Columns Using CSS
Divide a division in two columns is very easy, just specify the width of your column better if you put this (like width:50%) and set the float:left for left column and float:right for right column.
Using Python's list index() method on a list of tuples or objects?
How about this?
>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [x for x, y in enumerate(tuple_list) if y[1] == 7]
[1]
>>> [x for x, y in enumerate(tuple_list) if y[0] == 'kumquat']
[2]
As pointed out in the comments, this would get all matches. To just get the first one, you can do:
>>> [y[0] for y in tuple_list].index('kumquat')
2
There is a good discussion in the comments as to the speed difference between all the solutions posted. I may be a little biased but I would personally stick to a one-liner as the speed we're talking about is pretty insignificant versus creating functions and importing modules for this problem, but if you are planning on doing this to a very large amount of elements you might want to look at the other answers provided, as they are faster than what I provided.
How to disable an input box using angular.js
<input type="text" input-disabled="editableInput" />
<button ng-click="editableInput = !editableInput">enable/disable</button>
app.controller("myController", function(){
$scope.editableInput = false;
});
app.directive("inputDisabled", function(){
return function(scope, element, attrs){
scope.$watch(attrs.inputDisabled, function(val){
if(val)
element.removeAttr("disabled");
else
element.attr("disabled", "disabled");
});
}
});
What is the difference between printf() and puts() in C?
In simple cases, the compiler converts calls to printf()
to calls to puts()
.
For example, the following code will be compiled to the assembly code I show next.
#include <stdio.h>
main() {
printf("Hello world!");
return 0;
}
push rbp
mov rbp,rsp
mov edi,str.Helloworld!
call dword imp.puts
mov eax,0x0
pop rbp
ret
In this example, I used GCC version 4.7.2 and compiled the source with gcc -o hello hello.c
.
Find all zero-byte files in directory and subdirectories
Bash 4+ tested -
This is the correct way to search for size 0:
find /path/to/dir -size 0 -type f -name "*.xml"
Search for multiple file extensions of size 0:
find /path/to/dir -size 0 -type f \( -iname \*.css -o -iname \*.js \)
Note: If you removed the \( ... \) the results would be all of the files that meet this requirement hence ignoring the size 0.
C++: Converting Hexadecimal to Decimal
This should work as well.
#include <ctype.h>
#include <string.h>
template<typename T = unsigned int>
T Hex2Int(const char* const Hexstr, bool* Overflow)
{
if (!Hexstr)
return false;
if (Overflow)
*Overflow = false;
auto between = [](char val, char c1, char c2) { return val >= c1 && val <= c2; };
size_t len = strlen(Hexstr);
T result = 0;
for (size_t i = 0, offset = sizeof(T) << 3; i < len && (int)offset > 0; i++)
{
if (between(Hexstr[i], '0', '9'))
result = result << 4 ^ Hexstr[i] - '0';
else if (between(tolower(Hexstr[i]), 'a', 'f'))
result = result << 4 ^ tolower(Hexstr[i]) - ('a' - 10); // Remove the decimal part;
offset -= 4;
}
if (((len + ((len % 2) != 0)) << 2) > (sizeof(T) << 3) && Overflow)
*Overflow = true;
return result;
}
The 'Overflow' parameter is optional, so you can leave it NULL.
Example:
auto result = Hex2Int("C0ffee", NULL);
auto result2 = Hex2Int<long>("DeadC0ffe", NULL);
Should image size be defined in the img tag height/width attributes or in CSS?
Definitely not both. Other than that I'd have to say it's a personal preference. I'd use css if I had many images the same size to reduce code.
.my_images img {width: 20px; height:20px}
In the long term CSS may win out due to HTML attribute deprecation and more likely due to the growth of vector image formats like SVG where it can actually make sense to scale images using non-pixel based units like % or em.
Screen width in React Native
Only two simple steps.
import { Dimensions } from 'react-native'
at top of your file.
const { height } = Dimensions.get('window');
now the window screen height is stored in the height variable.
What is the default value for enum variable?
You can use this snippet :-D
using System;
using System.Reflection;
public static class EnumUtils
{
public static T GetDefaultValue<T>()
where T : struct, Enum
{
return (T)GetDefaultValue(typeof(T));
}
public static object GetDefaultValue(Type enumType)
{
var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
if (attribute != null)
return attribute.Value;
var innerType = enumType.GetEnumUnderlyingType();
var zero = Activator.CreateInstance(innerType);
if (enumType.IsEnumDefined(zero))
return zero;
var values = enumType.GetEnumValues();
return values.GetValue(0);
}
}
Example:
using System;
public enum Enum1
{
Foo,
Bar,
Baz,
Quux
}
public enum Enum2
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 0
}
public enum Enum3
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 4
}
public static class Program
{
public static void Main()
{
var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
Console.WriteLine(defaultValue1); // Foo
var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
Console.WriteLine(defaultValue2); // Quux
var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
Console.WriteLine(defaultValue3); // Foo
var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
Console.WriteLine(defaultValue4); // Bar
}
}
How to create major and minor gridlines with different linestyles in Python
A simple DIY way would be to make the grid yourself:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3], [2,3,4], 'ro')
for xmaj in ax.xaxis.get_majorticklocs():
ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
ax.axvline(x=xmin, ls='--')
for ymaj in ax.yaxis.get_majorticklocs():
ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
ax.axhline(y=ymin, ls='--')
plt.show()
Split Strings into words with multiple word boundary delimiters
First of all, always use re.compile() before performing any RegEx operation in a loop because it works faster than normal operation.
so for your problem first compile the pattern and then perform action on it.
import re
DATA = "Hey, you - what are you doing here!?"
reg_tok = re.compile("[\w']+")
print reg_tok.findall(DATA)
How to Call a Function inside a Render in React/Jsx
The fix was at the accepted answer. Yet if someone wants to know why it worked and why the implementation in the SO question didn't work,
First, functions are first class objects in JavaScript. That means they are treated like any other variable. Function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. Read more here.
So we use that variable to invoke the function by adding parentheses () at the end.
One thing,
If you have a function that returns a funtion and you just need to call that returned function, you can just have double paranthesis when you call the outer function ()().
Set markers for individual points on a line in Matplotlib
There is a picture show all markers' name and description, i hope it will help you.
import matplotlib.pylab as plt
markers=['.',',','o','v','^','<','>','1','2','3','4','8','s','p','P','*','h','H','+','x','X','D','d','|','_']
descriptions=['point', 'pixel', 'circle', 'triangle_down', 'triangle_up','triangle_left', 'triangle_right', 'tri_down', 'tri_up', 'tri_left','tri_right', 'octagon', 'square', 'pentagon', 'plus (filled)','star', 'hexagon1', 'hexagon2', 'plus', 'x', 'x (filled)','diamond', 'thin_diamond', 'vline', 'hline']
x=[]
y=[]
for i in range(5):
for j in range(5):
x.append(i)
y.append(j)
plt.figure()
for i,j,m,l in zip(x,y,markers,descriptions):
plt.scatter(i,j,marker=m)
plt.text(i-0.15,j+0.15,s=m+' : '+l)
plt.axis([-0.1,4.8,-0.1,4.5])
plt.tight_layout()
plt.axis('off')
plt.show()
How to change the type of a field?
I use this script in mongodb console for string to float conversions...
db.documents.find({ 'fwtweaeeba' : {$exists : true}}).forEach( function(obj) {
obj.fwtweaeeba = parseFloat( obj.fwtweaeeba );
db.documents.save(obj); } );
db.documents.find({ 'versions.0.content.fwtweaeeba' : {$exists : true}}).forEach( function(obj) {
obj.versions[0].content.fwtweaeeba = parseFloat( obj.versions[0].content.fwtweaeeba );
db.documents.save(obj); } );
db.documents.find({ 'versions.1.content.fwtweaeeba' : {$exists : true}}).forEach( function(obj) {
obj.versions[1].content.fwtweaeeba = parseFloat( obj.versions[1].content.fwtweaeeba );
db.documents.save(obj); } );
db.documents.find({ 'versions.2.content.fwtweaeeba' : {$exists : true}}).forEach( function(obj) {
obj.versions[2].content.fwtweaeeba = parseFloat( obj.versions[2].content.fwtweaeeba );
db.documents.save(obj); } );
And this one in php)))
foreach($db->documents->find(array("type" => "chair")) as $document){
$db->documents->update(
array('_id' => $document[_id]),
array(
'$set' => array(
'versions.0.content.axdducvoxb' => (float)$document['versions'][0]['content']['axdducvoxb'],
'versions.1.content.axdducvoxb' => (float)$document['versions'][1]['content']['axdducvoxb'],
'versions.2.content.axdducvoxb' => (float)$document['versions'][2]['content']['axdducvoxb'],
'axdducvoxb' => (float)$document['axdducvoxb']
)
),
array('$multi' => true)
);
}
Simple dictionary in C++
If you are into optimization, and assuming the input is always one of the four characters, the function below might be worth a try as a replacement for the map:
char map(const char in)
{ return ((in & 2) ? '\x8a' - in : '\x95' - in); }
It works based on the fact that you are dealing with two symmetric pairs. The conditional works to tell apart the A/T pair from the G/C one ('G' and 'C' happen to have the second-least-significant bit in common). The remaining arithmetics performs the symmetric mapping. It's based on the fact that a = (a + b) - b is true for any a,b.
Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM
The normal layout for a maven multi module project is:
parent
+-- pom.xml
+-- module
+-- pom.xml
Check that you use this layout.
Additionally:
the relativePath
looks strange. Instead of '..'
<relativePath>..</relativePath>
try '../' instead:
<relativePath>../</relativePath>
You can also remove relativePath
if you use the standard layout. This is what I always do, and on the command line I can build as well the parent (and all modules) or only a single module.
The module path may be wrong. In the parent you define the module as:
<module>junitcategorizer.cutdetection</module>
You must specify the name of the folder of the child module, not an artifact identifier. If junitcategorizer.cutdetection
is not the name of the folder than change it accordingly.
Hope that helps..
EDIT have a look at the other post, I answered there.
How can I convert a DateTime to the number of seconds since 1970?
That approach will be good if the date-time in question is in UTC, or represents local time in an area that has never observed daylight saving time. The DateTime difference routines do not take into account Daylight Saving Time, and consequently will regard midnight June 1 as being a multiple of 24 hours after midnight January 1. I'm unaware of anything in Windows that reports historical daylight-saving rules for the current locale, so I don't think there's any good way to correctly handle any time prior to the most recent daylight-saving rule change.
How to copy a folder via cmd?
xcopy "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i
Probably the problem is the space.Try with quotes.
Determine on iPhone if user has enabled push notifications
Swift 3+
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
// settings.authorizationStatus == .authorized
})
} else {
return UIApplication.shared.currentUserNotificationSettings?.types.contains(UIUserNotificationType.alert) ?? false
}
RxSwift Observable Version for iOS10+:
import UserNotifications
extension UNUserNotificationCenter {
static var isAuthorized: Observable<Bool> {
return Observable.create { observer in
DispatchQueue.main.async {
current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
if settings.authorizationStatus == .authorized {
observer.onNext(true)
observer.onCompleted()
} else {
current().requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in
observer.onNext(granted)
observer.onCompleted()
}
}
})
}
return Disposables.create()
}
}
}
Why does this SQL code give error 1066 (Not unique table/alias: 'user')?
You need to give the user table an alias the second time you join to it
e.g.
SELECT article . * , section.title, category.title, user.name, u2.name
FROM article
INNER JOIN section ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user ON article.author_id = user.id
LEFT JOIN user u2 ON article.modified_by = u2.id
WHERE article.id = '1'
state machines tutorials
Unfortunately, most of the articles on state machines are written for C++ or other languages that have direct support for polymorphism as it's nice to model the states in an FSM implementation as classes that derive from an abstract state class.
However, it's pretty easy to implement state machines in C using either switch statements to dispatch events to states (for simple FSMs, they pretty much code right up) or using tables to map events to state transitions.
There are a couple of simple, but decent articles on a basic framework for state machines in C here:
Edit: Site "under maintenance", web archive links:
switch
statement-based state machines often use a set of macros to 'hide' the mechanics of the switch
statement (or use a set of if
/then
/else
statements instead of a switch
) and make what amounts to a "FSM language" for describing the state machine in C source. I personally prefer the table-based approach, but these certainly have merit, are widely used, and can be effective especially for simpler FSMs.
One such framework is outlined by Steve Rabin in "Game Programming Gems" Chapter 3.0 (Designing a General Robust AI Engine).
A similar set of macros is discussed here:
If you're also interested in C++ state machine implementations there's a lot more that can be found. I'll post pointers if you're interested.
Reading a resource file from within jar
Rather than trying to address the resource as a File just ask the ClassLoader to return an InputStream for the resource instead via getResourceAsStream:
InputStream in = getClass().getResourceAsStream("/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
As long as the file.txt
resource is available on the classpath then this approach will work the same way regardless of whether the file.txt
resource is in a classes/
directory or inside a jar
.
The URI is not hierarchical
occurs because the URI for a resource within a jar file is going to look something like this: file:/example.jar!/file.txt
. You cannot read the entries within a jar
(a zip
file) like it was a plain old File.
This is explained well by the answers to:
Best way to reverse a string
static void Main(string[] args)
{
string str = "";
string reverse = "";
Console.WriteLine("Enter the value to reverse");
str = Console.ReadLine();
int length = 0;
length = str.Length - 1;
while(length >= 0)
{
reverse = reverse + str[length];
length--;
}
Console.Write("Reverse string is {0}", reverse);
Console.ReadKey();
}
How to get a Color from hexadecimal Color String
This question comes up for a number of searches related to hex color so I will add a summary here.
Color from int
Hex colors take the form RRGGBB
or AARRGGBB
(alpha, red, green, blue). In my experience, when using an int
directly, you need to use the full AARRGGBB
form. If you only have the RRGGBB
form then just prefix it with FF
to make the alpha (transparency) fully opaque. Here is how you would set it in code. Using 0x
at the beginning means it is hexadecimal and not base 10.
int myColor = 0xFF3F51B5;
myView.setBackgroundColor(myColor);
Color from String
As others have noted, you can use Color.parseColor
like so
int myColor = Color.parseColor("#3F51B5");
myView.setBackgroundColor(myColor);
Note that the String must start with a #
. Both RRGGBB
and AARRGGBB
formats are supported.
Color from XML
You should actually be getting your colors from XML whenever possible. This is the recommended option because it makes it much easier to make color changes to your app. If you set a lot of hex colors throughout your code then it is a big pain to try to change them later.
Android material design has color palates with the hex values already configured.
These theme colors are used throughout your app and look like this:
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="primary">#3F51B5</color>
<color name="primary_dark">#303F9F</color>
<color name="primary_light">#C5CAE9</color>
<color name="accent">#FF4081</color>
<color name="primary_text">#212121</color>
<color name="secondary_text">#757575</color>
<color name="icons">#FFFFFF</color>
<color name="divider">#BDBDBD</color>
</resources>
If you need additional colors, a good practice to follow is to define your color in two steps in xml. First name the the hex value color and then name a component of your app that should get a certain color. This makes it easy to adjust the colors later. Again, this is in colors.xml.
<color name="orange">#fff3632b</color>
<color name="my_view_background_color">@color/orange</color>
Then when you want to set the color in code, do the following:
int myColor = ContextCompat.getColor(context, R.color.my_view_background_color);
myView.setBackgroundColor(myColor);
Android Predefined colors
The Color class comes with a number of predefined color constants. You can use it like this.
int myColor = Color.BLUE;
myView.setBackgroundColor(myColor);
Other colors are
Color.BLACK
Color.BLUE
Color.CYAN
Color.DKGRAY
Color.GRAY
Color.GREEN
Color.LTGRAY
Color.MAGENTA
Color.RED
Color.TRANSPARENT
Color.WHITE
Color.YELLOW
Notes
Understanding the main method of python
If you import the module (.py) file you are creating now from another python script it will not execute the code within
if __name__ == '__main__':
...
If you run the script directly from the console, it will be executed.
Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution or importing of the module.
This is expanded upon a little more at python.berkely.edu
What are unit tests, integration tests, smoke tests, and regression tests?
I just wanted to add and give some more context on why we have these levels of test, what they really mean with examples
Mike Cohn in his book “Succeeding with Agile” came up with the “Testing Pyramid” as a way to approach automated tests in projects. There are various interpretations of this model. The model explains what kind of automated tests need to be created, how fast they can give feedback on the application under test and who writes these tests.
There are basically 3 levels of automated testing needed for any project and they are as follows.
Unit Tests-
These test the smallest component of your software application. This could literally be one function in a code which computes a value based on some inputs. This function is part of several other functions of the hardware/software codebase that makes up the application.
For example - Let’s take a web based calculator application. The smallest components of this application that needs to be unit tested could be a function that performs addition, another that performs subtraction and so on. All these small functions put together makes up the calculator application.
Historically developer writes these tests as they are usually written in the same programming language as the software application. Unit testing frameworks such as JUnit and NUnit (for java), MSTest (for C# and .NET) and Jasmine/Mocha (for JavaScript) are used for this purpose.
The biggest advantage of unit tests are, they run really fast underneath the UI and we can get quick feedback about the application. This should comprise more than 50% of your automated tests.
API/Integration Tests-
These test various components of the software system together. The components could include testing databases, API’s (Application Programming Interface), 3rd party tools and services along with the application.
For example - In our calculator example above, the web application may use a database to store values, use API’s to do some server side validations and it may use a 3rd party tool/service to publish results to the cloud to make it available across different platforms.
Historically a developer or technical QA would write these tests using various tools such as Postman, SoapUI, JMeter and other tools like Testim.
These run much faster than UI tests as they still run underneath the hood but may consume a little more time than unit tests as it has to check the communication between various independent components of the system and ensure they have seamless integration. This should comprise more that 30% of the automated tests.
UI Tests-
Finally, we have tests that validate the UI of the application. These tests are usually written to test end to end flows through the application.
For example - In the calculator application, an end to end flow could be, opening up the browser-> Entering the calculator application url -> Logging in with username/password -> Opening up the calculator application -> Performing some operations on the calculator -> verifying those results from the UI -> Logging out of the application. This could be one end to end flow that would be a good candidate for UI automation.
Historically, technical QA’s or manual testers write UI tests. They use open source frameworks like Selenium or UI testing platforms like Testim to author, execute and maintain the tests. These tests give more visual feedback as you can see how the tests are running, the difference between the expected and actual results through screenshots, logs, test reports.
The biggest limitation of UI tests is, they are relatively slow compared to Unit and API level tests. So, it should comprise only 10-20% of the overall automated tests.
The next two types of tests can vary based on your project but the idea is-
Smoke Tests
This can be a combination of the above 3 levels of testing. The idea is to run it during every code check in and ensure the critical functionalities of the system are still working as expected; after the new code changes are merged. They typically need to run with 5 - 10 mins to get faster feedback on failures
Regression Tests
They usually are run once a day at least and cover various functionalities of the system. They ensure the application is still working as expected. They are more details than the smoke tests and cover more scenarios of the application including the non-critical ones.
git - remote add origin vs remote set-url origin
This is very simple If you have already set a remote origin url then you use set-url
command to change that, otherwise simply use add
command
git remote -v
Check if any remote already exists
- If Yes then use
git remote set-url origin [email protected]:User/UserRepo.git
to change the origin
- If No then use
git remote add origin [email protected]:User/UserRepo.git
to set new origin for your repo.
- and finally use
git push -u origin master
to push your code to remote and add upstream (tracking) reference to your remote branch.
NOTE: If you use -u
flag, its for upstream, it enables you to use simply git pull
instead of git pull origin <branch-name>
in upcoming operations.
Happy Coding ;)
Primitive type 'short' - casting in Java
Java always uses at least 32 bit values for calculations. This is due to the 32-bit architecture which was common 1995 when java was introduced. The register size in the CPU was 32 bit and the arithmetic logic unit accepted 2 numbers of the length of a cpu register. So the cpus were optimized for such values.
This is the reason why all datatypes which support arithmetic opperations and have less than 32-bits are converted to int (32 bit) as soon as you use them for calculations.
So to sum up it mainly was due to performance issues and is kept nowadays for compatibility.
Regular expression to match DNS hostname or IP Address?
Here is a regex that I used in Ant to obtain a proxy host IP or hostname out of ANT_OPTS. This was used to obtain the proxy IP so that I could run an Ant "isreachable" test before configuring a proxy for a forked JVM.
^.*-Dhttp\.proxyHost=(\w{1,}\.\w{1,}\.\w{1,}\.*\w{0,})\s.*$
Maven: Failed to retrieve plugin descriptor error
Thank it worked...
edit setting.xml
and replace proxy with this
Its working 100%
<proxy>
<active>true</active>
<protocol>http</protocol>
<username>your username</username>
<password>password</password>
<host>proxy.host.net</host>
<port>80</port>
How to set cache: false in jQuery.get call
Add the parameter yourself.
$.get(url,{ "_": $.now() }, function(rdata){
console.log(rdata);
});
As of jQuery 3.0, you can now do this:
$.get({
url: url,
cache: false
}).then(function(rdata){
console.log(rdata);
});
Get encoding of a file in Windows
If you have "git" or "Cygwin" on your Windows Machine, then go to the folder where your file is present and execute the command:
file *
This will give you the encoding details of all the files in that folder.
How to install libusb in Ubuntu
Here is what worked for me.
Install the userspace USB programming library development files
sudo apt-get install libusb-1.0-0-dev
sudo updatedb && locate libusb.h
The path should appear as (or similar)
/usr/include/libusb-1.0/libusb.h
Include the header to your C code
#include <libusb-1.0/libusb.h>
Compile your C file
gcc -o example example.c -lusb-1.0
How to set a tkinter window to a constant size
Here is the most simple way.
import tkinter as tk
root = tk.Tk()
root.geometry('200x200')
root.resizable(width=0, height=0)
root.mainloop()
I don't think there is anything to specify.
It's pretty straight forward.
Can you autoplay HTML5 videos on the iPad?
iOS 10 update
The ban on autoplay has been lifted as of iOS 10 - but with some restrictions (e.g. A can be autoplayed if there is no audio track).
To see a full list of these restrictions, see the official docs: https://webkit.org/blog/6784/new-video-policies-for-ios/
iOS 9 and before
As of iOS 6.1, it is no longer possible to auto-play videos on the iPad.
My assumption as to why they've disabled the auto-play feature?
Well, as many device owners have data usage/bandwidth limits on their devices, I think Apple felt that the user themselves should decide when they initiate bandwidth usage.
After a bit of research I found the following extract in the Apple documentation in regard to auto-play on iOS devices to confirm my assumption:
"Apple has made the decision to disable the automatic playing of video
on iOS devices, through both script and attribute implementations.
In Safari, on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and
auto-play are disabled. No data is loaded until the user initiates it." - Apple documentation.
Here is a separate warning featured on the Safari HTML5 Reference page about why embedded media cannot be played in Safari on iOS:
Warning: To prevent unsolicited downloads over cellular networks at
the user’s expense, embedded media cannot be played automatically in
Safari on iOS—the user always initiates playback. A controller is
automatically supplied on iPhone or iPod touch once playback in
initiated, but for iPad you must either set the controls attribute or
provide a controller using JavaScript.
What this means (in terms of code) is that Javascript's play()
and load()
methods are inactive until the user initiates playback, unless the play()
or load()
method is triggered by user action (e.g. a click event).
Basically, a user-initiated play button works, but
an onLoad="play()"
event does not.
For example, this would play the movie:
<input type="button" value="Play" onclick="document.myMovie.play()">
Whereas the following would do nothing on iOS:
<body onload="document.myMovie.play()">
addEventListener vs onclick
Summary:
addEventListener
can add multiple events, whereas with onclick
this cannot be done.
onclick
can be added as an HTML
attribute, whereas an addEventListener
can only be added within <script>
elements.
addEventListener
can take a third argument which can stop the event propagation.
Both can be used to handle events. However, addEventListener
should be the preferred choice since it can do everything onclick
does and more. Don't use inline onclick
as HTML attributes as this mixes up the javascript and the HTML which is a bad practice. It makes the code less maintainable.
Array of PHP Objects
The best place to find answers to general (and somewhat easy questions) such as this is to read up on PHP docs. Specifically in your case you can read more on objects. You can store stdObject and instantiated objects within an array. In fact, there is a process known as 'hydration' which populates the member variables of an object with values from a database row, then the object is stored in an array (possibly with other objects) and returned to the calling code for access.
-- Edit --
class Car
{
public $color;
public $type;
}
$myCar = new Car();
$myCar->color = 'red';
$myCar->type = 'sedan';
$yourCar = new Car();
$yourCar->color = 'blue';
$yourCar->type = 'suv';
$cars = array($myCar, $yourCar);
foreach ($cars as $car) {
echo 'This car is a ' . $car->color . ' ' . $car->type . "\n";
}
Allowing Java to use an untrusted certificate for SSL/HTTPS connection
Here is some relevant code:
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
// Now you can access an https URL without having the certificate in the truststore
try {
URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}
This will completely disable SSL checking—just don't learn exception handling from such code!
To do what you want, you would have to implement a check in your TrustManager that prompts the user.
android layout with visibility GONE
Kotlin Style way to do this more simple (example):
isVisible = false
Complete example:
if (some_data_array.details == null){
holder.view.some_data_array.isVisible = false}
How to exit if a command failed?
I've hacked up the following idiom:
echo "Generating from IDL..."
idlj -fclient -td java/src echo.idl
if [ $? -ne 0 ]; then { echo "Failed, aborting." ; exit 1; } fi
echo "Compiling classes..."
javac *java
if [ $? -ne 0 ]; then { echo "Failed, aborting." ; exit 1; } fi
echo "Done."
Precede each command with an informative echo, and follow each command with that same
if [ $? -ne 0 ];...
line. (Of course, you can edit that error message if you want to.)
Passing variables through handlebars partial
The accepted answer works great if you just want to use a different context in your partial. However, it doesn't let you reference any of the parent context. To pass in multiple arguments, you need to write your own helper. Here's a working helper for Handlebars 2.0.0
(the other answer works for versions <2.0.0
):
Handlebars.registerHelper('renderPartial', function(partialName, options) {
if (!partialName) {
console.error('No partial name given.');
return '';
}
var partial = Handlebars.partials[partialName];
if (!partial) {
console.error('Couldnt find the compiled partial: ' + partialName);
return '';
}
return new Handlebars.SafeString( partial(options.hash) );
});
Then in your template, you can do something like:
{{renderPartial 'myPartialName' foo=this bar=../bar}}
And in your partial, you'll be able to access those values as context like:
<div id={{bar.id}}>{{foo}}</div>
Circular gradient in android
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<gradient
android:endColor="@color/color1"
android:gradientRadius="250dp"
android:startColor="#8F15DA"
android:type="radial" />
<corners
android:bottomLeftRadius="50dp"
android:bottomRightRadius="50dp"
android:radius="3dp"
android:topLeftRadius="0dp"
android:topRightRadius="50dp" />
</shape>
Send data from activity to fragment in Android
Basic Idea of using Fragments (F) is to create reusable self sustaining UI components in android applications. These Fragments are contained in activities and there are common(best) way of creating communication path ways from A -> F and F-A, It is a must to Communicate between F-F through a Activity because then only the Fragments become decoupled and self sustaining.
So passing data from A -> F is going to be the same as explained by ??s???? K. In addition to that answer, After creation of the Fragments inside an Activity, we can also pass data to the fragments calling methods in Fragments.
For example:
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
articleFrag.updateArticleView(position);
No Exception while type casting with a null in java
Casting null values is required for following construct where a method is overloaded and if null is passed to these overloaded methods then the compiler does not know how to clear up the ambiguity hence we need to typecast null in these cases:
class A {
public void foo(Long l) {
// do something with l
}
public void foo(String s) {
// do something with s
}
}
new A().foo((String)null);
new A().foo((Long)null);
Otherwise you couldn't call the method you need.
Check if Nullable Guid is empty in c#
If you want be sure you need to check both
SomeProperty == null || SomeProperty == Guid.Empty
Because it can be null 'Nullable' and it can be an empty GUID something like this {00000000-0000-0000-0000-000000000000}
Using Linq to get the last N elements of a collection?
I know it's to late to answer this question. But if you are working with collection of type IList<> and you don't care about an order of the returned collection, then this method is working faster. I've used Mark Byers answer and made a little changes. So now method TakeLast is:
public static IEnumerable<T> TakeLast<T>(IList<T> source, int takeCount)
{
if (source == null) { throw new ArgumentNullException("source"); }
if (takeCount < 0) { throw new ArgumentOutOfRangeException("takeCount", "must not be negative"); }
if (takeCount == 0) { yield break; }
if (source.Count > takeCount)
{
for (int z = source.Count - 1; takeCount > 0; z--)
{
takeCount--;
yield return source[z];
}
}
else
{
for(int i = 0; i < source.Count; i++)
{
yield return source[i];
}
}
}
For test I have used Mark Byers method and kbrimington's andswer. This is test:
IList<int> test = new List<int>();
for(int i = 0; i<1000000; i++)
{
test.Add(i);
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
IList<int> result = TakeLast(test, 10).ToList();
stopwatch.Stop();
Stopwatch stopwatch1 = new Stopwatch();
stopwatch1.Start();
IList<int> result1 = TakeLast2(test, 10).ToList();
stopwatch1.Stop();
Stopwatch stopwatch2 = new Stopwatch();
stopwatch2.Start();
IList<int> result2 = test.Skip(Math.Max(0, test.Count - 10)).Take(10).ToList();
stopwatch2.Stop();
And here are results for taking 10 elements:
and for taking 1000001 elements results are:
change text of button and disable button in iOS
To Change Button title:
[mybtn setTitle:@"My Button" forState:UIControlStateNormal];
[mybtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
For Disable:
[mybtn setEnabled:NO];
TimePicker Dialog from clicking EditText
For me the dialogue appears more than one if I click the dpFlightDate edit text more than one time same for the timmer dialog .
how can I avoid this dialog to appear only once and if the user click's 2nd time the dialog must not appear again ie if dialog is on the screen ?
// perform click event on edit text
dpFlightDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(frmFlightDetails.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
dpFlightDate.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
tpFlightTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog
timePickerDialog = new TimePickerDialog(frmFlightDetails.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
tpFlightTime.setText( selectedHour + ":" + selectedMinute);
}
}, hour, minute, true);//Yes 24 hour time
timePickerDialog.setTitle("Select Time");
timePickerDialog.show();
}
});
Controlling number of decimal digits in print output in R
If you are producing the entire output yourself, you can use sprintf()
, e.g.
> sprintf("%.10f",0.25)
[1] "0.2500000000"
specifies that you want to format a floating point number with ten decimal points (in %.10f
the f
is for float and the .10
specifies ten decimal points).
I don't know of any way of forcing R's higher level functions to print an exact number of digits.
Displaying 100 digits does not make sense if you are printing R's usual numbers, since the best accuracy you can get using 64-bit doubles is around 16 decimal digits (look at .Machine$double.eps on your system). The remaining digits will just be junk.
Get value when selected ng-option changes
Best practise is to create an object (always use a . in ng-model)
In your controller:
var myObj: {
ngModelValue: null
};
and in your template:
<select
ng-model="myObj.ngModelValue"
ng-options="o.id as o.name for o in options">
</select>
Now you can just watch
myObj.ngModelValue
or you can use the ng-change directive like so:
<select
ng-model="myObj.ngModelValue"
ng-options="o.id as o.name for o in options"
ng-change="myChangeCallback()">
</select>
The egghead.io video "The Dot" has a really good overview, as does this very popular stack overflow question: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
C# importing class into another class doesn't work
I know this is very old question but I had the same requirement and just discovered that after c#6 you can use static in using for classes to import.
I hope this helps someone....
using static yourNameSpace.YourClass;
Why in C++ do we use DWORD rather than unsigned int?
SDK developers prefer to define their own types using typedef. This allows changing underlying types only in one place, without changing all client code. It is important to follow this convention. DWORD is unlikely to be changed, but types like DWORD_PTR are different on different platforms, like Win32 and x64. So, if some function has DWORD parameter, use DWORD and not unsigned int, and your code will be compiled in all future windows headers versions.
Open files always in a new tab
In my case, I also had to set workbench.editor.showTabs
property to true (in addition to workbench.editor.enablePreview
)
I'm not sure how it got changed to false. Maybe, I've accidentally set it to false using some shortcut.
What is $@ in Bash?
Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters
Special Parameters
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.
*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*"
is equivalent to "$1c$2c..."
, where c
is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@"
is equivalent to "$1"
"$2"
... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@"
and $@
expand to nothing (i.e., they are removed).
How to restrict user to type 10 digit numbers in input element?
HTML
<input type="text" name="fieldName" id="fieldSelectorId">
This field only takes at max 10 digits number and do n't accept zero as the first digit.
JQuery
jQuery(document).ready(function () {
jQuery("#fieldSelectorId").keypress(function (e) {
var length = jQuery(this).val().length;
if(length > 9) {
return false;
} else if(e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
} else if((length == 0) && (e.which == 48)) {
return false;
}
});
});
ASP.Net MVC: How to display a byte array image from model
You need to have a byte[] in your DB.
My byte[] is in my Person object:
public class Person
{
public byte[] Image { get; set; }
}
You need to convert your byte[] in a String. So, I have in my controller :
String img = Convert.ToBase64String(person.Image);
Next, in my .cshtml file, my Model is a ViewModel. This is what I have in :
public String Image { get; set; }
I use it like this in my .cshtml file:
<img src="@String.Format("data:image/jpg;base64,{0}", Model.Image)" />
"data:image/image file extension;base64,{0}, your image String"
I wish it will help someone !
Is it possible to make abstract classes in Python?
As explained in the other answers, yes you can use abstract classes in Python using the abc
module. Below I give an actual example using abstract @classmethod
, @property
and @abstractmethod
(using Python 3.6+). For me it is usually easier to start off with examples I can easily copy&paste; I hope this answer is also useful for others.
Let's first create a base class called Base
:
from abc import ABC, abstractmethod
class Base(ABC):
@classmethod
@abstractmethod
def from_dict(cls, d):
pass
@property
@abstractmethod
def prop1(self):
pass
@property
@abstractmethod
def prop2(self):
pass
@prop2.setter
@abstractmethod
def prop2(self, val):
pass
@abstractmethod
def do_stuff(self):
pass
Our Base
class will always have a from_dict
classmethod
, a property
prop1
(which is read-only) and a property
prop2
(which can also be set) as well as a function called do_stuff
. Whatever class is now built based on Base
will have to implement all of these four methods/properties. Please note that for a method to be abstract, two decorators are required - classmethod
and abstract property
.
Now we could create a class A
like this:
class A(Base):
def __init__(self, name, val1, val2):
self.name = name
self.__val1 = val1
self._val2 = val2
@classmethod
def from_dict(cls, d):
name = d['name']
val1 = d['val1']
val2 = d['val2']
return cls(name, val1, val2)
@property
def prop1(self):
return self.__val1
@property
def prop2(self):
return self._val2
@prop2.setter
def prop2(self, value):
self._val2 = value
def do_stuff(self):
print('juhu!')
def i_am_not_abstract(self):
print('I can be customized')
All required methods/properties are implemented and we can - of course - also add additional functions that are not part of Base
(here: i_am_not_abstract
).
Now we can do:
a1 = A('dummy', 10, 'stuff')
a2 = A.from_dict({'name': 'from_d', 'val1': 20, 'val2': 'stuff'})
a1.prop1
# prints 10
a1.prop2
# prints 'stuff'
As desired, we cannot set prop1
:
a.prop1 = 100
will return
AttributeError: can't set attribute
Also our from_dict
method works fine:
a2.prop1
# prints 20
If we now defined a second class B
like this:
class B(Base):
def __init__(self, name):
self.name = name
@property
def prop1(self):
return self.name
and tried to instantiate an object like this:
b = B('iwillfail')
we will get an error
TypeError: Can't instantiate abstract class B with abstract methods
do_stuff, from_dict, prop2
listing all the things defined in Base
which we did not implement in B
.
Make a Bash alias that takes a parameter?
Respectfully to all those saying you can't insert a parameter in the middle of an alias I just tested it and found that it did work.
alias mycommand = "python3 "$1" script.py --folderoutput RESULTS/"
when I then ran mycommand foobar it worked exactly as if I had typed the command out longhand.
How to declare a global variable in php?
Let's think a little different, You can use static parameters:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function func() {
echo global::$foo;
}
HTML form with multiple "actions"
this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!
_x000D_
_x000D_
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
_x000D_
_x000D_
How do I get formatted JSON in .NET using C#?
This worked for me. In case someone is looking for a VB.NET version.
@imports System
@imports System.IO
@imports Newtonsoft.Json
Public Shared Function JsonPrettify(ByVal json As String) As String
Using stringReader = New StringReader(json)
Using stringWriter = New StringWriter()
Dim jsonReader = New JsonTextReader(stringReader)
Dim jsonWriter = New JsonTextWriter(stringWriter) With {
.Formatting = Formatting.Indented
}
jsonWriter.WriteToken(jsonReader)
Return stringWriter.ToString()
End Using
End Using
End Function
Find TODO tags in Eclipse
Is there an easy way to view all methods which contain this comment? Some sort of menu option?
Yes, choose one of the following:
Go to Window ? Show View ? Tasks (Not TaskList). The new view will show up where the "Console" and "Problems" tabs are by default.
As mentioned elsewhere, you can see them next to the scroll bar as little blue rectangles if you have the source file in question open.
If you just want the // TODO Auto-generated method stub
messages (rather than all // TODO
messages) you should use the search function (Ctrl-F for ones in this file Search ? Java Search ? Search string for the ability to specify this workspace, that file, this project, etc.)
Change location of log4j.properties
You must use log4j.configuration
property like this:
java -Dlog4j.configuration=file:/path/to/log4j.properties myApp
If the file is under the class-path (inside ./src/main/resources/ folder), you can omit the file://
protocol:
java -Dlog4j.configuration=path/to/log4j.properties myApp
Better way to convert file sizes in Python
Just in case anyone's searching for the reverse of this problem (as I sure did) here's what works for me:
def get_bytes(size, suffix):
size = int(float(size))
suffix = suffix.lower()
if suffix == 'kb' or suffix == 'kib':
return size << 10
elif suffix == 'mb' or suffix == 'mib':
return size << 20
elif suffix == 'gb' or suffix == 'gib':
return size << 30
return False
"FATAL: Module not found error" using modprobe
The best thing is to actually use the kernel makefile to install the module:
Here is are snippets to add to your Makefile
around the top add:
PWD=$(shell pwd)
VER=$(shell uname -r)
KERNEL_BUILD=/lib/modules/$(VER)/build
# Later if you want to package the module binary you can provide an INSTALL_ROOT
# INSTALL_ROOT=/tmp/install-root
around the end add:
install:
$(MAKE) -C $(KERNEL_BUILD) M=$(PWD) \
INSTALL_MOD_PATH=$(INSTALL_ROOT) modules_install
and then you can issue
sudo make install
this will put it either in /lib/modules/$(uname -r)/extra/
or /lib/modules/$(uname -r)/misc/
and run depmod appropriately
iOS 7 - Failing to instantiate default view controller
I get this error when I change the the storyboard file name "Main.storyboard" TO: "XXX.storyboard"
The solution for me was:
- Product->Clean
- CHANGE: Supporting Files -> info.plist -> Main storyboard file base name -> Main TO: XXX
Good Luck
PHP Multiple Checkbox Array
<form method='post' id='userform' action='thisform.php'> <tr>
<td>Trouble Type</td>
<td>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
</td> </tr> </table> <input type='submit' class='buttons'> </form>
<?php
if (isset($_POST['checkboxvar']))
{
print_r($_POST['checkboxvar']);
}
?>
You pass the form name as an array and then you can access all checked boxes using the var itself which would then be an array.
To echo checked options into your email you would then do this:
echo implode(',', $_POST['checkboxvar']); // change the comma to whatever separator you want
Please keep in mind you should always sanitize your input as needed.
For the record, official docs on this exist: http://php.net/manual/en/faq.html.php#faq.html.arrays
How to compare oldValues and newValues on React Hooks useEffect?
Option 1 - run useEffect when value changes
const Component = (props) => {
useEffect(() => {
console.log("val1 has changed");
}, [val1]);
return <div>...</div>;
};
Demo
Option 2 - useHasChanged hook
Comparing a current value to a previous value is a common pattern, and justifies a custom hook of it's own that hides implementation details.
const Component = (props) => {
const hasVal1Changed = useHasChanged(val1)
useEffect(() => {
if (hasVal1Changed ) {
console.log("val1 has changed");
}
});
return <div>...</div>;
};
const useHasChanged= (val: any) => {
const prevVal = usePrevious(val)
return prevVal !== val
}
const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
Demo
Date constructor returns NaN in IE, but works in Firefox and Chrome
Here's another approach that adds a method to the Date
object
usage: var d = (new Date()).parseISO8601("1971-12-15");
/**
* Parses the ISO 8601 formated date into a date object, ISO 8601 is YYYY-MM-DD
*
* @param {String} date the date as a string eg 1971-12-15
* @returns {Date} Date object representing the date of the supplied string
*/
Date.prototype.parseISO8601 = function(date){
var matches = date.match(/^\s*(\d{4})-(\d{2})-(\d{2})\s*$/);
if(matches){
this.setFullYear(parseInt(matches[1]));
this.setMonth(parseInt(matches[2]) - 1);
this.setDate(parseInt(matches[3]));
}
return this;
};
Is it possible to make input fields read-only through CSS?
It is not (with current browsers) possible to make an input field read-only through CSS alone.
Though, as you have already mentioned, you can apply the attribute readonly='readonly'
.
If your main criteria is to not alter the markup in the source, there are ways to get this in, unobtrusively, with javascript.
With jQuery, this is easy:
$('input').attr('readonly', true);
Or even with plain Javascript:
document.getElementById('someId').setAttribute('readonly', 'readonly');
How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame
There's a handy ntile
function in package dplyr
. It's flexible in the sense that you can very easily define the number of *tiles or "bins" you want to create.
Load the package (install first if you haven't) and add the quartile column:
library(dplyr)
temp$quartile <- ntile(temp$value, 4)
Or, if you want to use dplyr syntax:
temp <- temp %>% mutate(quartile = ntile(value, 4))
Result in both cases is:
temp
# name value quartile
#1 a -0.56047565 1
#2 b -0.23017749 2
#3 c 1.55870831 4
#4 d 0.07050839 2
#5 e 0.12928774 3
#6 f 1.71506499 4
#7 g 0.46091621 3
#8 h -1.26506123 1
#9 i -0.68685285 1
#10 j -0.44566197 2
#11 k 1.22408180 4
#12 l 0.35981383 3
data:
Note that you don't need to create the "quartile" column in advance and use set.seed
to make the randomization reproducible:
set.seed(123)
temp <- data.frame(name=letters[1:12], value=rnorm(12))
Spring Data JPA Update @Query not updating?
I struggled with the same problem where I was trying to execute an update query like the same as you did-
@Modifying
@Transactional
@Query(value = "UPDATE SAMPLE_TABLE st SET st.status=:flag WHERE se.referenceNo in :ids")
public int updateStatus(@Param("flag")String flag, @Param("ids")List<String> references);
This will work if you have put @EnableTransactionManagement
annotation on the main class.
Spring 3.1 introduces the @EnableTransactionManagement
annotation to be used in on @Configuration
classes and enable transactional support.
How to set up file permissions for Laravel?
I'd do it like this:
sudo chown -R $USER:www-data laravel-project/
find laravel-project/ -type f -exec chmod 664 {} \;
find laravel-project/ -type d -exec chmod 775 {} \;
then finally, you need to give webserver permission to modify the storage
and bootstrap/cache
directories:
sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
MySQL: #126 - Incorrect key file for table
Now of the other answers solved it for me. Turns out that renaming a column and an index in the same query caused the error.
Not working:
-- rename column and rename index
ALTER TABLE `client_types`
CHANGE `template_path` `path` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
DROP INDEX client_types_template_path_unique,
ADD UNIQUE INDEX `client_types_path_unique` (`path` ASC);
Works (2 statements):
-- rename column
ALTER TABLE `client_types`
CHANGE `template_path` `path` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
-- rename index
ALTER TABLE `client_types`
DROP INDEX client_types_template_path_unique,
ADD UNIQUE INDEX `client_types_path_unique` (`path` ASC);
This was on MariaDB 10.0.20. There were no errors with the same query on MySQL 5.5.48.
Scroll to a specific Element Using html
You should mention whether you want it to smoothly scroll or simply jump to an element.
Jumping is easy & can be done just with HTML or Javascript. The simplest is to use anchor's. The limitation is that every element you want to scroll to has to have an id
. A side effect is that #theID
will be appended to the URL
<a href="#scroll">Go to Title</a>
<div>
<h1 id="scroll">Title</h1>
</div>
You can add CSS effects to the target when the link is clicked with the CSS :target
selector.
With some basic JS you can do more, namely the method scrollIntoView()
. Your elements don't need an id, though it is still easier, e.g.
function onLinkClick() {
document.getElementsByTagName('h2')[3].scrollIntoView();
// will scroll to 4th h3 element
}
Finally, if you need smooth scrolling, you should have a look at JS Smooth Scroll or this snippet for jQuery. (NB: there are probably many more).
Understanding Fragment's setRetainInstance(boolean)
SetRetainInstance(true) allows the fragment sort of survive. Its members will be retained during configuration change like rotation. But it still may be killed when the activity is killed in the background. If the containing activity in the background is killed by the system, it's instanceState should be saved by the system you handled onSaveInstanceState properly. In another word the onSaveInstanceState will always be called. Though onCreateView won't be called if SetRetainInstance is true and fragment/activity is not killed yet, it still will be called if it's killed and being tried to be brought back.
Here are some analysis of the android activity/fragment hope it helps.
http://ideaventure.blogspot.com.au/2014/01/android-activityfragment-life-cycle.html
Creating a list/array in excel using VBA to get a list of unique names in a column
I realize this is an old question, but I use a much simpler way. Typically I just grab the list that I need, either by query or copying an existing list or whatever, then remove the duplicates. We will assume for this answer that your list is already in column C, row 4, as per the original question. This method works for whatever size list you have and you can select header yes or no.
Dim rng as range
Range("C4").Select
Set rng = Range(Selection, Selection.End(xlDown))
rng.RemoveDuplicates Columns:=1, Header:=xlYes
Error: stray '\240' in program
It appears you have illegal characters in your source. I cannot figure out what character \240
should be but apparently it is around the start of line 10
In the code you posted, the issue does not exist: Live On Coliru
How do you detect where two line segments intersect?
I tried some of these answers, but they didnt work for me (sorry guys); after some more net searching I found this.
With a little modification to his code I now have this function that will return the point of intersection or if no intersection is found it will return -1,-1.
Public Function intercetion(ByVal ax As Integer, ByVal ay As Integer, ByVal bx As Integer, ByVal by As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal dx As Integer, ByVal dy As Integer) As Point
'// Determines the intersection point of the line segment defined by points A and B
'// with the line segment defined by points C and D.
'//
'// Returns YES if the intersection point was found, and stores that point in X,Y.
'// Returns NO if there is no determinable intersection point, in which case X,Y will
'// be unmodified.
Dim distAB, theCos, theSin, newX, ABpos As Double
'// Fail if either line segment is zero-length.
If ax = bx And ay = by Or cx = dx And cy = dy Then Return New Point(-1, -1)
'// Fail if the segments share an end-point.
If ax = cx And ay = cy Or bx = cx And by = cy Or ax = dx And ay = dy Or bx = dx And by = dy Then Return New Point(-1, -1)
'// (1) Translate the system so that point A is on the origin.
bx -= ax
by -= ay
cx -= ax
cy -= ay
dx -= ax
dy -= ay
'// Discover the length of segment A-B.
distAB = Math.Sqrt(bx * bx + by * by)
'// (2) Rotate the system so that point B is on the positive X axis.
theCos = bx / distAB
theSin = by / distAB
newX = cx * theCos + cy * theSin
cy = cy * theCos - cx * theSin
cx = newX
newX = dx * theCos + dy * theSin
dy = dy * theCos - dx * theSin
dx = newX
'// Fail if segment C-D doesn't cross line A-B.
If cy < 0 And dy < 0 Or cy >= 0 And dy >= 0 Then Return New Point(-1, -1)
'// (3) Discover the position of the intersection point along line A-B.
ABpos = dx + (cx - dx) * dy / (dy - cy)
'// Fail if segment C-D crosses line A-B outside of segment A-B.
If ABpos < 0 Or ABpos > distAB Then Return New Point(-1, -1)
'// (4) Apply the discovered position to line A-B in the original coordinate system.
'*X=Ax+ABpos*theCos
'*Y=Ay+ABpos*theSin
'// Success.
Return New Point(ax + ABpos * theCos, ay + ABpos * theSin)
End Function
How should I tackle --secure-file-priv in MySQL?
I solved it using the LOCAL
option in the command:
LOAD DATA LOCAL INFILE "text.txt" INTO TABLE mytable;
You can find more info here.
If LOCAL is specified, the file is read by the client program on the
client host and sent to the server. The file can be given as a full
path name to specify its exact location. If given as a relative path
name, the name is interpreted relative to the directory in which the
client program was started.
Simple calculations for working with lat/lon and km distance?
Thanks Jim Lewis for his great answer and I would like to illustrate this solution by my function in Swift:
func getRandomLocation(forLocation location: CLLocation, withOffsetKM offset: Double) -> CLLocation {
let latDistance = (Double(arc4random()) / Double(UInt32.max)) * offset * 2.0 - offset
let longDistanceMax = sqrt(offset * offset - latDistance * latDistance)
let longDistance = (Double(arc4random()) / Double(UInt32.max)) * longDistanceMax * 2.0 - longDistanceMax
let lat: CLLocationDegrees = location.coordinate.latitude + latDistance / 110.574
let lng: CLLocationDegrees = location.coordinate.longitude + longDistance / (111.320 * cos(lat / .pi / 180))
return CLLocation(latitude: lat, longitude: lng)
}
In this function to convert distance I use following formulas:
latDistance / 110.574
longDistance / (111.320 * cos(lat / .pi / 180))
Extract a part of the filepath (a directory) in Python
In Python 3.4 you can use the pathlib module:
>>> from pathlib import Path
>>> p = Path('C:\Program Files\Internet Explorer\iexplore.exe')
>>> p.name
'iexplore.exe'
>>> p.suffix
'.exe'
>>> p.root
'\\'
>>> p.parts
('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')
>>> p.relative_to('C:\Program Files')
WindowsPath('Internet Explorer/iexplore.exe')
>>> p.exists()
True
How to add Headers on RESTful call using Jersey Client API
This snippet works fine, for sending the Bearer Token using Jersey Client.
WebTarget webTarget = client.target("endpoint");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
invocationBuilder.header("Authorization", "Bearer "+"Api Key");
Response response = invocationBuilder.get();
String responseData = response.readEntity(String.class);
System.out.println(response.getStatus());
System.out.println("responseData "+responseData);
mysql error 2005 - Unknown MySQL server host 'localhost'(11001)
I have passed through that error today and did everything described above but didn't work for me. So I decided to view the core problem and logged onto the MySQL root folder in Windows 7 and did this solution:
Go to folder:
C:\AppServ\MySQL
Right click and Run as Administrator these files:
mysql_servicefix.bat
mysql_serviceinstall.bat
mysql_servicestart.bat
Then close the entire explorer window and reopen it or clear cache then login to phpMyAdmin again.
Explanation of "ClassCastException" in Java
Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
Cast the String "1" to an int -> no problem
Cast the String "abc" to an int -> raises a ClassCastException
Or think of a class diagram with Animal.class, Dog.class and Cat.class
Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because its a dog.
Cat c = (Dog) a; // Raises class cast exception; you can't cast a dog to a cat.
Convert Mercurial project to Git
I had a similar task to do, but it contained some aspects that were not sufficiently covered by the other answers here:
- I wanted to convert all (in my case: two, or in general: more than one) branches of my repo.
- I had non-ASCII and (being a Windows user) non-UTF8-encoded characters (for the curious: German umlaute) in my commit messages and file names.
I did not try fast-export and hg-fast-export, since they require that you have Python and some Mercurial Python modules on your machine, which I didn't have.
I did try hg-init with TortoiseHG, and this answer gave me a good start. But it looked like it only converts the current branch, not all at once (*). So I read the hg-init docs and this blog post and added
[git]
branch_bookmark_suffix=_bookmark
to my mercurial.ini, and did
hg bookmarks -r default master
hg bookmarks -r my_branch my_branch_bookmark
hg gexport
(Repeat the 2nd line for every branch you want to convert, and repeat it again if you should happen to do another commit before executing the 3rd line). This creates a folder git
within .hg
, which turns out to be a bare Git repo with all the exported branches. I could clone this repo and had a working copy as desired.
Or almost...
Running
git status
on my working copy showed all files with non-ASCII characters in their names as untracked files. So I continued researching and followed this advice:
git rm -rf --cached \*
git add --all
git commit
And finally the repo was ready to be pushed up to Bitbucket :-)
I also tried the Github importer as mentioned in this answer. I used Bitbucket as the source system, and Github did quite a good job, i.e. it converted all branches automatically. However, it showed '?'-characters for all non-ASCII characters in my commit messages (Web-UI and locally) and filenames (Web-UI only), and while I could fix the filenames as described above, I had no idea what to do with the commit messages, and so I'd prefer the hg-init approach. Without the encoding issue the Github importer would have been a perfect and fast solution (as long as you have a paid Github account or can tolerate that your repo is public for as long as it takes to pull it from Github to your local machine).
(*) So it looked like before I discovered that I have to bookmark all the branches I want to export. If you do and push to a bare (!) repo, like the linked answer says, you get all the branches.
How to find all occurrences of a substring?
Here's a (very inefficient) way to get all (i.e. even overlapping) matches:
>>> string = "test test test test"
>>> [i for i in range(len(string)) if string.startswith('test', i)]
[0, 5, 10, 15]
c# search string in txt file
With LINQ, you could use the SkipWhile
/ TakeWhile
methods, like this:
var importantLines =
File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.TakeWhile(line => !line.Contains("CustomerCh"));
Spring JPA selecting specific columns
In my opinion this is great solution:
interface PersonRepository extends Repository<Person, UUID> {
<T> Collection<T> findByLastname(String lastname, Class<T> type);
}
and using it like so
void someMethod(PersonRepository people) {
Collection<Person> aggregates =
people.findByLastname("Matthews", Person.class);
Collection<NamesOnly> aggregates =
people.findByLastname("Matthews", NamesOnly.class);
}
In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?
== Equality operator evaluates the arguments after converting them to numbers.
So string zero "0" is converted to Number data type and boolean false is converted to Number 0.
So
"0" == false // true
Same applies to `
false == "0" //true
=== Strict equality check evaluates the arguments with the original data type
"0" === false // false, because "0" is a string and false is boolean
Same applies to
false === "0" // false
In
if("0") console.log("ha");
The String "0" is not comparing with any arguments, and string is a true value until or unless it is compared with any arguments.
It is exactly like
if(true) console.log("ha");
But
if (0) console.log("ha"); // empty console line, because 0 is false
`
How to add buttons at top of map fragment API v2 layout
Maybe a simpler solution is to set an overlay in front of your map using FrameLayout
or RelativeLayout
and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapActivity" >
<fragment xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scrollbars="vertical"
class="com.google.android.gms.maps.SupportMapFragment"/>
<RadioGroup
android:id="@+id/radio_group_list_selector"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:background="#80000000"
android:padding="4dp" >
<RadioButton
android:id="@+id/radioPopular"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="@string/Popular"
android:gravity="center_horizontal|center_vertical"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioAZ"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/AZ"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton2"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioCategory"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/Category"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton2"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioNearBy"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/NearBy"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton3"
android:textColor="@color/textcolor_radiobutton" />
</RadioGroup>
</FrameLayout>
How to submit an HTML form without redirection
In order to achieve what you want, you need to use jQuery Ajax as below:
$('#myForm').submit(function(e){
e.preventDefault();
$.ajax({
url: '/Car/Edit/17/',
type: 'post',
data:$('#myForm').serialize(),
success:function(){
// Whatever you want to do after the form is successfully submitted
}
});
});
Also try this one:
function SubForm(e){
e.preventDefault();
var url = $(this).closest('form').attr('action'),
data = $(this).closest('form').serialize();
$.ajax({
url: url,
type: 'post',
data: data,
success: function(){
// Whatever you want to do after the form is successfully submitted
}
});
}
Final solution
This worked flawlessly. I call this function from Html.ActionLink(...)
function SubForm (){
$.ajax({
url: '/Person/Edit/@Model.Id/',
type: 'post',
data: $('#myForm').serialize(),
success: function(){
alert("worked");
}
});
}
How to set conditional breakpoints in Visual Studio?
- Set a breakpoint as usual
- Right click on the breakpoint and select Condition
- You'll see a dialog that says "Breakpoint Condition"
- Put a condition in the field e.g. "i==5"
The breakpoint will only get hit when i is 5.
SQL Server 2008 Insert with WHILE LOOP
Assuming that ID
is an identity column:
INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32
Try to avoid loops with SQL. Try to think in terms of sets instead.
Font size relative to the user's screen resolution?
I've created a variant of https://stackoverflow.com/a/17845473/189411
where you can set min and max text size in relation of min and max size of box that you want "check" size. In addition you can check size of dom element different than box where you want apply text size.
You resize text between 19px and 25px on #size-2 element, based on 500px and 960px width of #size-2 element
resizeTextInRange(500,960,19,25,'#size-2');
You resize text between 13px and 20px on #size-1 element, based on 500px and 960px width of body element
resizeTextInRange(500,960,13,20,'#size-1','body');
complete code are there https://github.com/kiuz/sandbox-html-js-css/tree/gh-pages/text-resize-in-range-of-text-and-screen/src
function inRange (x,min,max) {
return Math.min(Math.max(x, min), max);
}
function resizeTextInRange(minW,maxW,textMinS,textMaxS, elementApply, elementCheck=0) {
if(elementCheck==0){elementCheck=elementApply;}
var ww = $(elementCheck).width();
var difW = maxW-minW;
var difT = textMaxS- textMinS;
var rapW = (ww-minW);
var out=(difT/100)*(rapW/(difW/100))+textMinS;
var normalizedOut = inRange(out, textMinS, textMaxS);
$(elementApply).css('font-size',normalizedOut+'px');
console.log(normalizedOut);
}
$(function () {
resizeTextInRange(500,960,19,25,'#size-2');
resizeTextInRange(500,960,13,20,'#size-1','body');
$(window).resize(function () {
resizeTextInRange(500,960,19,25,'#size-2');
resizeTextInRange(500,960,13,20,'#size-1','body');
});
});
Download and open PDF file using Ajax
This is how i solve this issue.
The answer of Jonathan Amend on this post helped me a lot.
The example below is simplified.
For more details, the above source code is able to download a file using a JQuery Ajax request (GET, POST, PUT etc). It, also, helps to upload parameters as JSON and to change the content type to application/json (my default).
The html source:
<form method="POST">
<input type="text" name="startDate"/>
<input type="text" name="endDate"/>
<input type="text" name="startDate"/>
<select name="reportTimeDetail">
<option value="1">1</option>
</select>
<button type="submit"> Submit</button>
</form>
A simple form with two input text, one select and a button element.
The javascript page source:
<script type="text/javascript" src="JQuery 1.11.0 link"></script>
<script type="text/javascript">
// File Download on form submition.
$(document).on("ready", function(){
$("form button").on("click", function (event) {
event.stopPropagation(); // Do not propagate the event.
// Create an object that will manage to download the file.
new AjaxDownloadFile({
url: "url that returns a file",
data: JSON.stringify($("form").serializeObject())
});
return false; // Do not submit the form.
});
});
</script>
A simple event on button click. It creates an AjaxDownloadFile object. The AjaxDownloadFile class source is below.
The AjaxDownloadFile class source:
var AjaxDownloadFile = function (configurationSettings) {
// Standard settings.
this.settings = {
// JQuery AJAX default attributes.
url: "",
type: "POST",
headers: {
"Content-Type": "application/json; charset=UTF-8"
},
data: {},
// Custom events.
onSuccessStart: function (response, status, xhr, self) {
},
onSuccessFinish: function (response, status, xhr, self, filename) {
},
onErrorOccured: function (response, status, xhr, self) {
}
};
this.download = function () {
var self = this;
$.ajax({
type: this.settings.type,
url: this.settings.url,
headers: this.settings.headers,
data: this.settings.data,
success: function (response, status, xhr) {
// Start custom event.
self.settings.onSuccessStart(response, status, xhr, self);
// Check if a filename is existing on the response headers.
var filename = "";
var disposition = xhr.getResponseHeader("Content-Disposition");
if (disposition && disposition.indexOf("attachment") !== -1) {
var filenameRegex = /filename[^;=\n]*=(([""]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1])
filename = matches[1].replace(/[""]/g, "");
}
var type = xhr.getResponseHeader("Content-Type");
var blob = new Blob([response], {type: type});
if (typeof window.navigator.msSaveBlob !== "undefined") {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed.
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// Use HTML5 a[download] attribute to specify filename.
var a = document.createElement("a");
// Safari doesn"t support this yet.
if (typeof a.download === "undefined") {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () {
URL.revokeObjectURL(downloadUrl);
}, 100); // Cleanup
}
// Final custom event.
self.settings.onSuccessFinish(response, status, xhr, self, filename);
},
error: function (response, status, xhr) {
// Custom event to handle the error.
self.settings.onErrorOccured(response, status, xhr, self);
}
});
};
// Constructor.
{
// Merge settings.
$.extend(this.settings, configurationSettings);
// Make the request.
this.download();
}
};
I created this class to added to my JS library. It is reusable. Hope that helps.
How to find the Vagrant IP?
run:
vagrant ssh-config > .ssh.config
and then in config/deploy.rb
role :web, "default"
role :app, "default"
set :use_sudo, true
set :user, 'root'
set :run_method, :sudo
# Must be set for the password prompt from git to work
default_run_options[:pty] = true
ssh_options[:forward_agent] = true
ssh_options[:config] = '.ssh.config'
How do you calculate the variance, median, and standard deviation in C++ or Java?
public class Statistics {
double[] data;
int size;
public Statistics(double[] data) {
this.data = data;
size = data.length;
}
double getMean() {
double sum = 0.0;
for(double a : data)
sum += a;
return sum/size;
}
double getVariance() {
double mean = getMean();
double temp = 0;
for(double a :data)
temp += (a-mean)*(a-mean);
return temp/(size-1);
}
double getStdDev() {
return Math.sqrt(getVariance());
}
public double median() {
Arrays.sort(data);
if (data.length % 2 == 0)
return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
return data[data.length / 2];
}
}
How to calculate number of days between two dates
I made a quick re-usable function in ES6 using Moment.js.
_x000D_
_x000D_
const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {_x000D_
const getDateAsArray = (date) => {_x000D_
return moment(date.split(/\D+/), date_format);_x000D_
}_x000D_
return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;_x000D_
}_x000D_
_x000D_
console.log(getDaysDiff('2019-10-01', '2019-10-30'));_x000D_
console.log(getDaysDiff('2019/10/01', '2019/10/30'));_x000D_
console.log(getDaysDiff('2019.10-01', '2019.10 30'));_x000D_
console.log(getDaysDiff('2019 10 01', '2019 10 30'));_x000D_
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));_x000D_
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));_x000D_
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));_x000D_
_x000D_
console.log(getDaysDiff('10-01-2019', '10-30-2019'));_x000D_
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
_x000D_
_x000D_
_x000D_
How to add column to numpy array
It can be done like this:
import numpy as np
# create a random matrix:
A = np.random.normal(size=(5,2))
# add a column of zeros to it:
print(np.hstack((A,np.zeros((A.shape[0],1)))))
In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.
How to design RESTful search/filtering?
Don't fret too much if your initial API is fully RESTful or not (specially when you are just in the alpha stages). Get the back-end plumbing to work first. You can always do some sort of URL transformation/re-writing to map things out, refining iteratively until you get something stable enough for widespread testing ("beta").
You can define URIs whose parameters are encoded by position and convention on the URIs themselves, prefixed by a path you know you'll always map to something. I don't know PHP, but I would assume that such a facility exists (as it exists in other languages with web frameworks):
.ie. Do a "user" type of search with param[i]=value[i] for i=1..4 on store #1 (with value1,value2,value3,... as a shorthand for URI query parameters):
1) GET /store1/search/user/value1,value2,value3,value4
or
2) GET /store1/search/user,value1,value2,value3,value4
or as follows (though I would not recommend it, more on that later)
3) GET /search/store1,user,value1,value2,value3,value4
With option 1, you map all URIs prefixed with /store1/search/user
to the search handler (or whichever the PHP designation) defaulting to do searches for resources under store1 (equivalent to /search?location=store1&type=user
.
By convention documented and enforced by the API, parameters values 1 through 4 are separated by commas and presented in that order.
Option 2 adds the search type (in this case user
) as positional parameter #1. Either option is just a cosmetic choice.
Option 3 is also possible, but I don't think I would like it. I think the ability of search within certain resources should be presented in the URI itself preceding the search itself (as if indicating clearly in the URI that the search is specific within the resource.)
The advantage of this over passing parameters on the URI is that the search is part of the URI (thus treating a search as a resource, a resource whose contents can - and will - change over time.) The disadvantage is that parameter order is mandatory.
Once you do something like this, you can use GET, and it would be a read-only resource (since you can't POST or PUT to it - it gets updated when it's GET'ed). It would also be a resource that only comes to exist when it is invoked.
One could also add more semantics to it by caching the results for a period of time or with a DELETE causing the cache to be deleted. This, however, might run counter to what people typically use DELETE for (and because people typically control caching with caching headers.)
How you go about it would be a design decision, but this would be the way I'd go about. It is not perfect, and I'm sure there will be cases where doing this is not the best thing to do (specially for very complex search criteria).
file_get_contents() how to fix error "Failed to open stream", "No such file"
Why don't you use cURL
?
$yourkey="your api key";
$url="https://prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=$yourkey";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$auth = curl_exec($curl);
if($auth)
{
$json = json_decode($auth);
print_r($json);
}
}
Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
error: function returns address of local variable
a
is an array local to the function.Once the function returns it does not exist anymore and hence you should not return the address of a local variable.
In other words the lifetime of a
is within the scope({
,}
) of the function and if you return a pointer to it what you have is a pointer pointing to some memory which is not valid. Such variables are also called automatic variabels because their lifetime is automatically managed you do not need to manage it explicitly.
Since you need to extend the variable to persist beyond the scope of the function you You need to allocate a array on heap and return a pointer to it.
char *a = malloc(1000);
This way the array a
resides in memory untill you call a free()
on the same address.
Do not forget to do so or you end up with a memory leak.
Could not autowire field:RestTemplate in Spring boot application
Please make sure two things:
1- Use @Bean
annotation with the method.
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
2- Scope of this method should be public not private.
Complete Example -
@Service
public class MakeHttpsCallImpl implements MakeHttpsCall {
@Autowired
private RestTemplate restTemplate;
@Override
public String makeHttpsCall() {
return restTemplate.getForObject("https://localhost:8085/onewayssl/v1/test",String.class);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
}
Newline in string attribute
Maybe someone prefers
<TextBlock Text="{Binding StringFormat='Stuff on line1{0}Stuff on line2{0}Stuff on line3',
Source={x:Static s:Environment.NewLine}}" />
with xmlns:s="clr-namespace:System;assembly=mscorlib"
.
Adding images or videos to iPhone Simulator
I just needed some random images for testing, so this is how I did it.
I have the simplest solution in the world. Just open Safari in the simulator, go to Google images (or your own web or Dropbox URL), view an image, hold down the mouse button for 2 seconds, and you'll see "Save Image" - it will save right into the Photos library. Rinse and repeat.
retrieve links from web page using python and BeautifulSoup
Here's an example using @ars accepted answer and the BeautifulSoup4
, requests
, and wget
modules to handle the downloads.
import requests
import wget
import os
from bs4 import BeautifulSoup, SoupStrainer
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/eeg-mld/eeg_full/'
file_type = '.tar.gz'
response = requests.get(url)
for link in BeautifulSoup(response.content, 'html.parser', parse_only=SoupStrainer('a')):
if link.has_attr('href'):
if file_type in link['href']:
full_path = url + link['href']
wget.download(full_path)
How to send an email with Gmail as provider using Python?
great answer from @David, here is for Python 3 without the generic try-except:
def send_email(user, password, recipient, subject, body):
gmail_user = user
gmail_pwd = password
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
How do I find the PublicKeyToken for a particular dll?
As @CRice said you can use the below method to get a list of dependent assembly with publicKeyToken
public static int DependencyInfo(string args)
{
Console.WriteLine(Assembly.LoadFile(args).FullName);
Console.WriteLine(Assembly.LoadFile(args).GetCustomAttributes(typeof(System.Runtime.Versioning.TargetFrameworkAttribute), false).SingleOrDefault());
try {
var assemblies = Assembly.LoadFile(args).GetReferencedAssemblies();
if (assemblies.GetLength(0) > 0)
{
foreach (var assembly in assemblies)
{
Console.WriteLine(" - " + assembly.FullName + ", ProcessorArchitecture=" + assembly.ProcessorArchitecture);
}
return 0;
}
}
catch(Exception e) {
Console.WriteLine("An exception occurred: {0}", e.Message);
return 1;
}
finally{}
return 1;
}
i generally use it as a LinqPad script
you can call it as
DependencyInfo("@c:\MyAssembly.dll");
from the code
how do I insert a column at a specific column index in pandas?
Here is a very simple answer to this(only one line).
You can do that after you added the 'n' column into your df as follows.
import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0
df
l v n
0 a 1 0
1 b 2 0
2 c 1 0
3 d 2 0
# here you can add the below code and it should work.
df = df[list('nlv')]
df
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
However, if you have words in your columns names instead of letters. It should include two brackets around your column names.
import pandas as pd
df = pd.DataFrame({'Upper':['a','b','c','d'], 'Lower':[1,2,1,2]})
df['Net'] = 0
df['Mid'] = 2
df['Zsore'] = 2
df
Upper Lower Net Mid Zsore
0 a 1 0 2 2
1 b 2 0 2 2
2 c 1 0 2 2
3 d 2 0 2 2
# here you can add below line and it should work
df = df[list(('Mid','Upper', 'Lower', 'Net','Zsore'))]
df
Mid Upper Lower Net Zsore
0 2 a 1 0 2
1 2 b 2 0 2
2 2 c 1 0 2
3 2 d 2 0 2
How to get selected option using Selenium WebDriver with Java
On the following option:
WebElement option = select.getFirstSelectedOption();
option.getText();
If from the method getText()
you get a blank, you can get the string from the value of the option using the method getAttribute
:
WebElement option = select.getFirstSelectedOption();
option.getAttribute("value");
What is base 64 encoding used for?
From http://en.wikipedia.org/wiki/Base64
The term Base64 refers to a specific MIME content transfer encoding.
It is also used as a generic term for any similar encoding scheme that
encodes binary data by treating it numerically and translating it into
a base 64 representation. The particular choice of base is due to the
history of character set encoding: one can choose a set of 64
characters that is both part of the subset common to most encodings,
and also printable. This combination leaves the data unlikely to be
modified in transit through systems, such as email, which were
traditionally not 8-bit clean.
Base64 can be used in a variety of contexts:
- Evolution and Thunderbird use Base64 to obfuscate e-mail passwords[1]
- Base64 can be used to transmit and store text that might otherwise cause delimiter collision
Base64 is often used as a quick but insecure shortcut to obscure secrets without incurring the overhead of cryptographic key management
Spammers use Base64 to evade basic anti-spamming tools, which often do not decode Base64 and therefore cannot detect keywords in encoded
messages.
- Base64 is used to encode character strings in LDIF files
- Base64 is sometimes used to embed binary data in an XML file, using a syntax similar to ...... e.g.
Firefox's bookmarks.html.
- Base64 is also used when communicating with government Fiscal Signature printing devices (usually, over serial or parallel ports) to
minimize the delay when transferring receipt characters for signing.
- Base64 is used to encode binary files such as images within scripts, to avoid depending on external files.
- Can be used to embed raw image data into a CSS property such as background-image.
Math.random() versus Random.nextInt(int)
Here is the detailed explanation of why "Random.nextInt(n)
is both more efficient and less biased than Math.random() * n
" from the Sun forums post that Gili linked to:
Math.random() uses Random.nextDouble() internally.
Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).
Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.
Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.
Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.
You will be waiting a very long time rolling dice for this effect to show up.
Math.random() also requires about twice the processing and is subject to synchronization.
How to copy files from host to Docker container?
Copy from container to host dir
docker cp [container-name/id]:./app/[index.js] index.js
(assume you have created a workdir /app in your dockerfile)
Copy from host to container
docker cp index.js [container-name/id]:./app/index.js
How to disable logging on the standard error stream in Python?
Found an elegant solution using decorators, which addresses the following problem: what if you are writing a module with several functions, each of them with several debugging messages, and you want to disable logging in all functions but the one you are currently focusing on?
You can do it using decorators:
import logging, sys
logger = logging.getLogger()
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
def disable_debug_messages(func):
def wrapper(*args, **kwargs):
prev_state = logger.disabled
logger.disabled = True
result = func(*args, **kwargs)
logger.disabled = prev_state
return result
return wrapper
Then, you can do:
@disable_debug_messages
def function_already_debugged():
...
logger.debug("This message won't be showed because of the decorator")
...
def function_being_focused():
...
logger.debug("This message will be showed")
...
Even if you call function_already_debugged
from within function_being_focused
, debug messages from function_already_debugged
won't be showed.
This ensures you will see only the debug messages from the function you are focusing on.
Hope it helps!
Should methods in a Java interface be declared with or without a public access modifier?
The public modifier should be omitted in Java interfaces (in my opinion).
Since it does not add any extra information, it just draws attention away from the important stuff.
Most style-guides will recommend that you leave it out, but of course, the most important thing is to be consistent across your codebase, and especially for each interface. The following example could easily confuse someone, who is not 100% fluent in Java:
public interface Foo{
public void MakeFoo();
void PerformBar();
}
How to copy data from another workbook (excel)?
Would you be happy to make "my file.xls" active if it didn't affect the screen? Turning off screen updating is the way to achieve this, it also has performance improvements (significant if you are doing looping while switching around worksheets / workbooks).
The command to do this is:
Application.ScreenUpdating = False
Don't forget to turn it back to True
when your macros is finished.
Mod in Java produces negative numbers
The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.
You can find the positive value by doing this:
int i = (((-1 % 2) + 2) % 2)
or this:
int i = -1 % 2;
if (i<0) i += 2;
(obviously -1 or 2 can be whatever you want the numerator or denominator to be)
How to check ASP.NET Version loaded on a system?
You can use
<%
Response.Write("Version: " + System.Environment.Version.ToString());
%>
That will get the currently running version. You can check the registry for all installed versions at:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET
Framework Setup\NDP
Convert line endings
Doing this with POSIX is tricky:
POSIX Sed does not support \r
or \15
. Even if it did, the in place
option -i
is not POSIX
POSIX Awk does support \r
and \15
, however the -i inplace
option
is not POSIX
d2u and dos2unix are not POSIX utilities, but ex is
POSIX ex does not support \r
, \15
, \n
or \12
To remove carriage returns:
awk 'BEGIN{RS="^$";ORS="";getline;gsub("\r","");print>ARGV[1]}' file
To add carriage returns:
awk 'BEGIN{RS="^$";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file
how to add value to combobox item
If you want to use SelectedValue then your combobox must be databound.
To set up the combobox:
ComboBox1.DataSource = GetMailItems()
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
To get the data:
Function GetMailItems() As List(Of MailItem)
Dim mailItems = New List(Of MailItem)
Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection)
Command.CommandTimeout = 30
Reader = Command.ExecuteReader()
If Reader.HasRows = True Then
While Reader.Read()
mailItems.Add(New MailItem(Reader("ID"), Reader("name")))
End While
End If
Return mailItems
End Function
Public Class MailItem
Public Sub New(ByVal id As Integer, ByVal name As String)
mID = id
mName = name
End Sub
Private mID As Integer
Public Property ID() As Integer
Get
Return mID
End Get
Set(ByVal value As Integer)
mID = value
End Set
End Property
Private mName As String
Public Property Name() As String
Get
Return mName
End Get
Set(ByVal value As String)
mName = value
End Set
End Property
End Class
Script parameters in Bash
If you're not completely attached to using "from" and "to" as your option names, it's fairly easy to implement this using getopts:
while getopts f:t: opts; do
case ${opts} in
f) FROM_VAL=${OPTARG} ;;
t) TO_VAL=${OPTARG} ;;
esac
done
getopts
is a program that processes command line arguments and conveniently parses them for you.
f:t:
specifies that you're expecting 2 parameters that contain values (indicated by the colon). Something like f:t:v
says that -v
will only be interpreted as a flag.
opts
is where the current parameter is stored. The case
statement is where you will process this.
${OPTARG}
contains the value following the parameter. ${FROM_VAL}
for example will get the value /home/kristoffer/test.png
if you ran your script like:
ocrscript.sh -f /home/kristoffer/test.png -t /home/kristoffer/test.txt
As the others are suggesting, if this is your first time writing bash scripts you should really read up on some basics. This was just a quick tutorial on how getopts
works.
Is there a Google Sheets formula to put the name of the sheet into a cell?
You have 2 options, and I am not sure if I am a fan of either of them, but that is my opinion. You may feel differently:
Option 1: Force the function to run.
A function in a cell does not run unless it references a cell that has changed. Changing a sheet name does not trigger any functions in the spreadsheet. But we can force the function to run by passing a range to it and whenever an item in that range changes, the function will trigger.
You can use the below script to create a custom function which will retrieve the name:
function mySheetName() {
var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
return key;
}
and in the cell place the following:
=mySheetName(A1:Z)
Now if any value in a cell in that passed range changes the script will run. This takes a second to run the script and sets a message in the cell each time any value is changed so this could become annoying very quickly. As already mentioned, it also requires a change in the range to cause it to trigger, so not really helpful on a fairly static file.
Option 2: Use the OnChange Event
While the run time feels better than the above option, and this does not depend on a value changing in the spreadsheet's cells, I do not like this because it forces where the name goes. You could use a Utilities sheet to define this location in various sheets if you wish. Below is the basic idea and may get you started if you like this option.
The OnChange event is triggered when the sheet name is changed. You can make the code below more sophisticated to check for errors, check the sheet ID to only work on a given sheet, etc. The basic code, however, is:
function setSheetName(e) {
var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange('K1').setValue(key);
}
Once you have saved the code, in the script editor set the Current Project's On Change Trigger to this function. It will write the sheet name to cell K1 on any change event. To set the trigger, select Current project's triggers under the Edit menu.
What is the connection string for localdb for version 11
1) Requires .NET framework 4 updated to at least 4.0.2. If you have 4.0.2, then you should have
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\SKUs\.NETFramework,Version=v4.0.2
If you have installed latest VS 2012 chances are that you already have 4.0.2. Just verify first.
2) Next you need to have an instance of LocalDb
. By default you have an instance whose name is a single v
character followed by the LocalDB release version number in the format xx.x. For example, v11.0
represents SQL Server 2012. Automatic instances are public by default. You can also have named instances which are private. Named instances provide isolation from other instances and can improve performance by reducing resource contention with other database users. You can check the status of instances using the SqlLocalDb.exe
utility (run it from command line).
3) Next your connection string should look like:
"Server=(localdb)\\v11.0;Integrated Security=true;"
or
"Data Source=(localdb)\\test;Integrated Security=true;"
from your code. They both are the same. Notice the two \\
required because \v
and \t
means special characters. Also note that what appears after (localdb)\\
is the name of your LocalDb instance. v11.0
is the default public instance, test
is something I have created manually which is private.
If you have a database (.mdf file) already:
"Server=(localdb)\\Test;Integrated Security=true;AttachDbFileName= myDbFile;"
If you don't have a Sql Server database:
"Server=(localdb)\\v11.0;Integrated Security=true;"
And you can create your own database programmatically:
a) to save it in the default location with default setting:
var query = "CREATE DATABASE myDbName;";
b) To save it in a specific location with your own custom settings:
// your db name
string dbName = "myDbName";
// path to your db files:
// ensure that the directory exists and you have read write permission.
string[] files = { Path.Combine(Application.StartupPath, dbName + ".mdf"),
Path.Combine(Application.StartupPath, dbName + ".ldf") };
// db creation query:
// note that the data file and log file have different logical names
var query = "CREATE DATABASE " + dbName +
" ON PRIMARY" +
" (NAME = " + dbName + "_data," +
" FILENAME = '" + files[0] + "'," +
" SIZE = 3MB," +
" MAXSIZE = 10MB," +
" FILEGROWTH = 10%)" +
" LOG ON" +
" (NAME = " + dbName + "_log," +
" FILENAME = '" + files[1] + "'," +
" SIZE = 1MB," +
" MAXSIZE = 5MB," +
" FILEGROWTH = 10%)" +
";";
And execute!
A sample table can be loaded into the database with something like:
@"CREATE TABLE supportContacts
(
id int identity primary key,
type varchar(20),
details varchar(30)
);
INSERT INTO supportContacts
(type, details)
VALUES
('Email', '[email protected]'),
('Twitter', '@sqlfiddle');";
Note that SqlLocalDb.exe
utility doesnt give you access to databases, you separately need sqlcmd
utility which is sad..
EDIT: moved position of semicolon otherwise error would occur if code was copy/pasted
Use of Finalize/Dispose method in C#
1) WebClient is a managed type, so you don't need a finalizer. The finalizer is needed in the case your users don't Dispose() of your NoGateway class and the native type (which is not collected by the GC) needs to be cleaned up after. In this case, if the user doesn't call Dispose(), the contained WebClient will be disposed by the GC right after the NoGateway does.
2) Indirectly yes, but you shouldn't have to worry about it. Your code is correct as stands and you cannot prevent your users from forgetting to Dispose() very easily.
How to change values in a tuple?
You can change the value of tuple using copy by reference
>>> tuple1=[20,30,40]
>>> tuple2=tuple1
>>> tuple2
[20, 30, 40]
>>> tuple2[1]=10
>>> print(tuple2)
[20, 10, 40]
>>> print(tuple1)
[20, 10, 40]
Iterator over HashMap in Java
Using EntrySet() and for each loop
for(Map.Entry<String, String> entry: hashMap.entrySet()) {
System.out.println("Key Of map = "+ entry.getKey() +
" , value of map = " + entry.getValue() );
}
Using keyset() and for each loop
for(String key : hashMap.keySet()) {
System.out.println("Key Of map = "+ key + " ,
value of map = " + hashMap.get(key) );
}
Using EntrySet() and java Iterator
for(String key : hashMap.keySet()) {
System.out.println("Key Of map = "+ key + " ,
value of map = " + hashMap.get(key) );
}
Using keyset() and java Iterator
Iterator<String> keysIterator = keySet.iterator();
while (keysIterator.hasNext()) {
String key = keysIterator.next();
System.out.println("Key Of map = "+ key + " , value of map = " + hashMap.get(key) );
}
Reference : How to iterate over Map or HashMap in java
How to "set a breakpoint in malloc_error_break to debug"
Set a breakpoint on malloc_error_break() by opening the Breakpoint Navigator (View->Navigators->Show Breakpoint Navigator or ?8), clicking the plus button in the lower left corner, and selecting "Add Symbolic Breakpoint". In the popup that comes up, enter malloc_error_break
in the Symbol field, then click Done.
EDIT: openfrog added a screenshot and indicated that he's already tried these steps without success after I posted my answer. With that edit, I'm not sure what to say. I haven't seen that fail to work myself, and indeed I always keep a breakpoint on malloc_error_break set.
Writing your own square root function
Depending on your needs, a simple divide-and-conquer strategy can be used. It won't converge as fast as some other methods but it may be a lot easier for a novice to understand. In addition, since it's an O(log n) algorithm (halving the search space each iteration), the worst case for a 32-bit float will be 32 iterations.
Let's say you want the square root of 62.104. You pick a value halfway between 0 and that, and square it. If the square is higher than your number, you need to concentrate on numbers less than the midpoint. If it's too low, concentrate on those higher.
With real math, you could keep dividing the search space in two forever (if it doesn't have a rational square root). In reality, computers will eventually run out of precision and you'll have your approximation. The following C program illustrates the point:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
float val, low, high, mid, oldmid, midsqr;
int step = 0;
// Get argument, force to non-negative.
if (argc < 2) {
printf ("Usage: sqrt <number>\n");
return 1;
}
val = fabs (atof (argv[1]));
// Set initial bounds and print heading.
low = 0;
high = mid = val;
oldmid = -1;
printf ("%4s %10s %10s %10s %10s %10s %s\n",
"Step", "Number", "Low", "High", "Mid", "Square", "Result");
// Keep going until accurate enough.
while (fabs(oldmid - mid) >= 0.00001) {
oldmid = mid;
// Get midpoint and see if we need lower or higher.
mid = (high + low) / 2;
midsqr = mid * mid;
printf ("%4d %10.4f %10.4f %10.4f %10.4f %10.4f ",
++step, val, low, high, mid, midsqr);
if (mid * mid > val) {
high = mid;
printf ("- too high\n");
} else {
low = mid;
printf ("- too low\n");
}
}
// Desired accuracy reached, print it.
printf ("sqrt(%.4f) = %.4f\n", val, mid);
return 0;
}
Here's a couple of runs so you hopefully get an idea how it works. For 77:
pax> sqrt 77
Step Number Low High Mid Square Result
1 77.0000 0.0000 77.0000 38.5000 1482.2500 - too high
2 77.0000 0.0000 38.5000 19.2500 370.5625 - too high
3 77.0000 0.0000 19.2500 9.6250 92.6406 - too high
4 77.0000 0.0000 9.6250 4.8125 23.1602 - too low
5 77.0000 4.8125 9.6250 7.2188 52.1104 - too low
6 77.0000 7.2188 9.6250 8.4219 70.9280 - too low
7 77.0000 8.4219 9.6250 9.0234 81.4224 - too high
8 77.0000 8.4219 9.0234 8.7227 76.0847 - too low
9 77.0000 8.7227 9.0234 8.8730 78.7310 - too high
10 77.0000 8.7227 8.8730 8.7979 77.4022 - too high
11 77.0000 8.7227 8.7979 8.7603 76.7421 - too low
12 77.0000 8.7603 8.7979 8.7791 77.0718 - too high
13 77.0000 8.7603 8.7791 8.7697 76.9068 - too low
14 77.0000 8.7697 8.7791 8.7744 76.9893 - too low
15 77.0000 8.7744 8.7791 8.7767 77.0305 - too high
16 77.0000 8.7744 8.7767 8.7755 77.0099 - too high
17 77.0000 8.7744 8.7755 8.7749 76.9996 - too low
18 77.0000 8.7749 8.7755 8.7752 77.0047 - too high
19 77.0000 8.7749 8.7752 8.7751 77.0022 - too high
20 77.0000 8.7749 8.7751 8.7750 77.0009 - too high
21 77.0000 8.7749 8.7750 8.7750 77.0002 - too high
22 77.0000 8.7749 8.7750 8.7750 76.9999 - too low
23 77.0000 8.7750 8.7750 8.7750 77.0000 - too low
sqrt(77.0000) = 8.7750
For 62.104:
pax> sqrt 62.104
Step Number Low High Mid Square Result
1 62.1040 0.0000 62.1040 31.0520 964.2267 - too high
2 62.1040 0.0000 31.0520 15.5260 241.0567 - too high
3 62.1040 0.0000 15.5260 7.7630 60.2642 - too low
4 62.1040 7.7630 15.5260 11.6445 135.5944 - too high
5 62.1040 7.7630 11.6445 9.7037 94.1628 - too high
6 62.1040 7.7630 9.7037 8.7334 76.2718 - too high
7 62.1040 7.7630 8.7334 8.2482 68.0326 - too high
8 62.1040 7.7630 8.2482 8.0056 64.0895 - too high
9 62.1040 7.7630 8.0056 7.8843 62.1621 - too high
10 62.1040 7.7630 7.8843 7.8236 61.2095 - too low
11 62.1040 7.8236 7.8843 7.8540 61.6849 - too low
12 62.1040 7.8540 7.8843 7.8691 61.9233 - too low
13 62.1040 7.8691 7.8843 7.8767 62.0426 - too low
14 62.1040 7.8767 7.8843 7.8805 62.1024 - too low
15 62.1040 7.8805 7.8843 7.8824 62.1323 - too high
16 62.1040 7.8805 7.8824 7.8815 62.1173 - too high
17 62.1040 7.8805 7.8815 7.8810 62.1098 - too high
18 62.1040 7.8805 7.8810 7.8807 62.1061 - too high
19 62.1040 7.8805 7.8807 7.8806 62.1042 - too high
20 62.1040 7.8805 7.8806 7.8806 62.1033 - too low
21 62.1040 7.8806 7.8806 7.8806 62.1038 - too low
22 62.1040 7.8806 7.8806 7.8806 62.1040 - too high
23 62.1040 7.8806 7.8806 7.8806 62.1039 - too high
sqrt(62.1040) = 7.8806
For 49:
pax> sqrt 49
Step Number Low High Mid Square Result
1 49.0000 0.0000 49.0000 24.5000 600.2500 - too high
2 49.0000 0.0000 24.5000 12.2500 150.0625 - too high
3 49.0000 0.0000 12.2500 6.1250 37.5156 - too low
4 49.0000 6.1250 12.2500 9.1875 84.4102 - too high
5 49.0000 6.1250 9.1875 7.6562 58.6182 - too high
6 49.0000 6.1250 7.6562 6.8906 47.4807 - too low
7 49.0000 6.8906 7.6562 7.2734 52.9029 - too high
8 49.0000 6.8906 7.2734 7.0820 50.1552 - too high
9 49.0000 6.8906 7.0820 6.9863 48.8088 - too low
10 49.0000 6.9863 7.0820 7.0342 49.4797 - too high
11 49.0000 6.9863 7.0342 7.0103 49.1437 - too high
12 49.0000 6.9863 7.0103 6.9983 48.9761 - too low
13 49.0000 6.9983 7.0103 7.0043 49.0598 - too high
14 49.0000 6.9983 7.0043 7.0013 49.0179 - too high
15 49.0000 6.9983 7.0013 6.9998 48.9970 - too low
16 49.0000 6.9998 7.0013 7.0005 49.0075 - too high
17 49.0000 6.9998 7.0005 7.0002 49.0022 - too high
18 49.0000 6.9998 7.0002 7.0000 48.9996 - too low
19 49.0000 7.0000 7.0002 7.0001 49.0009 - too high
20 49.0000 7.0000 7.0001 7.0000 49.0003 - too high
21 49.0000 7.0000 7.0000 7.0000 49.0000 - too low
22 49.0000 7.0000 7.0000 7.0000 49.0001 - too high
23 49.0000 7.0000 7.0000 7.0000 49.0000 - too high
sqrt(49.0000) = 7.0000
Python strftime - date without leading 0?
Take a look at -
bellow:
>>> from datetime import datetime
>>> datetime.now().strftime('%d-%b-%Y')
>>> '08-Oct-2011'
>>> datetime.now().strftime('%-d-%b-%Y')
>>> '8-Oct-2011'
>>> today = datetime.date.today()
>>> today.strftime('%d-%b-%Y')
>>> print(today)
Two Radio Buttons ASP.NET C#
I can see it's an old question, if you want to put other HTML inside could use the radiobutton with GroupName propery same in all radiobuttons and in the Text property set something like an image or the html you need.
<asp:RadioButton GroupName="group1" runat="server" ID="paypalrb" Text="<img src='https://www.paypalobjects.com/webstatic/mktg/logo/bdg_secured_by_pp_2line.png' border='0' alt='Secured by PayPal' style='width: 103px; height: 61px; padding:10px;'>" />