on OSX assure you have launched the Docker application before issuing
docker ps
or docker build
... etc ... yes it seems strange and somewhat misleading that issuing
docker --version
gives version even though the docker daemon is not running ... ditto for those other version cmds ... I just encountered exactly the same symptoms ... this behavior on OSX is different from on linux
There exists an on-line tool called IETransformsTranslator. With this tool you can make matrix filter transforms what works on IE6,IE7 & IE8. Just paste you CSS3 transform functions (e.g. rotate(15deg) ) and it will do the rest. http://www.useragentman.com/IETransformsTranslator/
This won't be secure, and it's simple to explain why:
If you hash the password on the client side and use that token instead of the password, then an attacker will be unlikely to find out what the password is.
But, the attacker doesn't need to find out what the password is, because your server isn't expecting the password any more - it's expecting the token. And the attacker does know the token because it's being sent over unencrypted HTTP!
Now, it might be possible to hack together some kind of challenge/response form of encryption which means that the same password will produce a different token each request. However, this will require that the password is stored in a decryptable format on the server, something which isn't ideal, but might be a suitable compromise.
And finally, do you really want to require users to have javascript turned on before they can log into your website?
In any case, SSL is neither an expensive or especially difficult to set up solution any more
You can use this as well:
SELECT RTRIM (
XMLAGG (XMLELEMENT (e, country_name || ',')).EXTRACT ('//text()'),
',')
country_name
FROM countries;
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
There is a command
svn revert -R .
OR
you can use the --depth=infinity, which is actually same as above:
svn revert --depth=infinity
svn revert
is inherently dangerous, since its entire purpose is to throw away data—namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes
You get the cursor position by calling GetCursorPos
.
POINT p;
if (GetCursorPos(&p))
{
//cursor position now in p.x and p.y
}
This returns the cursor position relative to screen coordinates. Call ScreenToClient
to map to window coordinates.
if (ScreenToClient(hwnd, &p))
{
//p.x and p.y are now relative to hwnd's client area
}
You hide and show the cursor with ShowCursor
.
ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again
You must ensure that every call to hide the cursor is matched by one that shows it again.
by typing yes it wont charge taxes, by typing no it will charge taxes.
=IF(C39="Yes","0",IF(C39="no",PRODUCT(G36*0.0825)))
This code may be helpful for you.
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
Often times we are interested in calculating the full significant digits, but for the visual aesthetics, we may want to see only few decimal point when we display the dataframe.
In jupyter-notebook, pandas can utilize the html formatting taking advantage of the method called style
.
For the case of just seeing two significant digits of some columns, we can use this code snippet:
import numpy as np
import pandas as pd
df = pd.DataFrame({'var1': [1.458315, 1.576704, 1.629253, 1.6693310000000001, 1.705139, 1.740447, 1.77598, 1.812037, 1.85313, 1.9439849999999999],
'var2': [1.500092, 1.6084450000000001, 1.652577, 1.685456, 1.7120959999999998, 1.741961, 1.7708009999999998, 1.7993270000000001, 1.8229819999999999, 1.8684009999999998],
'var3': [-0.0057090000000000005, -0.005122, -0.0047539999999999995, -0.003525, -0.003134, -0.0012230000000000001, -0.0017230000000000001, -0.002013, -0.001396, 0.005732]})
print(df)
var1 var2 var3
0 1.458315 1.500092 -0.005709
1 1.576704 1.608445 -0.005122
2 1.629253 1.652577 -0.004754
3 1.669331 1.685456 -0.003525
4 1.705139 1.712096 -0.003134
5 1.740447 1.741961 -0.001223
6 1.775980 1.770801 -0.001723
7 1.812037 1.799327 -0.002013
8 1.853130 1.822982 -0.001396
9 1.943985 1.868401 0.005732
df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
Gives:
var1 var2 var3
id
0 1.46 1.50 -0.57%
1 1.58 1.61 -0.51%
2 1.63 1.65 -0.48%
3 1.67 1.69 -0.35%
4 1.71 1.71 -0.31%
5 1.74 1.74 -0.12%
6 1.78 1.77 -0.17%
7 1.81 1.80 -0.20%
8 1.85 1.82 -0.14%
9 1.94 1.87 0.57%
If display command is not found try following:
from IPython.display import display
df_style = df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
display(df_style)
display
command, you need to have installed Ipython in your machine.display
command does not work in online python interpreter which do not have IPyton
installed such as https://repl.it/languages/python3Visual Studio Community 2015 suffices to build extensions for Python 3.5. It's free but a 6 GB download (overkill). On my computer it installed vcvarsall at C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat
For Python 3.4 you'd need Visual Studio 2010. I don't think there's any free edition. See https://matthew-brett.github.io/pydagogue/python_msvc.html
For those who want to perform the same calculations with no additional software in Windows, here is the script for command line script:
set input=video.ts
ffmpeg -i "%input%" 2> output.tmp
rem search " Duration: HH:MM:SS.mm, start: NNNN.NNNN, bitrate: xxxx kb/s"
for /F "tokens=1,2,3,4,5,6 delims=:., " %%i in (output.tmp) do (
if "%%i"=="Duration" call :calcLength %%j %%k %%l %%m
)
goto :EOF
:calcLength
set /A s=%3
set /A s=s+%2*60
set /A s=s+%1*60*60
set /A VIDEO_LENGTH_S = s
set /A VIDEO_LENGTH_MS = s*1000 + %4
echo Video duration %1:%2:%3.%4 = %VIDEO_LENGTH_MS%ms = %VIDEO_LENGTH_S%s
Same answer posted here: How to crop last N seconds from a TS video
well, it is not really necessary to create a function for this when it can be done simply with 1 CSS class.
just wrap your text around this class and see the magic :D
<p style={{whiteSpace: 'pre-line'}}>my json text goes here \n\n</p>
note: because you will always present your text in frontend with HTML you can add the style={{whiteSpace: 'pre-line'}} to any tag, not just the p tag.
My implementation
import $ from 'jquery';
$(document).ready(() => {
$('#whatDescribesYouSelectInput').on('change', (e) => {
if (e.target.value === 'Other') {
$('#whatDescribesYouOtherInput').attr('type', 'text');
$('#specifyLabel').show();
} else {
$('#whatDescribesYouOtherInput').attr('type', 'hidden');
$('#specifyLabel').hide();
}
});
});
this is a example for Horizontal and Vertical alignment simultaneously
<View style={{width: 200, flexDirection: 'row',alignItems: 'center'}}>
<Text style={{width: '100%',textAlign: 'center'}} />
</View>
You should go to Control Panel -> Programs and Features, find Microsoft Visual Studio 2015 and select "Change". Visual Studio 2015 setup will start. Select "Modify".
In Visual Studio components list, open the list of sub-items and select "ClickOnce Publication Tools" and "Windows 10 SDK" too.
on the form2.buttonclick put
this.close();
form1 should have object of form2.
you need to subscribe Closing event of form2.
and in closing method put
this.close();
Yes:
Use this to experiment with mailto form elements and link encoding.
You can enter subject, body (i.e. content), etc. into the form, hit the button and see the mailto html link that you can paste into your page.
You can even specify elements that are rarely known and used: cc, bcc, from emails.
Just to help someone who get here... You should not use $parent.$index as it's not really safe. If you add an ng-if inside the loop, you get the $index messed!
Right way
<table>
<tr ng-repeat="row in rows track by $index" ng-init="rowIndex = $index">
<td ng-repeat="column in columns track by $index" ng-init="columnIndex = $index">
<b ng-if="rowIndex == columnIndex">[{{rowIndex}} - {{columnIndex}}]</b>
<small ng-if="rowIndex != columnIndex">[{{rowIndex}} - {{columnIndex}}]</small>
</td>
</tr>
</table>
Is there a more elegant way to write this code?
from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
dates_dict[key].append(date)
@
followed by a number is the parameters in the order they're listed in a function.
Add the following style to your h3
elements:
word-wrap: break-word;
This will cause the long URLs in them to wrap. The default setting for word-wrap is normal
, which will wrap only at a limited set of split tokens (e.g. whitespaces, hyphens), which are not present in a URL.
Deleting all instances of *.exd
resolved it for me.
this states that Account.deposit(Double.MAX_VALUE);
it is setting deposit value to MAX value of Double
dataType.to procced for running tests.
In SQL*Plus putting SET DEFINE ?
at the top of the script will normally solve this. Might work for Oracle SQL Developer as well.
Simply add height: 100%;
onto the #B2
styling. min-height
shouldn't be necessary.
In addition to @StephaneDelcroix's answer, before using:
git clone [email protected]/my-project.git .
make sure that your current dir is empty by using
ls -a
With MySQL 8+ the new default authentication is caching_sha2_password
instead of mysql_native_password
. The new and more secure authentication method is not supported by the native mysql
package yet, but you should consider using the package @mysql/xdevapi
instead, which is officially supported and maintained by Oracle.
To install the new package, run:
npm install @mysql/xdevapi --save --save-exact
To connect to the database and INSERT some VALUES:
const mysqlx = require('@mysql/xdevapi');
var myTable;
mysqlx
.getSession({
user: 'root',
password: '*****',
host: 'localhost',
port: 33060
})
.then(function (session) {
// Accessing an existing table
myTable = session.getSchema('Database_Name').getTable('Table_Name');
// Insert SQL Table data
return myTable
.insert(['first_name', 'last_name'])
.values(['John', 'Doe'])
.execute()
});
The official package documentation can be found here: https://dev.mysql.com/doc/dev/connector-nodejs/8.0/
You can do it using old DirectShow functionality.
This answer teaches you how to create QuartzTypeLib.dll
:
Run tlbimp tool (in your case path will be different):
Run TlbImp.exe %windir%\system32\quartz.dll /out:QuartzTypeLib.dll
Alternatively, this project contains the library interop.QuartzTypeLib.dll
, which is basically the same thing as steps 1. and 2. The following steps teach how to use this library:
Add generated QuartzTypeLib.dll as a COM-reference to your project (click right mouse button on the project name in "Solution Explorer", then select "Add" menu item and then "Reference")
In your Project, expand the "References", find the QuartzTypeLib reference. Right click it and select properties, and change "Embed Interop Types" to false. (Otherwise you won't be able to use the FilgraphManager class in your project (and probably a couple of other ones)).
In Project Settings, in the Build tab, I had to disable the Prefer 32-bit flag, Otherwise I would get this Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040266
Use this class to play your favorite MP3 file:
using QuartzTypeLib;
public sealed class DirectShowPlayer
{
private FilgraphManager FilterGraph;
public void Play(string path)
{
FilgraphManager = new FilgraphManager();
FilterGraph.RenderFile(path);
FilterGraph.Run();
}
public void Stop()
{
FilterGraph?.Stop();
}
}
PS: TlbImp.exe
can be found here:
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin"
, or in
"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools"
How to put it all together example...
public class OrderListCursorAdapter extends CursorRecyclerViewAdapter<OrderListCursorAdapter.ViewHolder> {
private static final String TAG = OrderListCursorAdapter.class.getSimpleName();
private static final int ID_VIEW_HOLDER_ACTUAL = 0;
private static final int ID_VIEW_HOLDER = 1;
public OrderListCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
}
public static class ViewHolderActual extends ViewHolder {
private static final String TAG = ViewHolderActual.class.getSimpleName();
protected IViewHolderClick listener;
protected Button button;
public ViewHolderActual(View v, IViewHolderClick listener) {
super(v, listener);
this.listener = listener;
button = (Button) v.findViewById(R.id.orderList_item_button);
button.setOnClickListener(this);
}
public void initFromData(OrderData data) {
Log.d(TAG, "><initFromData(data=" + data + ")");
orderId = data.getId();
vAddressStart.setText(data.getAddressStart());
vAddressEnd.setText(data.getAddressEnd());
}
@Override
public void onClick(View view) {
if (view instanceof Button) {
listener.onButtonClick((Button) view, getPosition(), this);
} else {
super.onClick(view);
}
}
public interface IViewHolderClick extends ViewHolder.IViewHolderClick {
public void onButtonClick(Button button, int position, ViewHolder viewHolder);
}
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private static final String TAG = ViewHolder.class.getSimpleName();
protected long orderId;
protected IViewHolderClick listener;
protected TextView vAddressStart;
protected TextView vAddressEnd;
protected TextView vStatus;
public ViewHolder(View v, IViewHolderClick listener) {
super(v);
this.listener = listener;
v.setOnClickListener(this);
vAddressStart = (TextView) v.findViewById(R.id.addressStart);
vAddressEnd = (TextView) v.findViewById(R.id.addressEnd);
vStatus = (TextView) v.findViewById(R.id.status);
}
public void initFromData(OrderData data) {
Log.d(TAG, "><initFromData(data=" + data + ")");
orderId = data.getId();
vAddressStart.setText(data.getAddressStart());
vAddressEnd.setText(data.getAddressEnd());
}
public long getOrderId() {
return orderId;
}
@Override
public void onClick(View view) {
listener.onCardClick(view, getPosition(), this);
}
public interface IViewHolderClick {
public void onCardClick(View view, int position, ViewHolder viewHolder);
}
}
@Override
public int getItemViewType(int position) {
return position == 0 ? ID_VIEW_HOLDER_ACTUAL : ID_VIEW_HOLDER;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d(TAG, ">>onCreateViewHolder(parent=" + parent + ", viewType=" + viewType + ")");
ViewHolder result;
switch (viewType) {
case ID_VIEW_HOLDER_ACTUAL: {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout_actual, parent, false);
result = new ViewHolderActual(itemView, new ViewHolderActual.IViewHolderClick() {
@Override
public void onCardClick(View view, int position, ViewHolder viewHolder) {
Log.d(TAG, "><onCardClick(view=" + view + ", position=" + position + ", viewHolder=" + viewHolder + ")");
Intent intent = new Intent(view.getContext(), OrderDetailActivity.class);
intent.putExtra(OrderDetailActivity.ARG_ORDER_ID, viewHolder.getOrderId());
view.getContext().startActivity(intent);
}
@Override
public void onButtonClick(Button button, int position, ViewHolder viewHolder) {
Log.d(TAG, "><onButtonClick(button=" + button + ", position=" + position + ", viewHolder=" + viewHolder + ")");
Intent intent = new Intent(button.getContext(), OrderMapActivity.class);
intent.putExtra(OrderMapActivity.ARG_ORDER_ID, viewHolder.getOrderId());
button.getContext().startActivity(intent);
}
});
break;
}
case ID_VIEW_HOLDER:
default: {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);
result = new ViewHolder(itemView, new ViewHolder.IViewHolderClick() {
@Override
public void onCardClick(View view, int position, ViewHolder viewHolder) {
Log.d(TAG, "><onCardClick(view=" + view + ", position=" + position + ", viewHolder=" + viewHolder + ")");
Intent intent = new Intent(view.getContext(), OrderDetailActivity.class);
intent.putExtra(OrderDetailActivity.ARG_ORDER_ID, viewHolder.getOrderId());
view.getContext().startActivity(intent);
}
});
break;
}
}
Log.d(TAG, "<<onCreateViewHolder(parent=" + parent + ", viewType=" + viewType + ")= " + result);
return result;
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, Cursor cursor) {
Log.d(TAG, "><onBindViewHolder(viewHolder=" + viewHolder + ", cursor=" + cursor + ")");
final OrderData orderData = new OrderData(cursor);
viewHolder.initFromData(orderData);
}
}
If your onclick function returns false the default browser behaviour is cancelled. As such:
<a href='http://www.google.com' onclick='return check()'>check</a>
<script type='text/javascript'>
function check()
{
return false;
}
</script>
Either way, whether google does it or not isn't of much importance. It's cleaner to bind your onclick functions within javascript - this way you separate your HTML from other code.
For non-preemptive system,
waitingTime = startTime - arrivalTime
turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime
startTime = Time at which the process started executing
finishTime = Time at which the process finished executing
You can keep track of the current time elapsed in the system(timeElapsed
). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime
, when finishes, record its finishTime
(both same as timeElapsed
). That way you can calculate what you need.
I couldn't find the text-uppercase in Bootstrap referred to in one of the answers. No matter, I created it;
.text-uppercase {
text-transform: uppercase;
}
This displays text in uppercase, but the underlying data is not transformed in this way. So in jquery I have;
$(".text-uppercase").keyup(function () {
this.value = this.value.toLocaleUpperCase();
});
This will change the underlying data wherever you use the text-uppercase class.
This looks like a pretty clean solution: UIDevice BIdentifier
// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to erica sadun & mlamb.
- (NSString *) macaddress{
int mib[6];
size_t len;
char *buf;
unsigned char *ptr;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
mib[0] = CTL_NET;
mib[1] = AF_ROUTE;
mib[2] = 0;
mib[3] = AF_LINK;
mib[4] = NET_RT_IFLIST;
if ((mib[5] = if_nametoindex("en0")) == 0) {
printf("Error: if_nametoindex error\n");
return NULL;
}
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 1\n");
return NULL;
}
if ((buf = malloc(len)) == NULL) {
printf("Could not allocate memory. error!\n");
return NULL;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 2");
free(buf);
return NULL;
}
ifm = (struct if_msghdr *)buf;
sdl = (struct sockaddr_dl *)(ifm + 1);
ptr = (unsigned char *)LLADDR(sdl);
NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
*ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
free(buf);
return outstring;
}
You can use the Google Docs PDF-viewing widget, if you don't mind having them host the "application" itself.
I had more suggestions, but stack overflow only lets me post one hyperlink as a new user, sorry.
The following worked for me.
$ perldoc perllocal | grep Module
$ perldoc perllocal | grep -E 'VERSION|Module'
You could use std::search
with a custom predicate.
#include <locale>
#include <iostream>
#include <algorithm>
using namespace std;
// templated version of my_equal so it could work with both char and wchar_t
template<typename charT>
struct my_equal {
my_equal( const std::locale& loc ) : loc_(loc) {}
bool operator()(charT ch1, charT ch2) {
return std::toupper(ch1, loc_) == std::toupper(ch2, loc_);
}
private:
const std::locale& loc_;
};
// find substring (case insensitive)
template<typename T>
int ci_find_substr( const T& str1, const T& str2, const std::locale& loc = std::locale() )
{
typename T::const_iterator it = std::search( str1.begin(), str1.end(),
str2.begin(), str2.end(), my_equal<typename T::value_type>(loc) );
if ( it != str1.end() ) return it - str1.begin();
else return -1; // not found
}
int main(int arc, char *argv[])
{
// string test
std::string str1 = "FIRST HELLO";
std::string str2 = "hello";
int f1 = ci_find_substr( str1, str2 );
// wstring test
std::wstring wstr1 = L"????? ??????";
std::wstring wstr2 = L"??????";
int f2 = ci_find_substr( wstr1, wstr2 );
return 0;
}
Instead of just doing this quoted method from https://stackoverflow.com/a/4635440/3787376,
You can do something like this:
// show loading image $('#loader_img').show(); // main image loaded ? $('#main_img').on('load', function(){ // hide/remove the loading image $('#loader_img').hide(); });
You assign
load
event to the image which fires when image has finished loading. Before that, you can show your loader image.
you can use a different jQuery function to make the loading image fade away, then be hidden:
// Show the loading image.
$('#loader_img').show();
// When main image loads:
$('#main_img').on('load', function(){
// Fade out and hide the loading image.
$('#loader_img').fadeOut(100); // Time in milliseconds.
});
"Once the opacity reaches 0, the display style property is set to none." http://api.jquery.com/fadeOut/
Or you could not use the jQuery library because there are already simple cross-browser JavaScript methods.
The ARM architecture was originally designed for Acorn personal computers (See Acorn Archimedes, circa 1987, and RiscPC), which were just as much keyboard-based personal computers as were x86 based IBM PC models. Only later ARM implementations were primarily targeted at the mobile and embedded market segment.
Originally, simple RISC CPUs of roughly equivalent performance could be designed by much smaller engineering teams (see Berkeley RISC) than those working on the x86 development at Intel.
But, nowadays, the fastest ARM chips have very complex multi-issue out-of-order instruction dispatch units designed by large engineering teams, and x86 cores may have something like a RISC core fed by an instruction translation unit.
So, any current differences between the two architectures are more related to the specific market needs of the product niches that the development teams are targeting. (Random opinion: ARM probably makes more in license fees from embedded applications that tend to be far more power and cost constrained. And Intel needs to maintain a performance edge in PCs and servers for their profit margins. Thus you see differing implementation optimizations.)
Try setting the timeout value in your web service proxy class:
WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds
Set validateTLSCertificates
property to false
for your JSoup command.
Jsoup.connect("https://google.com/").validateTLSCertificates(false).get();
In IntelliJ IDEA:
In File Menu
? Project Structure
? Project
, change Project Language Level
to 8.0 - Lambdas, type annotations etc.
For Android 3.0+ Go File
? Project Structure
? Module
? app
and In Properties Tab set Source Compatibility
and Target Compatibility
to 1.8 (Java 8)
Screenshot:
Steps:
My inquiry is this. When does one use #import and when does one use @class?
Simple answer: You #import
or #include
when there is a physical dependency. Otherwise, you use forward declarations (@class MONClass
, struct MONStruct
, @protocol MONProtocol
).
Here are some common examples of physical dependence:
CGPoint
as an ivar or property, the compiler will need to see the declaration of CGPoint
.Sometimes if I use a @class declaration, I see a common compiler warning such as the following: "warning: receiver 'FooController' is a forward class and corresponding @interface may not exist."
The compiler's actually very lenient in this regard. It will drop hints (such as the one above), but you can trash your stack easily if you ignore them and don't #import
properly. Although it should (IMO), the compiler does not enforce this. In ARC, the compiler is more strict because it is responsible for reference counting. What happens is the compiler falls back on a default when it encounters an unknown method which you call. Every return value and parameter is assumed to be id
. Thus, you ought to eradicate every warning from your codebases because this should be considered physical dependence. This is analogous to calling a C function which is not declared. With C, parameters are assumed to be int
.
The reason you would favor forward declarations is that you can reduce your build times by factors because there is minimal dependence. With forward declarations, the compiler sees there is a name, and can correctly parse and compile the program without seeing the class declaration or all of its dependencies when there is no physical dependency. Clean builds take less time. Incremental builds take less time. Sure, you will end up spending a little more time making sure the all the headers you need are visible to every translation as a consequence, but this pays off in reduced build times quickly (assuming your project is not tiny).
If you use #import
or #include
instead, you're throwing a lot more work at the compiler than is necessary. You're also introducing complex header dependencies. You can liken this to a brute-force algorithm. When you #import
, you're dragging in tons of unnecessary information, which requires a lot of memory, disk I/O, and CPU to parse and compile the sources.
ObjC is pretty close to ideal for a C based language with regards to dependency because NSObject
types are never values -- NSObject
types are always reference counted pointers. So you can get away with incredibly fast compile times if you structure your program's dependencies appropriately and forward where possible because there is very little physical dependence required. You can also declare properties in the class extensions to further minimize dependence. That's a huge bonus for large systems -- you would know the difference it makes if you have ever developed a large C++ codebase.
Therefore, my recommendation is to use forwards where possible, and then to #import
where there is physical dependence. If you see the warning or another which implies physical dependence -- fix them all. The fix is to #import
in your implementation file.
As you build libraries, you will likely classify some interfaces as a group, in which case you would #import
that library where physical dependence is introduced (e.g. #import <AppKit/AppKit.h>
). This can introduce dependence, but the library maintainers can often handle the physical dependencies for you as needed -- if they introduce a feature, they can minimize the impact it has on your builds.
The __pycache__
folder and *.pyc
files are totally unnecessary to the developer. To hide these files from the explorer view, we need to edit the settings.json for VSCode. Add the folder and the files as shown below:
"files.exclude": {
...
...
"**/*.pyc": {"when": "$(basename).py"},
"**/__pycache__": true,
...
...
}
Yes you can use simply
$input_data = $_POST;
or extract() may be useful for you.
Since Gradle 4.9, the command line arguments can be passed with --args. For example, if you want to launch the application with command line arguments foo --bar
, you can use
gradle run --args='foo --bar'
Create a table with the set you want to export and then use the command line utility pg_dump to export to a file:
create table export_table as
select id, name, city
from nyummy.cimory
where city = 'tokyo'
$ pg_dump --table=export_table --data-only --column-inserts my_database > data.sql
--column-inserts
will dump as insert commands with column names.
--data-only
do not dump schema.
As commented below, creating a view in instead of a table will obviate the table creation whenever a new export is necessary.
public static String replaceCharsNew(String replaceStr,Map<String,String> replaceStrMap){
StringBuilder replaceStrBuilder = new StringBuilder(replaceStr);
Set<String> keys=replaceStrMap.keySet();
for(String invalidChar:keys){
int index = -1;
while((index=replaceStrBuilder.indexOf(invalidChar,index)) !=-1){
replaceStrBuilder.replace(index,index+invalidChar.length(),replaceStrMap.get(invalidChar));
}
}
return replaceStrBuilder.toString();
}
In Bootstrap 3.3.x make sure you use the scrollspy JavaScript capability to track active elements. It's easy to include it in your HTML. Just do the following:
<body data-spy="scroll" data-target="Id or class of the element you want to track">
In most cases I usually track active elements on my navbar, so I do the following:
<body data-spy="scroll" data-target=".navbar-fixed-top" >
Now in your CSS you can target .navbar-fixed-top .active a
:
.navbar-fixed-top .active a {
// Put in some styling
}
This should work if you are tracking active li elements in your top fixed navigation bar.
I had the same problem and was looking for a way to solve it which brought me here. After reviewing the suggestion made from RaeLehman it led me to the solution. Here's my implementation.
In my $(document).ready event I initialize my dialog with the autoOpen set to false. I also chose to bind a click event to an element, like a button, which will open my dialog.
$(document).ready(function(){
// Initialize my dialog
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons: {
"OK":function() { // do something },
"Cancel": function() { $(this).dialog("close"); }
}
});
// Bind to the click event for my button and execute my function
$("#x-button").click(function(){
Foo.DoSomething();
});
});
Next, I make sure that the function is defined and that is where I implement the dialog open method.
var Foo = {
DoSomething: function(){
$("#dialog").dialog("open");
}
}
By the way, I tested this in IE7 and Firefox and it works fine. Hope this helps!
XPath 1.0, which is what MS implements, does not have the idea of a default namespace. So try this:
XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);
Three years later, I ran into the same problem. Here's my solution, everybody feel free to cut-n-paste. The simplest things keep us up all night! Running on an ATMega, and Adafruit Feather M0:
void setup() {
// turn on Serial so we can see...
Serial.begin(9600);
// the culprit:
uint8_t my_str[6]; // an array big enough for a 5 character string
// give it something so we can see what it's doing
my_str[0] = 'H';
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = 0; // be sure to set the null terminator!!!
// can we see it?
Serial.println((char*)my_str);
// can we do logical operations with it as-is?
Serial.println((char*)my_str == 'Hello');
// okay, it can't; wrong data type (and no terminator!), so let's do this:
String str((char*)my_str);
// can we see it now?
Serial.println(str);
// make comparisons
Serial.println(str == 'Hello');
// one more time just because
Serial.println(str == "Hello");
// one last thing...!
Serial.println(sizeof(str));
}
void loop() {
// nothing
}
And we get:
Hello // as expected
0 // no surprise; wrong data type and no terminator in comparison value
Hello // also, as expected
1 // YAY!
1 // YAY!
6 // as expected
Hope this helps someone!
Simple example in java
public class Driver {
static int x;
static int y;
public static void main(String[] args)
throws Exception {
System.out.println("using double pipe");
if(setX() || setY())
{System.out.println("x = "+x);
System.out.println("y = "+y);
}
System.out.println("using single pipe");
if(setX() | setY())
{System.out.println("x = "+x);
System.out.println("y = "+y);
}
}
static boolean setX(){
x=5;
return true;
}
static boolean setY(){
y=5;
return true;
}
}
output :
using double pipe
x = 5
y = 0
using single pipe
x = 5
y = 5
The answer by Daniel A.A. Pelsmaeker and Yesh analogy is excellent. I would like to add a bit more from hackerrank tutorial. Hope it helps a bit too.
You can combine two queries suggested by @spacepille into single query that looks like this:
SELECT * FROM `table_name` WHERE id=(SELECT MAX(id) FROM `table_name`);
It should work blazing fast, but on INNODB tables it's fraction of milisecond slower than ORDER+LIMIT.
One more way to achieve this goal would be using JupyterHub.
With JupyterHub you can create a multi-user Hub which spawns, manages, and proxies multiple instances of the single-user Jupyter notebook server. Due to its flexibility and customization options, JupyterHub can be used to serve notebooks to a class of students, a corporate data science group, or a scientific research group.
Whoa there!
There's a potentially serious problem with this code, because it ignores the character encoding specified in the String
(which is UTF-8 by default). When you call String.getBytes()
the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 data when in fact it's getting EBCDIC or something… not pretty!
Instead, use the parse method that takes an InputSource, which can be constructed with a Reader, like this:
import java.io.StringReader;
import org.xml.sax.InputSource;
…
return builder.parse(new InputSource(new StringReader(xml)));
It may not seem like a big deal, but ignorance of character encoding issues leads to insidious code rot akin to y2k.
Just had to write a "live" example at work :)
This one supports multiple values for UserId on the same date.
Columns: UserId, Value, Date
SELECT
DISTINCT UserId,
MAX(Date) OVER (PARTITION BY UserId ORDER BY Date DESC),
MAX(Values) OVER (PARTITION BY UserId ORDER BY Date DESC)
FROM
(
SELECT UserId, Date, SUM(Value) As Values
FROM <<table_name>>
GROUP BY UserId, Date
)
You can use FIRST_VALUE instead of MAX and look it up in the explain plan. I didn't have the time to play with it.
Of course, if searching through huge tables, it's probably better if you use FULL hints in your query.
Isn't the question essentially: can I write the following?
if (foo)
console.log(bar)
else
console.log(foo + bar)
the answer is, yes, the above will translate.
however, be wary of doing the following
if (foo)
if (bar)
console.log(foo)
else
console.log(bar)
else
console.log(foobar)
be sure to wrap ambiguous code in braces as the above will throw an exception (and similar permutations will produce undesired behaviour.)
you can split using a third party software http://www.hjsplit.org/, for example give yours input that could be upto 9GB and then split, in my case I split 10 MB each
I had this problem recently and the problem was that my web server was not configured to serve woff files. For IIS 7, you can select your site, then select the MIME Types icon. If .woff is not in the list, you need to add it. The correct values are
File name extension: .woff
MIME type: application/font-woff
You need to use the CSS3 transform property rotate
- see here for which browsers support it and the prefix you need to use.
One example for webkit browsers is -webkit-transform: rotate(-90deg);
Edit: The question was changed substantially so I have added a demo that works in Chrome/Safari (as I only included the -webkit-
CSS prefixed rules). The problem you have is that you do not want to rotate the title div, but simply the text inside it. If you remove your rotation, the <div>
s are in the correct position and all you need to do is wrap the text in an element and rotate that instead.
There already exists a more customisable widget as part of the jQuery UI - see the accordion demo page. I am sure with some CSS cleverness you should be able to make the accordion vertical and also rotate the title text :-)
Edit 2: I had anticipated the text center problem and have already updated my demo. There is a height/width constraint though, so longer text could still break the layout.
Edit 3: It looks like the horizontal version was part of the original plan but I cannot see any way of configuring it on the demo page. I was incorrect… the new accordion is part of the upcoming jQuery UI 1.9! So you could try the development builds if you want the new functionality.
Hope this helps!
Well, the reason to use the pointer would be exactly the same that the reason to use pointers in C allocated with malloc: if you want your object to live longer than your variable!
It is even highly recommended to NOT use the new operator if you can avoid it. Especially if you use exceptions. In general it is much safer to let the compiler free your objects.
Could you use online services like this ?
Update: (as per request)
Google chrome will do this also http://cristian-radulescu.ro/article/pretty-print-javascript-with-google-chrome.html
For anybody else looking, here is a decent set of steps. http://forums.asp.net/t/1678976.aspx/1
Don't forget to manually add your key in OnActionExecuting() like I did.
Need to add the i parameter to make it case insensitive:
function getURLParameter(name) {
return decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
);
}
seems like you are hit by integer arithmetic: in some languages (int)/(int) will always be evaluated as integer arithmetic. in order to force floating-point arithmetic, make sure that at least one of the operands is non-integer:
double roundOff = Math.round(a*100)/100.f;
Just put the commands you want to run into a file, then pass it to the shell along with the database name and redirect the output to a file. So, if your find command is in find.js
and your database is foo
, it would look like this:
./mongo foo find.js >> out.json
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
This should be
compile("org.springframework.boot:spring-boot-starter-tomcat")
This can be an efficient way of performing different tests on a single statement
select
case colour_txt
when 'red' then 5
when 'green' then 4
when 'orange' then 3
else 0
end as Pass_Flag
this only works on equality comparisons!
I think it would be quite hard to calculate those because the branch target address is determined at run time and that prediction is done in hardware. If you explained the problem a bit more in depth and described what you are trying to do it would be a little easier to help. (:
Note the guidelines for performing work on a UI thread, collected on my blog:
There are two techniques you should use:
1) Use ConfigureAwait(false)
when you can.
E.g., await MyAsync().ConfigureAwait(false);
instead of await MyAsync();
.
ConfigureAwait(false)
tells the await
that you do not need to resume on the current context (in this case, "on the current context" means "on the UI thread"). However, for the rest of that async
method (after the ConfigureAwait
), you cannot do anything that assumes you're in the current context (e.g., update UI elements).
For more information, see my MSDN article Best Practices in Asynchronous Programming.
2) Use Task.Run
to call CPU-bound methods.
You should use Task.Run
, but not within any code you want to be reusable (i.e., library code). So you use Task.Run
to call the method, not as part of the implementation of the method.
So purely CPU-bound work would look like this:
// Documentation: This method is CPU-bound.
void DoWork();
Which you would call using Task.Run
:
await Task.Run(() => DoWork());
Methods that are a mixture of CPU-bound and I/O-bound should have an Async
signature with documentation pointing out their CPU-bound nature:
// Documentation: This method is CPU-bound.
Task DoWorkAsync();
Which you would also call using Task.Run
(since it is partially CPU-bound):
await Task.Run(() => DoWorkAsync());
Restoring a postgres backup file depends on how did you take the backup in the first place.
If you used pg_dump with -F c or -F d you need to use pg_restore otherwise you can just use
psql -h localhost -p 5432 -U postgres < backupfile
You are looking for --build-arg
and the ARG
instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg
to the Dockerfile
and then build with docker build --build-arg arg=2.3 .
.
SELECT DATEADD(day,1-DATEpart(day, GETDATE()),GETDATE())
First you have to install a module call Serial. To do that go to the folder call Scripts which is located in python installed folder. If you are using Python 3 version it's normally located in location below,
C:\Python34\Scripts
Once you open that folder right click on that folder with shift key. Then click on 'open command window here'. After that cmd
will pop up. Write the below code in that cmd
window,
pip install PySerial
and press enter.after that PySerial module will be installed. Remember to install the module u must have an INTERNET connection.
after successfully installed the module open python IDLE and write down the bellow code and run it.
import serial
# "COM11" is the port that your Arduino board is connected.set it to port that your are using
ser = serial.Serial("COM11", 9600)
while True:
cc=str(ser.readline())
print(cc[2:][:-5])
After some googling, I came across ng2-search-filter
. In will take your object and apply the search term against all object properties looking for a match.
The example above can be simplify a bit. Additionally you can put date manually from keyboard instead of selecting it via datepicker only. When clearing the value you need to handle also 'on clearDate' action to remove startDate/endDate boundary:
JS file:
$(".from_date").datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
}).on('changeDate', function (selected) {
var startDate = new Date(selected.date.valueOf());
$('.to_date').datepicker('setStartDate', startDate);
}).on('clearDate', function (selected) {
$('.to_date').datepicker('setStartDate', null);
});
$(".to_date").datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
}).on('changeDate', function (selected) {
var endDate = new Date(selected.date.valueOf());
$('.from_date').datepicker('setEndDate', endDate);
}).on('clearDate', function (selected) {
$('.from_date').datepicker('setEndDate', null);
});
HTML:
<input class="from_date" placeholder="Select start date" type="text" name="from_date">
<input class="to_date" placeholder="Select end date" type="text" name="to_date">
You must be prompted in your s4 screen to authorize that computer. You can tell it to remember it. This is for security reasons, occurring in Android 4.4+
Online APK Decompiler
http://www.decompileandroid.com/
https://www.decompiler.com/
APK Decompiler App for Windows
http://forum.xda-developers.com/showthread.php?t=2493107
Update 2015/12/04
ClassyShark you can open APK/Zip/Class/Jar files and analyze their contents.
https://github.com/google/android-classyshark
Update 2021/1/28
https://ibotpeaches.github.io/Apktool/
https://github.com/skylot/jadx
That syntax should work OK, but you can try this alternative.
<a href="javascript:void(0);" onclick="ShowOld(2367,146986,2);">
or
<a href="javascript:ShowOld(2367, 146986, 2);">
UPDATED ANSWER FOR STRING VALUES
If you are passing strings, use single quotes for your function's parameters
<a href="javascript:ShowOld('foo', 146986, 'bar');">
Firstly you need to create AdminClient bean:
@Bean
public AdminClient adminClient(){
Map<String, Object> configs = new HashMap<>();
configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,
StringUtils.arrayToCommaDelimitedString(new Object[]{"your bootstrap server address}));
return AdminClient.create(configs);
}
Then, you can use this script:
while (true) {
Map<String, ConsumerGroupDescription> groupDescriptionMap =
adminClient.describeConsumerGroups(Collections.singletonList(groupId))
.all()
.get(10, TimeUnit.SECONDS);
ConsumerGroupDescription consumerGroupDescription = groupDescriptionMap.get(groupId);
log.debug("Kafka consumer group ({}) state: {}",
groupId,
consumerGroupDescription.state());
if (consumerGroupDescription.state().equals(ConsumerGroupState.STABLE)) {
boolean isReady = true;
for (MemberDescription member : consumerGroupDescription.members()) {
if (member.assignment() == null || member.assignment().topicPartitions().isEmpty()) {
isReady = false;
}
}
if (isReady) {
break;
}
}
log.debug("Kafka consumer group ({}) is not ready. Waiting...", groupId);
TimeUnit.SECONDS.sleep(1);
}
This script will check the state of the consumer group every second till the state will be STABLE. Because all consumers assigned to topic partitions, you can conclude that server is running and ready.
This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date.
Func<DateTime> RandomDayFunc()
{
DateTime start = new DateTime(1995, 1, 1);
Random gen = new Random();
int range = ((TimeSpan)(DateTime.Today - start)).Days;
return () => start.AddDays(gen.Next(range));
}
As said earlier, just do:
[[NSUserDefaults standardUserDefaults] setObject: [NSArray arrayWithObjects:@"el", nil] forKey:@"AppleLanguages"];
But to avoid having to restart the app, put the line in the main method of main.m
, just before UIApplicationMain
(...).
jQuery("#input").live('change', function() {
// since we check more than once against the value, place it in a var.
var inputvalue = $("#input").attr("value");
// if it's value **IS NOT** ""
if(inputvalue !== "") {
jQuery(this).css('outline', 'solid 1px red');
}
// else if it's value **IS** ""
else if(inputvalue === "") {
alert('empty');
}
});
;(function() {
var redirect = false
if (navigator.userAgent.match(/iPhone/i)) {
redirect = true
}
if (navigator.userAgent.match(/iPod/i)) {
redirect = true
}
var isAndroid = /(android)/i.test(navigator.userAgent)
var isMobile = /(mobile)/i.test(navigator.userAgent)
if (isAndroid && isMobile) {
redirect = true
}
if (redirect) {
window.location.replace('jQueryMobileSite')
}
})()
None of the above helped for me.
I was able to install Mojave using this link here: http://dosdude1.com/mojave/ This patch worked beautifully and without a hitch
Proof: here's Mojave running on my (unsupported) 2011 Mac-mini
I am using this solution in case to find out that my app is running on debug version.
if (BuildConfig.BUILD_TYPE.equals("debug")){
//Do something
}
You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:
mLocationClient.requestLocationUpdates(mLocationRequest, this);
Be sure that the LocationListener you're implementing is from the google api, that is import this:
import com.google.android.gms.location.LocationListener;
and not this:
import android.location.LocationListener;
and it should work just fine.
It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html
The action
attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".
There is no reason to use $_SERVER['PHP_SELF']
, and #
doesn't submit the form at all (unless there is a submit
event handler attached that handles the submission).
Use dataType: "jsonp"
. I had the same error before. It fixed for me.
Yes, using System.Reflection
:
using System.Reflection;
...
string prop = "name";
PropertyInfo pi = myObject.GetType().GetProperty(prop);
pi.SetValue(myObject, "Bob", null);
git fetch && git checkout branch-name
Another option is to do like this:
<html>
<body>
<?php
//...php code...
?>
<script type="text/javascript">
document.write("Hello World!");
</script>
<?php
//....php code...
?>
</body>
</html>
and if you want to use PHP inside your JavaScript, do like this:
<html>
<body>
<?php
$text = "Hello World!";
?>
<script type="text/javascript">
document.write("<?php echo $text ?>");
</script>
<?php
//....php code...
?>
</body>
</html>
Hope this can help.
First, you do not need android:process=":remote"
, so please remove it, since all it will do is take up extra RAM for no benefit.
Second, since the <service>
element contains an action string, use it:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=new Intent("com.sample.service.serviceClass");
this.startService(intent);
}
There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that are defined in the List interface. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.
Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).
That's called polymorphism. You can read up on it.
Just as a side note:
Printing is O(1) but building a string and then printing is O(n), where n is the total number of characters in the string. So yes, while building the string is "cleaner", it's not the most efficient method of doing so.
The way I would do it is as follows:
from sys import stdout
printf = stdout.write
Now you have a "print function" that prints out any string you give it without returning the new line character each time.
printf("Hello,")
printf("World!")
The output will be: Hello, World!
However, if you want to print integers, floats, or other non-string values, you'll have to convert them to a string with the str() function.
printf(str(2) + " " + str(4))
The output will be: 2 4
Rendering engine goes several steps till it paints anything on the screen.
it looks like this:
The same process goes to CSS. for CSS rendering engine creates different/separated data structure for CSS but it's called CSSOM (CSS Object Model)
Browser works only with Object models so it needs to know all information about DOM and CSSDOM.
The next step is combining somehow DOM and CSSOM. because without CSSOM browser do not know how to style each element during rendering process.
All information above means that, anything you provide in your html (javascript, css ) browser will pause DOM construction process. If you are familiar with event loop, there is simple rule how event loop executes tasks:
So when you provide Javascript file, browser do not know what JS code is going to do and stops all DOM construction process and Javascript interptreter starts parsing and executing Javascript code.
Even you provide Javascript in the end of body tag, Browser will proceed all above steps to HTML and CSS but except rendering. it will find out Script tag and will stop until JS is done.
But HTML provided two additional options for script tag: async and defer.
Async - means execute code when it is downloaded and do not block DOM construction during downloading process.
Defer - means execute code after it's downloaded and browser finished DOM construction and rendering process.
Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets.
Both dictionaries and sets use hashing and they use much more memory than only for object storage. According to A.M. Kuchling in Beautiful Code, the implementation tries to keep the hash 2/3 full, so you might waste quite some memory.
If you do not add new entries on the fly (which you do, based on your updated question), it might be worthwhile to sort the list and use binary search. This is O(log n), and is likely to be slower for strings, impossible for objects which do not have a natural ordering.
I created this script to solve the problem of the class img-responsive bootstrap3, and in my case this solved!
$(document).ready(function() {
if ($.browser.msie) {
var pic_real_width, pic_real_height;
var images = $(".img-responsive");
images.each(function(){
var img = $(this);
$("<img/>")
.attr("src", $(img).attr("src"))
.load(function() {
pic_real_width = this.width;
pic_stretch_width = $(img).width();
if(pic_stretch_width > pic_real_width)
{
$(img).width(pic_real_width);
}
});
});
}
});
System.Interactive provides Buffer()
for this purpose. Some quick testing shows performance is similar to Sam's solution.
app.run(use_reloader=True)
we can use this, use_reloader so every time we reload the page our code changes will be updated.
For a RollingLogFileAppender you also need these elements and values:
<rollingStyle value="Date" />
<staticLogFileName value="false" />
return
means, "output this value from this function".
print
means, "send this value to (generally) stdout"
In the Python REPL, a function return will be output to the screen by default (this isn't quite the same as print).
This is an example of print:
>>> n = "foo\nbar" #just assigning a variable. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>
This is an example of return:
>>> def getN():
... return "foo\nbar"
...
>>> getN() #When this isn't assigned to something, it is just output
'foo\nbar'
>>> n = getN() # assigning a variable to the return value. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>
To check whether select box has any values:
if( $('#fruit_name').has('option').length > 0 ) {
To check whether selected value is empty:
if( !$('#fruit_name').val() ) {
If using GitHub on Windows:
This is why, before you start making changes of your own, that you should create a branch for each set of changes you plan to put into a pull request. That way, once you make the pull request, you can then make another branch and continue work on some other task/feature/bugfix without affecting the previous pull request.
This is perfectly legal:
public static void main(String[] args) {
}
public static void main(String argv) {
System.out.println("hello");
}
I found some examples are not compatible with python 3 I test one from @Triptych
s = filter(str.isdigit, repr(numList))
num = int(s)
in python 3 it's gonna give error
TypeError: int() argument must be a string, a bytes-like object or a number, not 'filter'
i think the more simple and compatible way would be
def magic(num_list):
return int("".join(map(str, num_list)))
Inside your git repository directory, run git config user.name
.
Why is running this command within your git repo directory important?
If you are outside of a git repository, git config user.name
gives you the value of user.name
at global level. When you make a commit, the associated user name is read at local level.
Although unlikely, let's say user.name
is defined as foo
at global level, but bar
at local level. Then, when you run git config user.name
outside of the git repo directory, it gives bar
. However, when you really commits something, the associated value is foo
.
Git config variables can be stored in 3 different levels. Each level overrides values in the previous level.
1. System level (applied to every user on the system and all their repositories)
git config --list --system
(may need sudo
)git config --system color.ui true
git config --edit --system
2. Global level (values specific personally to you, the user. )
git config --list --global
git config --global user.name xyz
git config --edit --global
3. Repository level (specific to that single repository)
git config --list --local
git config --local core.ignorecase true
(--local
optional)git config --edit --local
(--local
optional)How to view all settings?
git config --list
, showing system, global, and (if inside a repository) local configsgit config --list --show-origin
, also shows the origin file of each config itemHow to read one particular config?
git config user.name
to get user.name
, for example.--system
, --global
, --local
to read that value at a particular level.Reference: 1.6 Getting Started - First-Time Git Setup
I have tested all the above solutions but not working for me, i have tried to remove the http:// and won't redirect also removed the www it redirect well, so i get confused, specially i am running all my sites under https://
So i have combined some codes together and came up with perfect solution for both http:// and https:// and www and non-www.
# HTTPS forced
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
# Redirect to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
</IfModule>
Hope this can help someone :)
You're comparing strings. JavaScript compares the ASCII code for each character of the string.
To see why you get false, look at the charCodes:
"1300".charCodeAt(0);
49
"999".charCodeAt(0);
57
The comparison is false because, when comparing the strings, the character codes for 1 is not greater than that of 9.
The fix is to treat the strings as numbers. You can use a number of methods:
parseInt(string, radix)
parseInt("1300", 10);
> 1300 - notice the lack of quotes
+"1300"
> 1300
Number("1300")
> 1300
Rename the closing function as 'hide', for example and it will work.
function hide() {
if(document.getElementById('benefits').style.display=='block') {
document.getElementById('benefits').style.display='none';
}
}
You could do it this way:
-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
ELSE '"DECLINED"'
END
The reason you can do an AND
here is that you are not checking the CASE
of STATE
, but instead you are CASING Conditions.
The key part here is that the STATE
condition is a part of the WHEN
.
my_var: the variable declared
VAR: the variable, whose value is to be checked
param_1, param_2: values of the variable VAR
value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var
my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"
Just add in the '0' in your select.
INSERT INTO table_name (a,b,c,d)
SELECT
other_table.a AS a,
other_table.b AS b,
other_table.c AS c,
'0' AS d
FROM other_table
Older versions of JSP did not support the second syntax.
Here's a lightweight solution I use which allows the application to bring an already existing window to the foreground without resorting to custom windows messages or blindly searching process names.
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
static readonly string guid = "<Application Guid>";
static void Main()
{
Mutex mutex = null;
if (!CreateMutex(out mutex))
return;
// Application startup code.
Environment.SetEnvironmentVariable(guid, null, EnvironmentVariableTarget.User);
}
static bool CreateMutex(out Mutex mutex)
{
bool createdNew = false;
mutex = new Mutex(false, guid, out createdNew);
if (createdNew)
{
Process process = Process.GetCurrentProcess();
string value = process.Id.ToString();
Environment.SetEnvironmentVariable(guid, value, EnvironmentVariableTarget.User);
}
else
{
string value = Environment.GetEnvironmentVariable(guid, EnvironmentVariableTarget.User);
Process process = null;
int processId = -1;
if (int.TryParse(value, out processId))
process = Process.GetProcessById(processId);
if (process == null || !SetForegroundWindow(process.MainWindowHandle))
MessageBox.Show("Unable to start application. An instance of this application is already running.");
}
return createdNew;
}
Edit: You can also store and initialize mutex and createdNew statically, but you'll need to explicitly dispose/release the mutex once you're done with it. Personally, I prefer keeping the mutex local as it will be automatically disposed of even if the application closes without ever reaching the end of Main.
Change your meta tag to the one below and use placeholder attribute inside your HTML input tag.
<meta http-equiv="X-UA-Compatible" content="IE=edge" />_x000D_
<input type="text" placeholder="Placeholder text" />?
_x000D_
I would say: (simple zero will work, 0px is a zero ;))
<body style="margin: 0;">
but maybe something overwrites your css. (assigns different style after you ;))
If you use Firefox - check out firebug plugin.
And in Chrome - just right-click on the page and chose "inspect element" in the menu. Find BODY in elements tree and check its properties.
Won't days * 24 * 60 * 60 * 1000
suffice?
I have used the following for "formatting" the database on device after I have changed the structure of the database in assets. I simply uncomment the line in MainActivity when I wanted that the database is read from the assets again. This will reset the device database values and structure to mach with the preoccupied database in assets folder.
//database initialization. Uncomment to clear the database
//deleteDatabase("questions.db");
Next, I will implement a button that will run the deleteDatabase so that the user can reset its progress in the game.
Here is a combination of the answer by @Mohsenasm and a comment from @Ghigo adopted to Swift
extension UIView {
var globalFrame: CGRect? {
let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
return self.superview?.convert(self.frame, to: rootView)
}
}
Because this seems to not be marked as answered yet... The Answer of Thomas Arildsen should be the proper one: just use
np.flipud(your_array)
if it is a 1d array (column array).
With matrizes do
fliplr(matrix)
if you want to reverse rows and flipud(matrix)
if you want to flip columns. No need for making your 1d column array a 2dimensional row array (matrix with one None layer) and then flipping it.
I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.
Do not use a union
!
C++ does not permit type punning via union
s!
Reading from a union field that was not the last field written to is undefined behaviour!
Many compilers support doing so as an extensions, but the language makes no guarantee.
See this answer for more details:
https://stackoverflow.com/a/11996970
There are only two valid answers that are guaranteed to be portable.
The first answer, if you have access to a system that supports C++20,
is to use std::endian
from the <type_traits>
header.
(At the time of writing, C++20 has not yet been released, but unless something happens to affect std::endian
's inclusion, this shall be the preferred way to test the endianness at compile time from C++20 onwards.)
constexpr bool is_little_endian = (std::endian::native == std::endian::little);
Prior to C++20, the only valid answer is to store an integer and then inspect its first byte through type punning.
Unlike the use of union
s, this is expressly allowed by C++'s type system.
It's also important to remember that for optimum portability static_cast
should be used,
because reinterpret_cast
is implementation defined.
If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined: ... a
char
orunsigned char
type.
enum class endianness
{
little = 0,
big = 1,
};
inline endianness get_system_endianness()
{
const int value { 0x01 };
const void * address = static_cast<const void *>(&value);
const unsigned char * least_significant_address = static_cast<const unsigned char *>(address);
return (*least_significant_address == 0x01) ? endianness::little : endianness::big;
}
inline bool is_system_little_endian()
{
const int value { 0x01 };
const void * address = static_cast<const void *>(&value);
const unsigned char * least_significant_address = static_cast<const unsigned char *>(address);
return (*least_significant_address == 0x01);
}
inline bool is_system_little_endian()
{
const int value = 0x01;
const void * address = static_cast<const void *>(&value);
const unsigned char * least_significant_address = static_cast<const unsigned char *>(address);
return (*least_significant_address == 0x01);
}
I know this is late, but it does answer your original question.
/*Read the comments the same way that SQL runs the query
1) FROM
2) GROUP
3) SELECT
4) My final notes at the bottom
*/
SELECT
list.invoiceid
, cust.customernumber
, MAX(list.inv_amount) AS invoice_amount/* we select the max because it will be the same for each payment to that invoice (presumably invoice amounts do not vary based on payment) */
, MAX(list.inv_amount) - SUM(list.pay_amount) AS [amount_due]
FROM
Customers AS cust
INNER JOIN
Payments AS pay
ON
pay.customerid = cust.customerid
INNER JOIN ( /* generate a list of payment_ids, their amounts, and the totals of the invoices they billed to*/
SELECT
inpay.paymentid AS paymentid
, inv.invoiceid AS invoiceid
, inv.amount AS inv_amount
, pay.amount AS pay_amount
FROM
InvoicePayments AS inpay
INNER JOIN
Invoices AS inv
ON inv.invoiceid = inpay.invoiceid
INNER JOIN
Payments AS pay
ON pay.paymentid = inpay.paymentid
) AS list
ON
list.paymentid = pay.paymentid
/* so at this point my result set would look like:
-- All my customers (crossed by) every paymentid they are associated to (I'll call this A)
-- Every invoice payment and its association to: its own ammount, the total invoice ammount, its own paymentid (what I call list)
-- Filter out all records in A that do not have a paymentid matching in (list)
-- we filter the result because there may be payments that did not go towards invoices!
*/
GROUP BY
/* we want a record line for each customer and invoice ( or basically each invoice but i believe this makes more sense logically */
cust.customernumber
, list.invoiceid
/*
-- we can improve this query by only hitting the Payments table once by moving it inside of our list subquery,
-- but this is what made sense to me when I was planning.
-- Hopefully it makes it clearer how the thought process works to leave it in there
-- as several people have already pointed out, the data structure of the DB prevents us from looking at customers with invoices that have no payments towards them.
*/
First check if the user has granted the permission:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED)
Then, you could use this to request to the user:
ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, requestCode);
And in Marshmallow, it will appear in a dialog
The following worked for me in with iOS 13.6 and Xcode 11.6 with a UITableViewController
that was embedded in a UINavigationController
:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
nil
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
.zero
}
No other trickery needed. The override
keywords aren't needed when not using a UITableViewController
(i.e. when just implemented the UITableViewDelegate
methods). Of course if the goal was to hide just the first section's header, then this logic could be wrapped in a conditional as such:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
return nil
} else {
// Return some other view...
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return .zero
} else {
// Return some other height...
}
}
If you are using windows and are interested in clearing the screen before running the program, you can compile the file call it from a .bat file. for example:
cls
java "what ever the name of the compiles class is"
Save as "etc".bat and then running by calling it in the command prompt or double clicking the file
I am on Android Studio 2.0 and facing the same problem. The solution provided by Rudy Kurniawan sorted out this issue. The affected file can be located by:
"Project" -> "Android" -> "Gradle Scripts" -> "build.gradle(Module:app)"
The "Project" pane is default on the left. To find it, inspect the name of the side tabs, click it, then use the top pull down box to get to "Android". Expand the tree in the pane to find the target file. Double-click it to edit.
You can use built-in sorted
function.
print sorted(['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'])
Check out the request module.
It's more full featured than node's built-in http client.
var request = require('request');
var propertiesObject = { field1:'test1', field2:'test2' };
request({url:url, qs:propertiesObject}, function(err, response, body) {
if(err) { console.log(err); return; }
console.log("Get response: " + response.statusCode);
});
I have exactly similar problem too. I have used the command
findprivatekey root localmachine -n "CN="CertName"
the result shows that the private key is in c:\ProgramData folder instead of C:\Documents and settngs\All users..
When I delete the key from c:\ProgramData folder, again run the findPrivatekey command does not succeed. ie. it does not find the key.
But if i search the same key returned by earlier command, i can still find the key in
C:\Documents and settngs\All users..
So to my understanding, IIS or the hosted WCF is not finding the private key from C:\Documents and settngs\All users..
It's pretty simple.
var oFile = document.getElementById("fileUpload").files[0]; // <input type="file" id="fileUpload" accept=".jpg,.png,.gif,.jpeg"/>
if (oFile.size > 2097152) // 2 MiB for bytes.
{
alert("File size must under 2MiB!");
return;
}
I'm a little late to the party but for future readers.
From what i can tell, you're just wanting to toggle the visibility state right? Why not just use the !
operator?
jxPanel6.setVisible(!jxPanel6.isVisible);
It's not an if statement but I prefer this method for code related to your example.
I also needed this once, and I did a check on the window title of the process. If it is the one you expect, you can be sure the application is running. The application I was checking needed some time for startup and this method worked fine for me.
var process = Process.Start("popup.exe");
while(process.MainWindowTitle != "Title")
{
Thread.Sleep(10);
}
First of all do not use list
as a variable name- that is a builtin function.
I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-
my_list = []
my_list.append(np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
my_list.append(np.genfromtxt('temp2.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
That will create a list (a type of mutable array in python) called my_list
with the output of the np.getfromtext()
method in the first 2 indexes.
The first can be referenced with my_list[0]
and the second with my_list[1]
^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$
This matches 99.99% of email addresses, including some of the newer top-level-domain extensions, such as info, museum, name, etc. It also allows for emails tied directly to IP addresses.
Try writing it like this:
div { border: 1px solid #CCC; }
_x000D_
<div style="display: inline">a</div>_x000D_
<div style="display: inline">b</div>_x000D_
<div style="display: inline">c</div>
_x000D_
The main difference is that
substr() allows you to specify the maximum length to return
substring() allows you to specify the indices and the second argument is NOT inclusive
There are some additional subtleties between substr() and substring() such as the handling of equal arguments and negative arguments. Also note substring() and slice() are similar but not always the same.
//*** length vs indices:
"string".substring(2,4); // "ri" (start, end) indices / second value is NOT inclusive
"string".substr(2,4); // "ring" (start, length) length is the maximum length to return
"string".slice(2,4); // "ri" (start, end) indices / second value is NOT inclusive
//*** watch out for substring swap:
"string".substring(3,2); // "r" (swaps the larger and the smaller number)
"string".substr(3,2); // "in"
"string".slice(3,2); // "" (just returns "")
//*** negative second argument:
"string".substring(2,-4); // "st" (converts negative numbers to 0, then swaps first and second position)
"string".substr(2,-4); // ""
"string".slice(2,-4); // ""
//*** negative first argument:
"string".substring(-3); // "string"
"string".substr(-3); // "ing" (read from end of string)
"string".slice(-3); // "ing"
color="white"
is not a known attribute to Angular Material.
color attribute can changed to primary
, accent
, and warn
. as said in this doc
your icon inside button works because its parent class button has css class of color:white
, or may be your color="accent"
is white. check the developer tools to find it.
By default, icons will use the current font color
Here is a simpler example that does not require multiple threads:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SimplePty
{
public SimplePty(Process process) throws IOException
{
while (process.isAlive())
{
sync(process.getErrorStream(), System.err);
sync(process.getInputStream(), System.out);
sync(System.in, process.getOutputStream());
}
}
private void sync(InputStream in, OutputStream out) throws IOException
{
while (in.available() > 0)
{
out.write(in.read());
out.flush();
}
}
public static void main( String[] args ) throws IOException
{
String os = System.getProperty("os.name").toLowerCase();
String shell = os.contains("win") ? "cmd" : "bash";
Process process = new ProcessBuilder(shell).start();
new SimplePty(process);
}
}
If you VS solution contains several projects, select all of them in the right pane, and press "properties". Then go to C++ -> Code Generation and chose one Run Time library option for all of them
public partial class Form1 : Form
{
private Thread n_server;
private Thread n_client;
private Thread n_send_server;
private TcpClient client;
private TcpListener listener;
private int port = 2222;
private string IP = " ";
private Socket socket;
byte[] bufferReceive = new byte[4096];
byte[] bufferSend = new byte[4096];
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
public void Server()
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
try
{
socket = listener.AcceptSocket();
if (socket.Connected)
{
textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Client : " + socket.RemoteEndPoint.ToString(); });
}
while (true)
{
int length = socket.Receive(bufferReceive);
if (length > 0)
{
label2.Invoke((MethodInvoker)delegate { label2.Text = Encoding.Unicode.GetString(bufferReceive); });
}
}
}
catch
{
}
}
public void Client()
{
IP = "localhost";
client = new TcpClient();
try
{
client.Connect(IP, port);
while (true)
{
NetworkStream nts = client.GetStream();
int length;
while ((length = nts.Read(bufferReceive, 0, bufferReceive.Length)) != 0)
{
label3.Invoke((MethodInvoker)delegate { label3.Text = Encoding.Unicode.GetString(bufferReceive); });
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
if (client.Connected)
{
textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Connected..."; });
}
}
private void button1_Click(object sender, EventArgs e)
{
n_server = new Thread(new ThreadStart(Server));
n_server.IsBackground = true;
n_server.Start();
textBox1.Text = "Server up";
}
private void button2_Click(object sender, EventArgs e)
{
n_client = new Thread(new ThreadStart(Client));
n_client.IsBackground = true;
n_client.Start();
}
private void send()
{
if (socket!=null)
{
bufferSend = Encoding.Unicode.GetBytes(textBox2.Text);
socket.Send(bufferSend);
}
else
{
if (client.Connected)
{
bufferSend = Encoding.Unicode.GetBytes(textBox3.Text);
NetworkStream nts = client.GetStream();
if (nts.CanWrite)
{
nts.Write(bufferSend,0,bufferSend.Length);
}
}
}
}
private void button3_Click(object sender, EventArgs e)
{
n_send_server = new Thread(new ThreadStart(send));
n_send_server.IsBackground = true;
n_send_server.Start();
}
}
Another way:
x=$'Some\nstring'
readarray -t y <<<"$x"
Or, if you don't have bash 4, the bash 3.2 equivalent:
IFS=$'\n' read -rd '' -a y <<<"$x"
You can also do it the way you were initially trying to use:
y=(${x//$'\n'/ })
This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'
. To make it work, you need to restrict the word separator before parsing it:
IFS=$'\n' y=(${x//$'\n'/ })
...and then, since you are changing the separator, you don't need to convert the \n
to space
anymore, so you can simplify it to:
IFS=$'\n' y=($x)
This approach will function unless $x
contains a matching globbing pattern (such as "*
") - in which case it will be replaced by the matched file name(s). The read
/readarray
methods require newer bash versions, but work in all cases.
Building on Benjamin's, using pandas.Series
, and replacing MAD with IQR:
def reject_outliers(sr, iq_range=0.5):
pcnt = (1 - iq_range) / 2
qlow, median, qhigh = sr.dropna().quantile([pcnt, 0.50, 1-pcnt])
iqr = qhigh - qlow
return sr[ (sr - median).abs() <= iqr]
For instance, if you set iq_range=0.6
, the percentiles of the interquartile-range would become: 0.20 <--> 0.80
, so more outliers will be included.
To run Anaconda Prompt using icon, I made an icon and put
%windir%\System32\cmd.exe "/K" C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3
The file location would be different in each computer.
at icon -> right click -> Property -> Shortcut -> Target
I see %HOMEPATH%
at icon -> right click -> Property -> Start in
OS: Windows 10, Library: Anaconda 10 (64 bit)
Algorithm is a sequence of some operations that given an input computes something (a function) and outputs a result.
Algorithm may yield an exact or approximate values.
It also may compute a random value that is with high probability close to the exact value.
A heuristic algorithm uses some insight on input values and computes not exact value (but may be close to optimal). In some special cases, heuristic can find exact solution.
The easiest thing is to run the program, open the task manager, right-click the process and select properties, here is the full address
I found the xmessage command, which is sort of good enough.
It's running every minute of the hour 22 I guess. Try the following to run it every first minute of the hour 22:
0 22 * * * ....
Title_Authors is a look up two things join at a time project results and continue chaining
DataClasses1DataContext db = new DataClasses1DataContext();
var queryresults = from a in db.Authors
join ba in db.Title_Authors
on a.Au_ID equals ba.Au_ID into idAuthor
from c in idAuthor
join t in db.Titles
on c.ISBN equals t.ISBN
select new { Author = a.Author1,Title= t.Title1 };
foreach (var item in queryresults)
{
MessageBox.Show(item.Author);
MessageBox.Show(item.Title);
return;
}
Remove the content of the folder \.m2\repository\org\apache\maven\plugins\maven-resource-plugin\2.7
. The cached info turned out to be the issue.
Just remove the .val(). Like:
if ( $('html').attr('lang') == 'fr-FR' ) {
// do this
} else {
// do that
}
As Selman22 said, you are overriding the default object.Equals
method, which accepts an object obj
and not a safe compile time type.
In order for that to happen, make your type implement IEquatable<Box>
:
public class Box : IEquatable<Box>
{
double height, length, breadth;
public static bool operator ==(Box obj1, Box obj2)
{
if (ReferenceEquals(obj1, obj2))
{
return true;
}
if (ReferenceEquals(obj1, null))
{
return false;
}
if (ReferenceEquals(obj2, null))
{
return false;
}
return obj1.Equals(obj2);
}
public static bool operator !=(Box obj1, Box obj2)
{
return !(obj1 == obj2);
}
public bool Equals(Box other)
{
if (ReferenceEquals(other, null))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return height.Equals(other.height)
&& length.Equals(other.length)
&& breadth.Equals(other.breadth);
}
public override bool Equals(object obj)
{
return Equals(obj as Box);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = height.GetHashCode();
hashCode = (hashCode * 397) ^ length.GetHashCode();
hashCode = (hashCode * 397) ^ breadth.GetHashCode();
return hashCode;
}
}
}
Another thing to note is that you are making a floating point comparison using the equality operator and you might experience a loss of precision.
VS2010 has a property for 'Build Action', and also for 'Copy to Output Directory'. So an action of 'None' will still copy over to the build directory if the copy property is set to 'Copy if Newer' or 'Copy Always'.
So a Build Action of 'Content' should be reserved to indicate content you will access via 'Application.GetContentStream'
I used the 'Build Action' setting of 'None' and the 'Copy to Output Direcotry' setting of 'Copy if Newer' for some externally linked .config includes.
G.
Nto sure which RDBMS you are using, but if it is SQL Server you could look at rather using a CASE statement
Evaluates a list of conditions and returns one of multiple possible result expressions.
The CASE expression has two formats:
The simple CASE expression compares an expression to a set of simple expressions to determine the result.
The searched CASE expression evaluates a set of Boolean expressions to determine the result.
Both formats support an optional ELSE argument.
Here is another way without regex.
$myUrl = "http://www.domain.com/link.php";
$myParsedURL = parse_url($myUrl);
$myDomainName= $myParsedURL['host'];
$ipAddress = gethostbyname($myDomainName);
if($ipAddress == $myDomainName)
{
echo "There is no url";
}
else
{
echo "url found";
}
You can download a list of symbols from here. You have an option to download the whole list directly into excel file. You will have to register though.
I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.
CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG
You can find details about the parameters at this link.
Hope it helps!
run npm i moment react-moment --save
you can use this in your component,
import Moment from 'react-moment';
const date = new Date();
<Moment format='MMMM Do YYYY, h:mm:ss a'>{date}</Moment>
You can use Autohotkey
, download it from: http://ahkscript.org/download/
After the installation, if you want to open Gmail website when you press Alt+g, you can do something like this:
!g::
Run www.gmail.com
return
Further reference: Hotkeys (Mouse, Joystick and Keyboard Shortcuts)
my rule of thumb is:
rebase
for branches with the same name,merge
otherwise.
examples for same names would be master
, origin/master
and otherRemote/master
.
if develop
exists only in the local repository, and it is always based on a recent origin/master
commit, you should call it master
, and work there directly. it simplifies your life, and presents things as they actually are: you are directly developing on the master
branch.
if develop
is shared, it should not be rebased on master
, just merged back into it with --no-ff
. you are developing on develop
. master
and develop
have different names, because we want them to be different things, and stay separate. do not make them same with rebase
.
I just wrote my little subclass of UIView that has ability to produce native iOS 7 blur on any custom view. It uses UIToolbar but in a safe way for changing it's frame, bounds, color and alpha with real-time animation.
Please let me know if you notice any problems.
As described here, you need to edit (as root) the file /etc/apt/sources.list
(the easiest way to do this is to type sudo gedit /etc/apt/sources.list
). On the line that mentions http://packages.ros.org/ros/ubuntu you need to add [trusted=yes]
after the word deb
(you might need to add it as a separate word). Then save the file and try again.
In JSF I used:
<h:head>
<f:facet name="first">
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
</f:facet>
<!-- ... other meta tags ... -->
</h:head>
I am also looking for an answer to this question, (to clarify, I want to be able to draw an image with user defined opacity such as how you can draw shapes with opacity) if you draw with primitive shapes you can set fill and stroke color with alpha to define the transparency. As far as I have concluded right now, this does not seem to affect image drawing.
//works with shapes but not with images
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
I have concluded that setting the globalCompositeOperation
works with images.
//works with images
ctx.globalCompositeOperation = "lighter";
I wonder if there is some kind third way of setting color so that we can tint images and make them transparent easily.
EDIT:
After further digging I have concluded that you can set the transparency of an image by setting the globalAlpha
parameter BEFORE you draw the image:
//works with images
ctx.globalAlpha = 0.5
If you want to achieve a fading effect over time you need some kind of loop that changes the alpha value, this is fairly easy, one way to achieve it is the setTimeout
function, look that up to create a loop from which you alter the alpha over time.
Based on Jon Skeet answer i've made a class that permits to do it easily at work:
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* <p>
* This permits to easily implement a failsafe implementation of the enums's valueOf
* Better use it inside the enum so that only one of this object instance exist for each enum...
* (a cache could solve this if needed)
* </p>
*
* <p>
* Basic usage exemple on an enum class called MyEnum:
*
* private static final FailSafeValueOf<MyEnum> FAIL_SAFE = FailSafeValueOf.create(MyEnum.class);
* public static MyEnum failSafeValueOf(String enumName) {
* return FAIL_SAFE.valueOf(enumName);
* }
*
* </p>
*
* <p>
* You can also use it outside of the enum this way:
* FailSafeValueOf.create(MyEnum.class).valueOf("EnumName");
* </p>
*
* @author Sebastien Lorber <i>([email protected])</i>
*/
public class FailSafeValueOf<T extends Enum<T>> {
private final Map<String,T> nameToEnumMap;
private FailSafeValueOf(Class<T> enumClass) {
Map<String,T> map = Maps.newHashMap();
for ( T value : EnumSet.allOf(enumClass)) {
map.put( value.name() , value);
}
nameToEnumMap = ImmutableMap.copyOf(map);
}
/**
* Returns the value of the given enum element
* If the
* @param enumName
* @return
*/
public T valueOf(String enumName) {
return nameToEnumMap.get(enumName);
}
public static <U extends Enum<U>> FailSafeValueOf<U> create(Class<U> enumClass) {
return new FailSafeValueOf<U>(enumClass);
}
}
And the unit test:
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/**
* @author Sebastien Lorber <i>([email protected])</i>
*/
public class FailSafeValueOfTest {
private enum MyEnum {
TOTO,
TATA,
;
private static final FailSafeValueOf<MyEnum> FAIL_SAFE = FailSafeValueOf.create(MyEnum.class);
public static MyEnum failSafeValueOf(String enumName) {
return FAIL_SAFE.valueOf(enumName);
}
}
@Test
public void testInEnum() {
assertNotNull( MyEnum.failSafeValueOf("TOTO") );
assertNotNull( MyEnum.failSafeValueOf("TATA") );
assertNull( MyEnum.failSafeValueOf("TITI") );
}
@Test
public void testInApp() {
assertNotNull( FailSafeValueOf.create(MyEnum.class).valueOf("TOTO") );
assertNotNull( FailSafeValueOf.create(MyEnum.class).valueOf("TATA") );
assertNull( FailSafeValueOf.create(MyEnum.class).valueOf("TITI") );
}
}
Notice that i used Guava to make an ImmutableMap but actually you could use a normal map i think since the map is never returned...
The problem is that in many cases the packages are multiarch already so the i386 package is not available, but other packages still depend on the i386 package only. This is a problem in the repository, and the managers of the repos should fix it
Add builtin COPY in project.csproj file:
<Project>
...
<Target Name="AfterBuild">
<Copy SourceFiles="$(ProjectDir)..\..\Lib\*.dll" DestinationFolder="$(OutDir)Debug\bin" SkipUnchangedFiles="false" />
<Copy SourceFiles="$(ProjectDir)..\..\Lib\*.dll" DestinationFolder="$(OutDir)Release\bin" SkipUnchangedFiles="false" />
</Target>
</Project>
(number/10**x)%10
You can use this in a loop, where number is the full number, x is each iteration of the loop (0,1,2,3,...,n) with n being the stop point. x = 0 gives the ones place, x = 1 gives the tens, x = 2 gives the hundreds, and so on. Keep in mind that this will give the value of the digits from right to left, so this might not be the for an ISBN but it will still isolate each digit.
A simple string.Concat() is what you need.
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string result = string.Concat(test);
If you also need to add a seperator (space, comma etc) then, string.Join() should be used.
string[] test = new string[2];
test[0] = "Red";
test[1] = "Blue";
string result = string.Join(",", test);
If you have to perform this on a string array with hundereds of elements than string.Join() is better by performace point of view. Just give a "" (blank) argument as seperator. StringBuilder can also be used for sake of performance, but it will make code a bit longer.
Allowed only characters & spaces. Ex : Jayant Lonari
if (!/^[a-zA-Z\s]+$/.test(NAME)) {
//Throw Error
}
Python comes with numerous ways of formatting strings:
New style .format()
, which supports a rich formatting mini-language:
>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!
Old style %
format specifier:
>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!
In Py 3.6 using the new f""
format strings:
>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!
Or using print()
s default sep
arator:
>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!
And least effectively, construct a new string by casting it to a str()
and concatenating:
>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!
Or join()
ing it:
>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!
If you don't need to access your array, (just a simple for loop) you can use upto or each :
Upto:
1.9.3p392 :030 > 2.upto(4) {|i| puts i}
2
3
4
=> 2
Each:
1.9.3p392 :031 > (2..4).each {|i| puts i}
2
3
4
=> 2..4
Found this in another thread that helped me: Use xp_cmdshell and sqlcmd Is it possible to execute a text file from SQL query? - by Gulzar Nazim
EXEC xp_cmdshell 'sqlcmd -S ' + @DBServerName + ' -d ' + @DBName + ' -i ' + @FilePathName
I've been using this because I'm returning results from another table. Though I'm trying to avoid the nested join if it helps w/ one less step. Oh well. It returns the same thing.
select
users.userid
, lastIP.IP
, lastIP.maxdate
from users
inner join (
select userid, IP, datetime
from IPAddresses
inner join (
select userid, max(datetime) as maxdate
from IPAddresses
group by userid
) maxIP on IPAddresses.datetime = maxIP.maxdate and IPAddresses.userid = maxIP.userid
) as lastIP on users.userid = lastIP.userid
"ABCDEFG".First
returns "A"
Dim s as string
s = "Rajan"
s.First
'R
s = "Sajan"
s.First
'S
All type information is erased in JavaScript side and therefore you can't new up T just like @Sohnee states, but I would prefer having typed parameter passed in to constructor:
class A {
}
class B<T> {
Prop: T;
constructor(TCreator: { new (): T; }) {
this.Prop = new TCreator();
}
}
var test = new B<A>(A);
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
./me casts raise_dead()
I was looking for something like this, but I also needed to reuse the same string minus two parameters so I ended up with something like:
my_exe ()
{
mysql -sN -e "select $1 from heat.stack where heat.stack.name=\"$2\";"
}
This is something I use to monitor openstack heat stack creation. In this case I expect two conditions, an action 'CREATE' and a status 'COMPLETE' on a stack named "Somestack"
To get those variables I can do something like:
ACTION=$(my_exe action Somestack)
STATUS=$(my_exe status Somestack)
if [[ "$ACTION" == "CREATE" ]] && [[ "$STATUS" == "COMPLETE" ]]
...
SELECT field1
, field2
, 'Test' AS field3
FROM Test
; // replace with simple quote '
A workaround is to:
write a counter in a firebase doc, which you increment within a transaction everytime you create a new entry
You store the count in a field of your new entry (i.e: position: 4).
Then you create an index on that field (position DESC).
You can do a skip+limit with a query.Where("position", "<" x).OrderBy("position", DESC)
Hope this helps!
You can use zip
with *
to get transpose of a matrix:
>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis = [[1,2,3],
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
If you want the returned list to be a list of lists:
>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
You are looking for the insert
function, found in the table
section of the main library.
foo = {}
table.insert(foo, "bar")
table.insert(foo, "baz")
// The answer that I was looking for when searching
public void Answer()
{
IEnumerable<YourClass> first = this.GetFirstIEnumerableList();
// Assign to empty list so we can use later
IEnumerable<YourClass> second = new List<YourClass>();
if (IwantToUseSecondList)
{
second = this.GetSecondIEnumerableList();
}
IEnumerable<SchemapassgruppData> concatedList = first.Concat(second);
}
THIS IS THE VB VERSION (Works with GREEK) :
Imports System.Text
Imports System.Globalization
Public Function RemoveDiacritics(ByVal s As String)
Dim normalizedString As String
Dim stringBuilder As New StringBuilder
normalizedString = s.Normalize(NormalizationForm.FormD)
Dim i As Integer
Dim c As Char
For i = 0 To normalizedString.Length - 1
c = normalizedString(i)
If CharUnicodeInfo.GetUnicodeCategory(c) <> UnicodeCategory.NonSpacingMark Then
stringBuilder.Append(c)
End If
Next
Return stringBuilder.ToString()
End Function
If you want to write fast to file streams then you could make stream the read buffer larger:
wfstream f;
const size_t nBufferSize = 16184;
wchar_t buffer[nBufferSize];
f.rdbuf()->pubsetbuf(buffer, nBufferSize);
Also, when writing lots of data to files it is sometimes faster to logically extend the file size instead of physically, this is because when logically extending a file the file system does not zero the new space out before writing to it. It is also smart to logically extend the file more than you actually need to prevent lots of file extentions. Logical file extention is supported on Windows by calling SetFileValidData
or xfsctl
with XFS_IOC_RESVSP64
on XFS systems.
you can use pandas.set_option(), for column, you can specify any of these options
pd.set_option("display.max_rows", 200)
pd.set_option("display.max_columns", 100)
pd.set_option("display.max_colwidth", 200)
For full print column, you can use like this
import pandas as pd
pd.set_option('display.max_colwidth', -1)
print(words.head())
I think much confusion is generated by not communicating what is meant by passed by reference. When some people say pass by reference they usually mean not the argument itself, but rather the object being referenced. Some other say that pass by reference means that the object can't be changed in the callee. Example:
struct Object {
int i;
};
void sample(Object* o) { // 1
o->i++;
}
void sample(Object const& o) { // 2
// nothing useful here :)
}
void sample(Object & o) { // 3
o.i++;
}
void sample1(Object o) { // 4
o.i++;
}
int main() {
Object obj = { 10 };
Object const obj_c = { 10 };
sample(&obj); // calls 1
sample(obj) // calls 3
sample(obj_c); // calls 2
sample1(obj); // calls 4
}
Some people would claim that 1 and 3 are pass by reference, while 2 would be pass by value. Another group of people say all but the last is pass by reference, because the object itself is not copied.
I would like to draw a definition of that here what i claim to be pass by reference. A general overview over it can be found here: Difference between pass by reference and pass by value. The first and last are pass by value, and the middle two are pass by reference:
sample(&obj);
// yields a `Object*`. Passes a *pointer* to the object by value.
// The caller can change the pointer (the parameter), but that
// won't change the temporary pointer created on the call side (the argument).
sample(obj)
// passes the object by *reference*. It denotes the object itself. The callee
// has got a reference parameter.
sample(obj_c);
// also passes *by reference*. the reference parameter references the
// same object like the argument expression.
sample1(obj);
// pass by value. The parameter object denotes a different object than the
// one passed in.
I vote for the following definition:
An argument (1.3.1) is passed by reference if and only if the corresponding parameter of the function that's called has reference type and the reference parameter binds directly to the argument expression (8.5.3/4). In all other cases, we have to do with pass by value.
That means that the following is pass by value:
void f1(Object const& o);
f1(Object()); // 1
void f2(int const& i);
f2(42); // 2
void f3(Object o);
f3(Object()); // 3
Object o1; f3(o1); // 4
void f4(Object *o);
Object o1; f4(&o1); // 5
1
is pass by value, because it's not directly bound. The implementation may copy the temporary and then bind that temporary to the reference. 2
is pass by value, because the implementation initializes a temporary of the literal and then binds to the reference. 3
is pass by value, because the parameter has not reference type. 4
is pass by value for the same reason. 5
is pass by value because the parameter has not got reference type. The following cases are pass by reference (by the rules of 8.5.3/4 and others):
void f1(Object *& op);
Object a; Object *op1 = &a; f1(op1); // 1
void f2(Object const& op);
Object b; f2(b); // 2
struct A { };
struct B { operator A&() { static A a; return a; } };
void f3(A &);
B b; f3(b); // passes the static a by reference
Check-it Out:
HTML:
<a id="aSelect" href="#">Select</a>
<br />
<asp:ListBox ID="lstSelect" runat="server" SelectionMode="Multiple" Width="100px">
<asp:ListItem Text="Raj" Value="1"></asp:ListItem>
<asp:ListItem Text="Karan" Value="2"></asp:ListItem>
<asp:ListItem Text="Riya" Value="3"></asp:ListItem>
<asp:ListItem Text="Aman" Value="4"></asp:ListItem>
<asp:ListItem Text="Tom" Value="5"></asp:ListItem>
</asp:ListBox>
JQUERY:
$("#aSelect").click(function(){
var selectedValues = [];
$("#lstSelect :selected").each(function(){
selectedValues.push($(this).val());
});
alert(selectedValues);
return false;
});
You can use RETURN
to stop execution of a stored procedure immediately. Quote taken from Books Online:
Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.
Out of paranoia, I tried yor example and it does output the PRINTs and does stop execution immediately.
If you are using ionic in config.xml update widget tag with "xmlns:android="http://schemas.android.com/apk/res/android"
<widget id="io.ionic.starter" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0">_x000D_
_x000D_
_x000D_
<widget/>
_x000D_
This is a JQuery code for Preventing Submit
$('form').submit(function (e) {
if (radioButtonValue !== "0") {
e.preventDefault();
}
});
This works for me:
String getMonthName(int monthNumber) {
String[] months = new DateFormatSymbols().getMonths();
int n = monthNumber-1;
return (n >= 0 && n <= 11) ? months[n] : "wrong number";
}
To returns "September"
with one line:
String month = getMonthName(9);
Check the link Regular Expression Demo
use the below reg exp
[a-z] + [^0-9\s.]+|.(?!\d)