Since link to this question shows up on very top of returned results when you search for "php MSVCR110.dll" (not to mention it got 100k+ views and growing), here're some additional notes that you may find handy in your quest to solve MSVCR110.dll mistery...
The approach described in the answer is valid not only for MSVCR110.dll case but also applies when you are looking for other versions, like newer MSVCR71.dll
and I updated the answer to include VC15 even it's beyond scope of the original question.
On http://windows.php.net/ you can read:
VC9, VC11 and VC15
More recent versions of PHP are built with VC9, VC11 or VC15 (Visual Studio 2008, 2012 or 2015 compiler respectively) and include improvements in performance and stability.
The VC9 builds require you to have the Visual C++ Redistributable for Visual Studio 2008 SP1 x86 or x64 installed.
The VC11 builds require to have the Visual C++ Redistributable for Visual Studio 2012 x86 or x64 installed.
The VC15 builds require to have the Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed.
This is quite crucial as you not only need to get Visual C++ Redistributable installed but you also need the right version of it, and which one is right and correct, depends on what PHP build you are actually going to use. Pay attention to what version of PHP for Windows you are fetching, especially pay attention to this "VCxx" suffix, because if you install PHP that requires VC9 while having redistributables VC11 installed it is not going to work as run-time dependency is simply not fulfilled. Contrary to what some may think, you need exactly the version required, as newer (higher) releases does NOT cover older (lower) versions. so i.e. VC11 is not providing VC9 compatibility. Also VC15 is neither fulfilling VC11 nor VC9 dependency. It is just VC15 and NOTHING ELSE. Deal with it :)
For example, archive name php-5.6.4-nts-Win32-VC11-x86
tells us the following
Most searches I did lead to VC9 of redistributables, so in case of constant failures to make thing works, if possible, try installing different PHP build, to see if you by any chance do not face mismatching versions.
Download links
Note that you are using 32-bit version of PHP, so you need 32-bit redistributable (x86) even if your version of Windows is 64-bit!
Specify the maxrecursion option at the end of the query:
...
from EmployeeTree
option (maxrecursion 0)
That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.
You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.
StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
int idx = (((uri != null) && (uri.length() > 0)) ? url.indexOf(uri) : url.length());
String host = url.substring(0, idx); //base url
idx = host.indexOf("://");
if(idx > 0) {
host = host.substring(idx); //remove scheme if present
}
We have another way to find out the number of rows in a table without running a select
query on that table.
Every MySQL instance has information_schema database. If you run the following query, it will give complete details about the table including the approximate number of rows in that table.
select * from information_schema.TABLES where table_name = 'table_name'\G
Here is how I transitioned from UIWebView to WKWebView.
Note: There is no property like UIWebView that you can drag onto your storyboard, you have to do it programatically.
Make sure you import WebKit/WebKit.h into your header file.
This is my header file:
#import <WebKit/WebKit.h>
@interface ViewController : UIViewController
@property(strong,nonatomic) WKWebView *webView;
@property (strong, nonatomic) NSString *productURL;
@end
Here is my implementation file:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.productURL = @"http://www.URL YOU WANT TO VIEW GOES HERE";
NSURL *url = [NSURL URLWithString:self.productURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
_webView = [[WKWebView alloc] initWithFrame:self.view.frame];
[_webView loadRequest:request];
_webView.frame = CGRectMake(self.view.frame.origin.x,self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
[self.view addSubview:_webView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
JoshAdel's solution uses np.newaxis to add a dimension. An alternative is to use reshape() to align the dimensions in preparation for broadcasting.
data = np.array([[1,1,1],[2,2,2],[3,3,3]])
vector = np.array([1,2,3])
data
# array([[1, 1, 1],
# [2, 2, 2],
# [3, 3, 3]])
vector
# array([1, 2, 3])
data.shape
# (3, 3)
vector.shape
# (3,)
data / vector.reshape((3,1))
# array([[1, 1, 1],
# [1, 1, 1],
# [1, 1, 1]])
Performing the reshape() allows the dimensions to line up for broadcasting:
data: 3 x 3
vector: 3
vector reshaped: 3 x 1
Note that data/vector
is ok, but it doesn't get you the answer that you want. It divides each column of array
(instead of each row) by each corresponding element of vector
. It's what you would get if you explicitly reshaped vector
to be 1x3
instead of 3x1
.
data / vector
# array([[1, 0, 0],
# [2, 1, 0],
# [3, 1, 1]])
data / vector.reshape((1,3))
# array([[1, 0, 0],
# [2, 1, 0],
# [3, 1, 1]])
%cd C:\Users\asus\Desktop\python
import pandas as pd
df = pd.read_csv('value.txt')
df.head()
Date price factor_1 factor_2
0 2012-06-11 1600.20 1.255 1.548
1 2012-06-12 1610.02 1.258 1.554
2 2012-06-13 1618.07 1.249 1.552
3 2012-06-14 1624.40 1.253 1.556
4 2012-06-15 1626.15 1.258 1.552
Remove leading + trailing '0':
list = [i.strip('0') for i in listOfNum ]
Remove leading '0':
list = [ i.lstrip('0') for i in listOfNum ]
Remove trailing '0':
list = [ i.rstrip('0') for i in listOfNum ]
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
Gotcha!
If none of the above answers helped you, maybe you are importing some element from the same file where a component is injecting the service.
I explain better:
This is the service file:
// your-service-file.ts
import { helloWorld } from 'your-component-file.ts'
@Injectable()
export class CustomService() {
helloWorld()
}
This is the component file:
@Component({..})
export class CustomComponent {
constructor(service: CustomService) { }
}
export function helloWorld() {
console.log('hello world');
}
So it causes problems even if the symbol isn't inside the same component, but just inside the same file. Move the symbol (it can be a function, a constant, a class and so on...) elsewhere and the error will fade away
Since you're using requests
, you should use the response's json
method.
import requests
response = requests.get(...)
data = response.json()
I used this code to show the dialog at the bottom of the screen:
Dialog dlg = <code to create custom dialog>;
Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);
This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about
private void showPictureialog() {
final Dialog dialog = new Dialog(this,
android.R.style.Theme_Translucent_NoTitleBar);
// Setting dialogview
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
dialog.setTitle(null);
dialog.setContentView(R.layout.selectpic_dialog);
dialog.setCancelable(true);
dialog.show();
}
you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment
Check the 'minSdkVersion' in your build.gradle
The default project creates it with the latest API, so if you're phone is not yet up-dated (e.g. minSdkVersion 21), which is probably your case.
Make sure the minSdkVersion value matches with the device API version or if the device has a higher one.
Example:
defaultConfig {
applicationId 'xxxxxx'
minSdkVersion 16
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
A similar question is: Mapping a NumPy array in place. If you can find a ufunc for your f(), then you should use the out parameter.
You don't need initialization lists for that:
std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);
I hope I'm not late to the party.. Here is my answer. I like using Pattern/Matcher because it uses regex which should be more efficient. Yet, I think this answer could be enhanced:
Matcher matcher = Pattern.compile("is").matcher("I think there is a smarter solution, isn't there?");
int numOfOcurrences = 2;
for(int i = 0; i < numOfOcurrences; i++) matcher.find();
System.out.println("Index: " + matcher.start());
I think you can create a simple SQL query:
$sql="select username from user where id in (select id from idtables)";
$query=$this->db->query($sql);
and then you can use it normally.
Try moving the order by clause outside sub select and add the order by field in sub select
SELECT * FROM
(SELECT COUNT(1) ,refKlinik_id FROM Seanslar WHERE MONTH(tarihi) = 4 GROUP BY refKlinik_id)
as dorduncuay
ORDER BY refKlinik_id
You can use a regular expression such as:
var x = "|f|oo||";
var y = x.replace(/^\|+|\|+$/g, "");
alert(y); // f|oo
UPDATE:
Should you wish to generalize this into a function, you can do the following:
var escapeRegExp = function(strToEscape) {
// Escape special characters for use in a regular expression
return strToEscape.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
var trimChar = function(origString, charToTrim) {
charToTrim = escapeRegExp(charToTrim);
var regEx = new RegExp("^[" + charToTrim + "]+|[" + charToTrim + "]+$", "g");
return origString.replace(regEx, "");
};
var x = "|f|oo||";
var y = trimChar(x, "|");
alert(y); // f|oo
Just add the following rules to the parent element:
display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */
Here's a sample demo (Resize window to see the image align)
Browser support for Flexbox nowadays is quite good.
For cross-browser compatibility for display: flex
and align-items
, you can add the older flexbox syntax as well:
display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
ZIP is a file format used for storing an arbitrary number of files and folders together with lossless compression. It makes no strict assumptions about the compression methods used, but is most frequently used with DEFLATE.
Gzip is both a compression algorithm based on DEFLATE but less encumbered with potential patents et al, and a file format for storing a single compressed file. It supports compressing an arbitrary number of files and folders when combined with tar. The resulting file has an extension of .tgz
or .tar.gz
and is commonly called a tarball.
zlib is a library of functions encapsulating DEFLATE in its most common LZ77 incarnation.
This answer is only applicable for websites which use Bootstrap. The responsive embed feature of the Bootstrap takes care of the scrollbars.
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="http://www.youtube.com/embed/WsFWhL4Y84Y"></iframe>
</div>
jsfiddle: http://jsfiddle.net/00qggsjj/2/
I've been through a number of photo capture strategies, and there always seems to be a case, a platform or certain devices, where some or all of the above strategies will fail in unexpected ways. I was able to find a strategy that uses the URI generation code below which seems to work in most if not all cases.
mPhotoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new ContentValues());
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
startActivityForResult(intent,CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE_CONTENT_RESOLVER);
To contribute further to the discussion and help out newcomers I've created a sample/test app that shows several different strategies for photo capture implementation. Contributions of other implementations are definitely encouraged to add to the discussion.
I come to this question quite regularly and it always takes me a while to find what I search:
import seaborn as sns
import matplotlib.pyplot as plt
plt.show() # <--- This is what you are looking for
Please note: In Python 2, you can also use sns.plt.show()
, but not in Python 3.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Visualize C_0.99 for all languages except the 10 with most characters."""
import seaborn as sns
import matplotlib.pyplot as plt
l = [41, 44, 46, 46, 47, 47, 48, 48, 49, 51, 52, 53, 53, 53, 53, 55, 55, 55,
55, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 58, 58, 58,
58, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 60, 60, 60, 60, 60, 60, 61,
61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 62, 62, 62, 62, 62, 62, 62, 62,
62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 64, 64, 64, 64, 64, 64, 64, 65,
65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 66, 66, 66, 66, 66, 66, 66,
67, 67, 67, 67, 67, 67, 67, 67, 68, 68, 68, 68, 68, 69, 69, 69, 70, 70,
70, 70, 71, 71, 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 73, 73, 73, 73,
74, 74, 74, 74, 74, 75, 75, 75, 76, 77, 77, 78, 78, 79, 79, 79, 79, 80,
80, 80, 80, 81, 81, 81, 81, 83, 84, 84, 85, 86, 86, 86, 86, 87, 87, 87,
87, 87, 88, 90, 90, 90, 90, 90, 90, 91, 91, 91, 91, 91, 91, 91, 91, 92,
92, 93, 93, 93, 94, 95, 95, 96, 98, 98, 99, 100, 102, 104, 105, 107, 108,
109, 110, 110, 113, 113, 115, 116, 118, 119, 121]
sns.distplot(l, kde=True, rug=False)
plt.show()
Gives
I create following web-component similar to JSF
<ui-include src="b.xhtml"><ui-include>
You can use it as regular html tag inside your pages (after including snippet js code)
customElements.define('ui-include', class extends HTMLElement {
async connectedCallback() {
let src = this.getAttribute('src');
this.innerHTML = await (await fetch(src)).text();;
}
})
_x000D_
ui-include { margin: 20px } /* example CSS */
_x000D_
<ui-include src="https://cors-anywhere.herokuapp.com/https://example.com/index.html"></ui-include>
<div>My page data... - in this snippet styles overlaps...</div>
<ui-include src="https://cors-anywhere.herokuapp.com/https://www.w3.org/index.html"></ui-include>
_x000D_
As per your question vertical listing have a scrollbar effect.
CSS / HTML :
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<header>header area</header>_x000D_
<nav>_x000D_
<ul>_x000D_
<li>Link 1</li>_x000D_
<li>Link 2</li>_x000D_
<li>Link 3</li>_x000D_
<li>Link 4</li>_x000D_
<li>Link 5</li>_x000D_
<li>Link 6</li> _x000D_
<li>Link 7</li> _x000D_
<li>Link 8</li>_x000D_
<li>Link 9</li>_x000D_
<li>Link 10</li>_x000D_
<li>Link 11</li>_x000D_
<li>Link 13</li>_x000D_
<li>Link 13</li>_x000D_
_x000D_
</ul>_x000D_
</nav>_x000D_
_x000D_
<footer>footer area</footer>_x000D_
</body>_x000D_
</html>
_x000D_
You may not want absolute positioning because it breaks the reflow: in some circumstances, a better solution is to make the grandparent element display:table;
and the parent element display:table-cell;vertical-align:bottom;
. After doing this, you should be able to give the the child elements display:inline-block;
and they will automagically flow towards the bottom of the parent.
I like using the [ThreadStatic]
attribute in combination with thread and stack based programming. For example, if I want a value that I want to share with the rest of a call sequence, but I want to do it out of band (i.e. outside of the call parameters), I might employ something like this.
class MyContextInformation : IDisposable {
[ThreadStatic] private static MyContextInformation current;
public static MyContextInformation Current {
get { return current; }
}
private MyContextInformation previous;
public MyContextInformation(Object myData) {
this.myData = myData;
previous = current;
current = this;
}
public void Dispose() {
current = previous;
}
}
Later in my code, I can use this to provide contextual information out of band to people downstream from my code. Example:
using(new MyContextInformation(someInfoInContext)) {
...
}
The ThreadStatic attribute allows me to scope the call only to the thread in question avoiding the messy problem of data access across threads.
It is because you forgot to pass in event
into the click
function:
$('.menuOption').on('click', function (e) { // <-- the "e" for event
e.preventDefault(); // now it'll work
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
On a side note, e
is more commonly used as opposed to the word event
since Event
is a global variable in most browsers.
^
matches position just before the first character of the string$
matches position just after the last character of the string.
matches a single character. Does not matter what character it is, except newline*
matches preceding match zero or more timesSo, ^.*$
means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string. This regex pattern is not very useful.
Let's take a regex pattern that may be a bit useful. Let's say I have two strings The bat of Matt Jones
and Matthew's last name is Jones
. The pattern ^Matt.*Jones$
will match Matthew's last name is Jones
. Why? The pattern says - the string should start with Matt and end with Jones and there can be zero or more characters (any characters) in between them.
Feel free to use an online tool like https://regex101.com/ to test out regex patterns and strings.
You can easily auto increase versionName and versionCode programmatically.
For Android add this to your gradle script and also create a file version.properties with VERSION_CODE=555
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
def code = versionProps['VERSION_CODE'].toInteger() + 1
versionProps['VERSION_CODE'] = code.toString()
versionProps.store(versionPropsFile.newWriter(), null)
defaultConfig {
applicationId "app.umanusorn.playground"
minSdkVersion 29
targetSdkVersion 30
versionCode code
versionName code.toString()
That's not the real error, here's how to find it:
Go to the hadoop jobtracker web-dashboard, find the hive mapreduce jobs that failed and look at the logs of the failed tasks. That will show you the real error.
The console output errors are useless, largely beause it doesn't have a view of the individual jobs/tasks to pull the real errors (there could be errors in multiple tasks)
Hope that helps.
This will work too!
foreach($data as &$value) {
$value['transaction_date'] = date('d/m/Y', $value['transaction_date']);
}
Yay for alternatives!
If you can't use tab.select() and you don't want to use a ViewPager, you can still programmatically select a tab. If you're using a custom view through TabLayout.Tab setCustomView(android.view.View view)
it is simpler. Here's how to do it both ways.
// if you've set a custom view
void updateTabSelection(int position) {
// get the position of the currently selected tab and set selected to false
mTabLayout.getTabAt(mTabLayout.getSelectedTabPosition()).getCustomView().setSelected(false);
// set selected to true on the desired tab
mTabLayout.getTabAt(position).getCustomView().setSelected(true);
// move the selection indicator
mTabLayout.setScrollPosition(position, 0, true);
// ... your logic to swap out your fragments
}
If you aren't using a custom view then you can do it like this
// if you are not using a custom view
void updateTabSelection(int position) {
// get a reference to the tabs container view
LinearLayout ll = (LinearLayout) mTabLayout.getChildAt(0);
// get the child view at the position of the currently selected tab and set selected to false
ll.getChildAt(mTabLayout.getSelectedTabPosition()).setSelected(false);
// get the child view at the new selected position and set selected to true
ll.getChildAt(position).setSelected(true);
// move the selection indicator
mTabLayout.setScrollPosition(position, 0, true);
// ... your logic to swap out your fragments
}
Use a StateListDrawable to toggle between selected and unselected drawables or something similar to do what you want with colors and/or drawables.
If TomCat is install. Perhaps it is not installed Java EE. Services-> plug-ins-> additional plug-ins-> in the search dial tomcat. and install the module java ee. then in the services, servers, add the tomcat server.
If your objects has some common ancestor [let it be T
] you should use List<T>
instead of List<Object>
, and implement a Comparator for this T, using the name field.
If you don't have a common ancestor, you can implement a Comperator, and use reflection to extract the name, Note that it is unsafe, unsuggested, and suffers from bad performance to use reflection, but it allows you to access a field name without knowing anything about the actual type of the object [besides the fact that it has a field with the relevant name]
In both cases, you should use Collections.sort() to sort.
how about this solution?
if type(x) in (float, int):
# do whatever
else:
# do whatever
I opened "Passwords and Keys" application in my Unity and removed unwanted keys from Secure Keys -> OpenSSH keys And they automatically had been removed from ssh-agent -l as well.
just use mCheckedPosition
save status
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.checkBox.setChecked(position == mCheckedPostion);
holder.checkBox.setOnClickListener(v -> {
if (position == mCheckedPostion) {
holder.checkBox.setChecked(false);
mCheckedPostion = -1;
} else {
mCheckedPostion = position;
notifyDataSetChanged();
}
});
}
I believe you are not the only one who has problems when trying to deploy Crystal Report for VS 2010. Based on the error message you had, have you checked:
Please make sure you just have one CR version installed on your system. If you do have other CR version installed, consider to uninstall it so that your application is not "confused" about the CR version.
You need to make sure you download the correct CR version. Since you are using VS 2010, you need to refer to CRforVS_redist_install_64bit_13_0_1.zip (for 64 bit machine) or CRforVS_redist_install_32bit_13_0_1.zip (for 32 bit machine). These two are the redistributable packages. You can download full package from the below link as well: CRforVS_13_0_1.exe Note: It is sometimes necessary to install 32bit CR runtime even on 64bit OS
Make sure you setup FULL TRUST permission on your root folder
The LOCAL SERVICE permission must be setup on your application pool
Make sure the aspnet_client folder exists on your root folder.
If you can make sure all the 5 points above, your Crystal Report should work without any fuss.
Another important thing to note down here is that if you host your Crystal Report with a shared host, you need to check it with them of whether they really support Crystal Report. If you still have problems, you can switch to http://www.asphostcentral.com, who provides Crystal Report support.
Good luck!
Does Retrofit have any method to achieve this? If not, how I can do that?
YES
Retrofit is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface.
For more information refer the following link
https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial
public function rules()
{
if ($this->method() == 'PUT') {
$post_id = $this->segment(3);
$rules = [
'post_title' => 'required|unique:posts,post_title,' . $post_id
];
} else {
$rules = [
'post_title' => 'required|unique:posts,post_title'
];
}
return $rules;
}
None of the above answers worked for me. It appears that my own app's usage of DirectoryInfo
on the target directory was causing it to remain locked.
Forcing garbage collection appeared to resolve the issue, but not right away. A few attempts to delete where required.
Note the Directory.Exists
as it can disappear after an exception. I don't know why the delete for me was delayed (Windows 7 SP1)
for (int attempts = 0; attempts < 10; attempts++)
{
try
{
if (Directory.Exists(folder))
{
Directory.Delete(folder, true);
}
return;
}
catch (IOException e)
{
GC.Collect();
Thread.Sleep(1000);
}
}
throw new Exception("Failed to remove folder.");
Using -engine specific rules ensures effective browser targeting.
<style type="text/css">
//Other browsers
color : black;
//Webkit (Chrome, Safari)
@media screen and (-webkit-min-device-pixel-ratio:0) {
color:green;
}
//Firefox
@media screen and (-moz-images-in-menus:0) {
color:orange;
}
</style>
//Internet Explorer
<!--[if IE]>
<style type='text/css'>
color:blue;
</style>
<![endif]-->
var random = items[Math.floor(Math.random()*items.length)]
I don't think that solution would work anyways because you will see some error message in your error log file.
The solution was a lot easier than what I thought.
simply, open the following path to your php5-fpm
sudo nano /etc/php5/fpm/pool.d/www.conf
or if you're the admin 'root'
nano /etc/php5/fpm/pool.d/www.conf
Then find this line and uncomment it:
listen.allowed_clients = 127.0.0.1
This solution will make you be able to use listen = 127.0.0.1:9000 in your vhost blocks
like this: fastcgi_pass 127.0.0.1:9000;
after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm
Php5-fpm
sudo service php5-fpm restart
or
sudo service php5-fpm reload
Nginx
sudo service nginx restart
or
sudo service nginx reload
From the comments:
Also comment
;listen = /var/run/php5-fpm.sock
and add
listen = 9000
Several answers are here but nobody has posted usefull code.
Here is my code that detects all encodings that Microsoft detects in Framework 4 in the StreamReader class.
Obviously you must call this function immediately after opening the stream before reading anything else from the stream because the BOM are the first bytes in the stream.
This function requires a Stream that can seek (for example a FileStream). If you have a Stream that cannot seek you must write a more complicated code that returns a Byte buffer with the bytes that have already been read but that are not BOM.
/// <summary>
/// UTF8 : EF BB BF
/// UTF16 BE: FE FF
/// UTF16 LE: FF FE
/// UTF32 BE: 00 00 FE FF
/// UTF32 LE: FF FE 00 00
/// </summary>
public static Encoding DetectEncoding(Stream i_Stream)
{
if (!i_Stream.CanSeek || !i_Stream.CanRead)
throw new Exception("DetectEncoding() requires a seekable and readable Stream");
// Try to read 4 bytes. If the stream is shorter, less bytes will be read.
Byte[] u8_Buf = new Byte[4];
int s32_Count = i_Stream.Read(u8_Buf, 0, 4);
if (s32_Count >= 2)
{
if (u8_Buf[0] == 0xFE && u8_Buf[1] == 0xFF)
{
i_Stream.Position = 2;
return new UnicodeEncoding(true, true);
}
if (u8_Buf[0] == 0xFF && u8_Buf[1] == 0xFE)
{
if (s32_Count >= 4 && u8_Buf[2] == 0 && u8_Buf[3] == 0)
{
i_Stream.Position = 4;
return new UTF32Encoding(false, true);
}
else
{
i_Stream.Position = 2;
return new UnicodeEncoding(false, true);
}
}
if (s32_Count >= 3 && u8_Buf[0] == 0xEF && u8_Buf[1] == 0xBB && u8_Buf[2] == 0xBF)
{
i_Stream.Position = 3;
return Encoding.UTF8;
}
if (s32_Count >= 4 && u8_Buf[0] == 0 && u8_Buf[1] == 0 && u8_Buf[2] == 0xFE && u8_Buf[3] == 0xFF)
{
i_Stream.Position = 4;
return new UTF32Encoding(true, true);
}
}
i_Stream.Position = 0;
return Encoding.Default;
}
Set a transparent border and then change it:
.default{
border: 2px solid transparent;
}
.new{
border: 2px solid red;
}
git branch --set-upstream-to origin/solaris
The answer to the question you asked—which I'll rephrase a bit as "do I have to set an upstream"—is: no, you don't have to set an upstream at all.
If you do not have upstream for the current branch, however, Git changes its behavior on git push
, and on other commands as well.
The complete push story here is long and boring and goes back in history to before Git version 1.5. To shorten it a whole lot, git push
was implemented poorly.1 As of Git version 2.0, Git now has a configuration knob spelled push.default
which now defaults to simple
. For several versions of Git before and after 2.0, every time you ran git push
, Git would spew lots of noise trying to convince you to set push.default
just to get git push
to shut up.
You do not mention which version of Git you are running, nor whether you have configured push.default
, so we must guess. My guess is that you are using Git version 2-point-something, and that you have set push.default
to simple
to get it to shut up. Precisely which version of Git you have, and what if anything you have push.default
set to, does matter, due to that long and boring history, but in the end, the fact that you're getting yet another complaint from Git indicates that your Git is configured to avoid one of the mistakes from the past.
An upstream is simply another branch name, usually a remote-tracking branch, associated with a (regular, local) branch.
Every branch has the option of having one (1) upstream set. That is, every branch either has an upstream, or does not have an upstream. No branch can have more than one upstream.
The upstream should, but does not have to be, a valid branch (whether remote-tracking like origin/B
or local like master
). That is, if the current branch B has upstream U, git rev-parse U
should work. If it does not work—if it complains that U does not exist—then most of Git acts as though the upstream is not set at all. A few commands, like git branch -vv
, will show the upstream setting but mark it as "gone".
If your push.default
is set to simple
or upstream
, the upstream setting will make git push
, used with no additional arguments, just work.
That's it—that's all it does for git push
. But that's fairly significant, since git push
is one of the places where a simple typo causes major headaches.
If your push.default
is set to nothing
, matching
, or current
, setting an upstream does nothing at all for git push
.
(All of this assumes your Git version is at least 2.0.)
git fetch
If you run git fetch
with no additional arguments, Git figures out which remote to fetch from by consulting the current branch's upstream. If the upstream is a remote-tracking branch, Git fetches from that remote. (If the upstream is not set or is a local branch, Git tries fetching origin
.)
git merge
and git rebase
tooIf you run git merge
or git rebase
with no additional arguments, Git uses the current branch's upstream. So it shortens the use of these two commands.
git pull
You should never2 use git pull
anyway, but if you do, git pull
uses the upstream setting to figure out which remote to fetch from, and then which branch to merge or rebase with. That is, git pull
does the same thing as git fetch
—because it actually runs git fetch
—and then does the same thing as git merge
or git rebase
, because it actually runs git merge
or git rebase
.
(You should usually just do these two steps manually, at least until you know Git well enough that when either step fails, which they will eventually, you recognize what went wrong and know what to do about it.)
git status
This may actually be the most important. Once you have an upstream set, git status
can report the difference between your current branch and its upstream, in terms of commits.
If, as is the normal case, you are on branch B
with its upstream set to origin/B
, and you run git status
, you will immediately see whether you have commits you can push, and/or commits you can merge or rebase onto.
This is because git status
runs:
git rev-list --count @{u}..HEAD
: how many commits do you have on B
that are not on origin/B
?git rev-list --count HEAD..@{u}
: how many commits do you have on origin/B
that are not on B
?Setting an upstream gives you all of these things.
master
already has an upstream set?When you first clone from some remote, using:
$ git clone git://some.host/path/to/repo.git
or similar, the last step Git does is, essentially, git checkout master
. This checks out your local branch master
—only you don't have a local branch master
.
On the other hand, you do have a remote-tracking branch named origin/master
, because you just cloned it.
Git guesses that you must have meant: "make me a new local master
that points to the same commit as remote-tracking origin/master
, and, while you're at it, set the upstream for master
to origin/master
."
This happens for every branch you git checkout
that you do not already have. Git creates the branch and makes it "track" (have as an upstream) the corresponding remote-tracking branch.
If you create a new branch:
$ git checkout -b solaris
there is, as yet, no origin/solaris
. Your local solaris
cannot track remote-tracking branch origin/solaris
because it does not exist.
When you first push the new branch:
$ git push origin solaris
that creates solaris
on origin
, and hence also creates origin/solaris
in your own Git repository. But it's too late: you already have a local solaris
that has no upstream.3
Probably. See "implemented poorly" and footnote 1. It's hard to change now: There are millions4 of scripts that use Git and some may well depend on its current behavior. Changing the behavior requires a new major release, nag-ware to force you to set some configuration field, and so on. In short, Git is a victim of its own success: whatever mistakes it has in it, today, can only be fixed if the change is either mostly invisible, clearly-much-better, or done slowly over time.
The fact is, it doesn't today, unless you use --set-upstream
or -u
during the git push
. That's what the message is telling you.
You don't have to do it like that. Well, as we noted above, you don't have to do it at all, but let's say you want an upstream. You have already created branch solaris
on origin
, through an earlier push, and as your git branch
output shows, you already have origin/solaris
in your local repository.
You just don't have it set as the upstream for solaris
.
To set it now, rather than during the first push, use git branch --set-upstream-to
. The --set-upstream-to
sub-command takes the name of any existing branch, such as origin/solaris
, and sets the current branch's upstream to that other branch.
That's it—that's all it does—but it has all those implications noted above. It means you can just run git fetch
, then look around, then run git merge
or git rebase
as appropriate, then make new commits and run git push
, without a bunch of additional fussing-around.
1To be fair, it was not clear back then that the initial implementation was error-prone. That only became clear when every new user made the same mistakes every time. It's now "less poor", which is not to say "great".
2"Never" is a bit strong, but I find that Git newbies understand things a lot better when I separate out the steps, especially when I can show them what git fetch
actually did, and they can then see what git merge
or git rebase
will do next.
3If you run your first git push
as git push -u origin solaris
—i.e., if you add the -u
flag—Git will set origin/solaris
as the upstream for your current branch if (and only if) the push succeeds. So you should supply -u
on the first push. In fact, you can supply it on any later push, and it will set or change the upstream at that point. But I think git branch --set-upstream-to
is easier, if you forgot.
4Measured by the Austin Powers / Dr Evil method of simply saying "one MILLLL-YUN", anyway.
I found the same thing: curl by itself would print to STDOUT, but could not be piped into another program.
At first, I thought I had solved it by using xargs to echo the output first:
curl -s ... <url> | xargs -0 echo | ...
But then, as pointed out in the comments, it also works without the xargs part, so -s
(silent mode) is the key to preventing extraneous progress output to STDOUT:
curl -s ... <url> | perl -ne 'print $1 if /<sometag>([^<]+)/'
The above example grabs the simple <sometag>
content (containing no embedded tags) from the XML output of the curl statement.
Since Express 4.0, there's a dedicated sendStatus
function:
res.sendStatus(404);
If you're using an earlier version of Express, use the status
function instead.
res.status(404).send('Not found');
The best solution would be to go to http://projects.eclipse.org/projects/tools.pdt/downloads where you will find the URL to the most updated PDT, as most of the URLS listed above are hitting a 404. Then pasting the URL to eclipse.
ummm, I don't know why all this programming, I think the original problem is solved easily by specifying this default route ...
routes.MapRoute("Default", "{*id}",
new { controller = "Home"
, action = "Index"
, id = UrlParameter.Optional
}
);
using System;
using System.Security;
class Sample {
static void Main() {
string text = "Escape characters : < > & \" \'";
string xmlText = SecurityElement.Escape(text);
//output:
//Escape characters : < > & " '
Console.WriteLine(xmlText);
}
}
This can be done like this. It worked fine for me. And also set the directory permissions to 777 or 775 if not set.
ob_clean();
$mpdf->Output('directory_name/pdf_file_name.pdf', 'F');
playSound is a static method meaning it exists when the program is loaded. audioSounds and minTime are SoundManager instance variable, meaning they will exist within an instance of SoundManager. You have not created an instance of SoundManager so audioSounds doesn't exist (or it does but you do not have a reference to a SoundManager object to see that).
To solve your problem you can either make audioSounds static:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;
so they will be created and may be referenced in the same way that PlaySound will be. Alternatively you can create an instance of SoundManager from within your method:
SoundManager soundManager = new SoundManager();
foreach (AudioSource sound in soundManager.audioSounds) // Loop through List with foreach
{
if (sourceSound.name != sound.name && sound.time <= soundManager.minTime)
{
playsound = true;
}
}
Solution with utl_encode.base64_encode
and utl_encode.base64_decode
have one limitation, they work only with strings up to 32,767 characters/bytes.
In case you have to convert bigger strings you will face several obstacles.
BASE64_ENCODE
the function has to read 3 Bytes and transform them. In case of Multi-Byte characters (e.g. öäüè€
stored at UTF-8, aka AL32UTF8
) 3 Character are not necessarily also 3 Bytes. In order to read always 3 Bytes you have to convert your CLOB
into BLOB
first.BASE64_DECODE
. The function has to read 4 Bytes and transform them into 3 Bytes. Those 3 Bytes are not necessarily also 3 CharactersCR
and/or LF
) character each 64 characters. Such new-line characters have to be ignored while decoding.Taking all this into consideration the full featured solution could be this one:
CREATE OR REPLACE FUNCTION DecodeBASE64(InBase64Char IN OUT NOCOPY CLOB) RETURN CLOB IS
blob_loc BLOB;
clob_trim CLOB;
res CLOB;
lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
dest_offset INTEGER := 1;
src_offset INTEGER := 1;
read_offset INTEGER := 1;
warning INTEGER;
ClobLen INTEGER := DBMS_LOB.GETLENGTH(InBase64Char);
amount INTEGER := 1440; -- must be a whole multiple of 4
buffer RAW(1440);
stringBuffer VARCHAR2(1440);
-- BASE64 characters are always simple ASCII. Thus you get never any Mulit-Byte character and having the same size as 'amount' is sufficient
BEGIN
IF InBase64Char IS NULL OR NVL(ClobLen, 0) = 0 THEN
RETURN NULL;
ELSIF ClobLen<= 32000 THEN
RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(InBase64Char)));
END IF;
-- UTL_ENCODE.BASE64_DECODE is limited to 32k, process in chunks if bigger
-- Remove all NEW_LINE from base64 string
ClobLen := DBMS_LOB.GETLENGTH(InBase64Char);
DBMS_LOB.CREATETEMPORARY(clob_trim, TRUE);
LOOP
EXIT WHEN read_offset > ClobLen;
stringBuffer := REPLACE(REPLACE(DBMS_LOB.SUBSTR(InBase64Char, amount, read_offset), CHR(13), NULL), CHR(10), NULL);
DBMS_LOB.WRITEAPPEND(clob_trim, LENGTH(stringBuffer), stringBuffer);
read_offset := read_offset + amount;
END LOOP;
read_offset := 1;
ClobLen := DBMS_LOB.GETLENGTH(clob_trim);
DBMS_LOB.CREATETEMPORARY(blob_loc, TRUE);
LOOP
EXIT WHEN read_offset > ClobLen;
buffer := UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(DBMS_LOB.SUBSTR(clob_trim, amount, read_offset)));
DBMS_LOB.WRITEAPPEND(blob_loc, DBMS_LOB.GETLENGTH(buffer), buffer);
read_offset := read_offset + amount;
END LOOP;
DBMS_LOB.CREATETEMPORARY(res, TRUE);
DBMS_LOB.CONVERTTOCLOB(res, blob_loc, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset, DBMS_LOB.DEFAULT_CSID, lang_context, warning);
DBMS_LOB.FREETEMPORARY(blob_loc);
DBMS_LOB.FREETEMPORARY(clob_trim);
RETURN res;
END DecodeBASE64;
CREATE OR REPLACE FUNCTION EncodeBASE64(InClearChar IN OUT NOCOPY CLOB) RETURN CLOB IS
dest_lob BLOB;
lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
dest_offset INTEGER := 1;
src_offset INTEGER := 1;
read_offset INTEGER := 1;
warning INTEGER;
ClobLen INTEGER := DBMS_LOB.GETLENGTH(InClearChar);
amount INTEGER := 1440; -- must be a whole multiple of 3
-- size of a whole multiple of 48 is beneficial to get NEW_LINE after each 64 characters
buffer RAW(1440);
res CLOB := EMPTY_CLOB();
BEGIN
IF InClearChar IS NULL OR NVL(ClobLen, 0) = 0 THEN
RETURN NULL;
ELSIF ClobLen <= 24000 THEN
RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(UTL_RAW.CAST_TO_RAW(InClearChar)));
END IF;
-- UTL_ENCODE.BASE64_ENCODE is limited to 32k/(3/4), process in chunks if bigger
DBMS_LOB.CREATETEMPORARY(dest_lob, TRUE);
DBMS_LOB.CONVERTTOBLOB(dest_lob, InClearChar, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset, DBMS_LOB.DEFAULT_CSID, lang_context, warning);
LOOP
EXIT WHEN read_offset >= dest_offset;
DBMS_LOB.READ(dest_lob, amount, read_offset, buffer);
res := res || UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(buffer));
read_offset := read_offset + amount;
END LOOP;
DBMS_LOB.FREETEMPORARY(dest_lob);
RETURN res;
END EncodeBASE64;
We should also consider that the SVM system can be applied directly to non-metric spaces, such as the set of labeled graphs or strings. In fact, the internal kernel function can be generalized properly to virtually any kind of input, provided that the positive definiteness requirement of the kernel is satisfied. On the other hand, to be able to use an ANN on a set of labeled graphs, explicit embedding procedures must be considered.
Easy with a Python2/3 one-liner:
$ python -c 'print u"\u2620"' # python2
$ python3 -c 'print(u"\u2620")' # python3
Results in:
?
To return only one row use LIMIT 1
:
SELECT *
FROM tbl_foo
WHERE name = 'sarmen'
LIMIT 1
It doesn't make sense to say 'first row' or 'last row' unless you have an ORDER BY
clause. Assuming you add an ORDER BY
clause then you can use LIMIT in the following ways:
LIMIT 1
.LIMIT 1, 1
.LIMIT 1
.The usual way to do this is something like the following.
test1.py
def some_func():
print 'in test 1, unproductive'
if __name__ == '__main__':
# test1.py executed as script
# do something
some_func()
service.py
import test1
def service_func():
print 'service func'
if __name__ == '__main__':
# service.py executed as script
# do something
service_func()
test1.some_func()
Add this to build.gradle file
dexOptions {
javaMaxHeapSize "2g"
}
Don't forget that if you are running your project from a particular Eclipse configuration, you should change the Java Runtime within 'Run Configurations' --> 'Your maven configuration' --> 'JRE tab'after you add the right JDK to your Eclipse preferences.
In my case, It was because of my target processor (x64) I changed it to x86 cleaned the project, restarted VS(2012) and rebuilt the project; then it was gone.
The npm module anyid provides flexible API to generate various kinds of string ID / code.
To generate random string in A-Za-z0-9 using 48 random bytes:
const id = anyid().encode('Aa0').bits(48 * 8).random().id();
// G4NtiI9OYbSgVl3EAkkoxHKyxBAWzcTI7aH13yIUNggIaNqPQoSS7SpcalIqX0qGZ
To generate fixed length alphabet only string filled by random bytes:
const id = anyid().encode('Aa').length(20).random().id();
// qgQBBtDwGMuFHXeoVLpt
Internally it uses crypto.randomBytes()
to generate random.
From Prepared statements and stored procedures
Use bindParam
to insert multiple rows with one time binding:
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
Rewriting a file in place is often done by saving the old copy with a modified name. Unix folks add a ~
to mark the old one. Windows folks do all kinds of things -- add .bak or .old -- or rename the file entirely or put the ~ on the front of the name.
import shutil
shutil.move( afile, afile+"~" )
destination= open( aFile, "w" )
source= open( aFile+"~", "r" )
for line in source:
destination.write( line )
if <some condition>:
destination.write( >some additional line> + "\n" )
source.close()
destination.close()
Instead of shutil
, you can use the following.
import os
os.rename( aFile, aFile+"~" )
Just use the *args
parameter, which allows you to pass as many arguments as you want after your a,b,c
. You would have to add some logic to map args
->c,d,e,f
but its a "way" of overloading.
def myfunc(a,b, *args, **kwargs):
for ar in args:
print ar
myfunc(a,b,c,d,e,f)
And it will print values of c,d,e,f
Similarly you could use the kwargs
argument and then you could name your parameters.
def myfunc(a,b, *args, **kwargs):
c = kwargs.get('c', None)
d = kwargs.get('d', None)
#etc
myfunc(a,b, c='nick', d='dog', ...)
And then kwargs
would have a dictionary of all the parameters that are key valued after a,b
I add credentials for HttpWebRequest
.
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
Take out the method name from in your import statement. e.g.
import Dan.Vik.disp;
becomes:
import Dan.Vik;
This can be done in Kotlin like this:
var clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
var clip = ClipData.newPlainText("label", file.readText())
clipboard.primaryClip = clip
Where file.readText()
is your input string.
this should work just fine if you just need to show what time left, since JavaScript uses frames for its time you'll have get your End Time - The Time RN after that we can divide it by 1000 since apparently 1000 frames = 1 seconds, after that you can use the basic math of time, but there's still a problem to this code, since the calculation is static, it can't compensate for the different day total in a year (360/365/366), the bunch of IF after the calculation is to make it null if the time is lower than 0, hope this helps even though it's not exactly what you're asking :)
var now = new Date();
var end = new Date("End Time");
var total = (end - now) ;
var totalD = Math.abs(Math.floor(total/1000));
var years = Math.floor(totalD / (365*60*60*24));
var months = Math.floor((totalD - years*365*60*60*24) / (30*60*60*24));
var days = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24)/ (60*60*24));
var hours = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24)/ (60*60));
var minutes = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60)/ (60));
var seconds = Math.floor(totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60 - minutes*60);
var Y = years < 1 ? "" : years + " Years ";
var M = months < 1 ? "" : months + " Months ";
var D = days < 1 ? "" : days + " Days ";
var H = hours < 1 ? "" : hours + " Hours ";
var I = minutes < 1 ? "" : minutes + " Minutes ";
var S = seconds < 1 ? "" : seconds + " Seconds ";
var A = years == 0 && months == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0 ? "Sending" : " Remaining";
document.getElementById('txt').innerHTML = Y + M + D + H + I + S + A;
With the two previous steps stated above, you're still missing the foreign key constraint. This should work:
class AddUserReferenceToTester < ActiveRecord::Migration
def change
add_column :testers, :user_id, :integer, references: :users
end
end
If this need to be done in UIBarButtonItem, additional wrapping in view should be used
This will work
let view = UIView()
let button = UIButton()
button.setTitle("Skip", for: .normal)
button.setImage(#imageLiteral(resourceName:"forward_button"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.sizeToFit()
view.addSubview(button)
view.frame = button.bounds
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)
This won't work
let button = UIButton()
button.setTitle("Skip", for: .normal)
button.setImage(#imageLiteral(resourceName:"forward_button"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.sizeToFit()
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
To script this:
pid=$(lsof -ti tcp:8080)
if [[ $pid ]]; then
kill -9 $pid
fi
The -t
argument makes the output of lsof "terse" which means that it only returns the PID.
In openCV's documentation there is an example for getting video frame by frame. It is written in c++ but it is very easy to port the example to python - you can search for each fumction documentation to see how to call them in python.
#include "opencv2/opencv.hpp"
using namespace cv;
int main(int, char**)
{
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat edges;
namedWindow("edges",1);
for(;;)
{
Mat frame;
cap >> frame; // get a new frame from camera
cvtColor(frame, edges, CV_BGR2GRAY);
GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
imshow("edges", edges);
if(waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
System.IO.File.ReadLines()
is perfect for this scenario. It returns all the lines of a file, but lets you begin iterating over the lines immediately which means it does not have to store the entire contents in memory.
Requires .NET 4.0 or higher.
foreach ($line in [System.IO.File]::ReadLines($filename)) {
# do something with $line
}
I like this solution best. Simple, scalable, responsive. The idea here is to create a zero-height outer div with bottom padding set to the aspect ratio of the video. The iframe is scaled to 100% in both width and height, completely filling the outer container. The outer container automatically adjusts its height according to its width, and the iframe inside adjusts itself accordingly.
<div style="position:relative; width:100%; height:0px; padding-bottom:56.25%;">
<iframe style="position:absolute; left:0; top:0; width:100%; height:100%"
src="http://www.youtube.com/embed/RksyMaJiD8Y">
</iframe>
</div>
The only variable here is the padding-bottom value in the outer div. It's 75% for 4:3 aspect ratio videos, and 56.25% for widescreen 16:9 aspect ratio videos.
It's pretty straightforward with some simple rules:
then
, return it - any promise you don't return will not be waited for outside..all
them - that way it waits for all the promises and no error from any of them are silenced.then
s, you can typically return in the middle - then
chains are usually at most 1 level deep.And some tips:
.map
than with for/push
- if you're mapping values with a function, map
lets you concisely express the notion of applying actions one by one and aggregating the results.Promise.all
than to execute things one after the other - each waiting before the next.Ok, so let's get started:
var items = [1, 2, 3, 4, 5];
var fn = function asyncMultiplyBy2(v){ // sample async action
return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));
};
// map over forEach since it returns
var actions = items.map(fn); // run the function over all items
// we now have a promises array and we want to wait for it
var results = Promise.all(actions); // pass array of promises
results.then(data => // or just .then(console.log)
console.log(data) // [2, 4, 6, 8, 10]
);
// we can nest this of course, as I said, `then` chains:
var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(
data => Promise.all(data.map(fn))
).then(function(data){
// the next `then` is executed after the promise has returned from the previous
// `then` fulfilled, in this case it's an aggregate promise because of
// the `.all`
return Promise.all(data.map(fn));
}).then(function(data){
// just for good measure
return Promise.all(data.map(fn));
});
// now to get the results:
res2.then(function(data){
console.log(data); // [16, 32, 48, 64, 80]
});
TL;DR:
pip install -Iv
(i.e. pip install -Iv MySQL_python==1.2.2
)First, I see two issues with what you're trying to do. Since you already have an installed version, you should either uninstall the current existing driver or use pip install -I MySQL_python==1.2.2
However, you'll soon find out that this doesn't work. If you look at pip's installation log, or if you do a pip install -Iv MySQL_python==1.2.2
you'll find that the PyPI URL link does not work for MySQL_python v1.2.2. You can verify this here: http://pypi.python.org/pypi/MySQL-python/1.2.2
The download link 404s and the fallback URL links are re-directing infinitely due to sourceforge.net's recent upgrade and PyPI's stale URL.
So to properly install the driver, you can follow these steps:
pip uninstall MySQL_python
pip install -Iv http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.2/MySQL-python-1.2.2.tar.gz/download
Using the Regex methods in .NET you should be able to match any non-numeric digit using \D, like so:
phoneNumber = Regex.Replace(phoneNumber, "\\D", String.Empty);
The quick answer I suggest is:
response.Result.Content.ReadAsStringAsync().Result
CouchDB and MySQL are two very different beasts. JSON is the native way to store stuff in CouchDB. In MySQL, the best you could do is store JSON data as text in a single field. This would entirely defeat the purpose of storing it in an RDBMS and would greatly complicate every database transaction.
Don't.
Having said that, FriendFeed seemed to use an extremely custom schema on top of MySQL. It really depends on what exactly you want to store, there's hardly one definite answer on how to abuse a database system so it makes sense for you. Given that the article is very old and their main reason against Mongo and Couch was immaturity, I'd re-evaluate these two if MySQL doesn't cut it for you. They should have grown a lot by now.
There is a case I make: exception happen in somewhere, but I catched the exception without print anything, thus the code didn't even reach the log4j code, so no output.
You can also resize the image to the desired width and height. For example:
<p align="center">
<img src="https://anyserver.com/image.png" width="750px" height="300px"/></p>
To add a centered caption to the image, just one more line:
<p align="center">This is a centered caption for the image<p align="center">
Fortunately, this works both for README.md and the GitHub Wiki pages.
You can hijack your Android audio port using an Arduino board like this. Then, you have two options (as far as I'm concerned):
1) Buy another Arduino Shield that supports RFID. I haven't seen one that supports UHF so far.
2) Try to connect your Arduino hijack with a USB RFID reader and build some embedded hardware kit.
Right now, I'm working in the second option but with iPhone.
Run php --ini
and notice file path on Loaded Configuration File
.
Then run command like cat -n /etc/php/7.2/cli/php.ini | grep intl
to find if the extension is commented or not.
Then update loaded configuration file by commenting line by adding ;
such as ;extension=intl
This can happen when you install php-intl
package and also enable the same extension on php.ini
file.
Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64
macro and other printf
issues altogether:
#include <fmt/core.h>
int main() {
uint64_t ui64 = 90;
fmt::print("test uint64_t : {}\n", ui64);
}
The formatting facility based on this library is proposed for standardization in C++20: P0645.
Disclaimer: I'm the author of {fmt}.
SELECT * FROM my_table
WHERE UPPER(some_field) != some_field
This should work with funny characters like åäöøüæï. You might need to use a language-specific utf-8 collation for the table.
"WORKSPACE" environment variable works for the latest version of Jenkins Pipeline. You can use this in your Jenkins file: "${env.WORKSPACE}"
Sample use below:
def files = findFiles glob: '**/reports/*.json'
for (def i=0; i<files.length; i++) {
jsonFilePath = "${files[i].path}"
jsonPath = "${env.WORKSPACE}" + "/" + jsonFilePath
echo jsonPath
hope that helps!!
If you happen to be using the venv module that comes with Python 3.3+, it supports an --upgrade
option.
Per the docs:
Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place
python3 -m venv --upgrade ENV_DIR
Ajay Kumar offers the simplest echo +$numString; I use these:
echo round($val = "0005");
echo $val = 0005;
//both output 5
echo round($val = 00000648370000075845);
echo round($val = "00000648370000075845");
//output 648370000075845, no need to care about the other zeroes in the number
//like with regex or comparative functions. Works w/wo single/double quotes
Actually any math function will take the number from the "string" and treat it like so. It's much simpler than any regex or comparative functions. I saw that in php.net, don't remember where.
From all my searching around, I strongly say that the most practical, accurate and free data source is provided by GeoNames.
You can access their data in 2 ways:
The way more simple is use this.$emit
Father.vue
<template>
<div>
<h1>{{ message }}</h1>
<child v-on:listenerChild="listenerChild"/>
</div>
</template>
<script>
import Child from "./Child";
export default {
name: "Father",
data() {
return {
message: "Where are you, my Child?"
};
},
components: {
Child
},
methods: {
listenerChild(reply) {
this.message = reply;
}
}
};
</script>
Child.vue
<template>
<div>
<button @click="replyDaddy">Reply Daddy</button>
</div>
</template>
<script>
export default {
name: "Child",
methods: {
replyDaddy() {
this.$emit("listenerChild", "I'm here my Daddy!");
}
}
};
</script>
My full example: https://codesandbox.io/s/update-parent-property-ufj4b
I had the same problem and I solved it by using an absolute import instead of a relative one.
for example in your case, you will write something like this:
from app.mymodule import myclass
You can see in the documentation.
Note that relative imports are based on the name of the current module. Since the name of the main module is always "
__main__
", modules intended for use as the main module of a Python application must always use absolute imports.
I prefer skipping it, I read somewhere that interfaces are by default, public
and abstract
.
To my surprise the book - Head First Design Patterns, is using public
with interface declaration and interface methods... that made me rethink once again and I landed up on this post.
Anyways, I think redundant information should be ignored.
I have made a registry edit script to open Cygwin at any folder you right click. It's on my GitHub.
Sample RegEdit
code from Github for 64-bit machines:
REGEDIT4
[HKEY_CLASSES_ROOT\Directory\shell\CygwinHere]
@="&Cygwin Bash Here"
[HKEY_CLASSES_ROOT\Directory\shell\CygwinHere\command]
@="C:\\cygwin64\\bin\\mintty.exe -i /Cygwin-Terminal.ico C:\\cygwin64\\bin\\bash.exe --login -c \"cd \\\"%V\\\" ; exec bash -rcfile ~/.bashrc\""
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\Background\shell\CygwinHere]
@="&Cygwin Bash Here"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\Background\shell\CygwinHere\command]
@="C:\\cygwin64\\bin\\mintty.exe -i /Cygwin-Terminal.ico C:\\cygwin64\\bin\\bash.exe --login -c \"cd \\\"%V\\\" ; exec bash -rcfile ~/.bashrc\""
In case anyone face pip issue like below
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
The root cause is openssl 1.1 doesn’t support python 3.6 anymore. So you need to install old version openssl 1.0
here is the solution:
brew uninstall --ignore-dependencies openssl
brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb
This code has been tested and works on Android 4.4
Spinner spinner = (Spinner) activity.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_spinner_dropdown_item) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
if (position == getCount()) {
((TextView)v.findViewById(android.R.id.text1)).setText("");
((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
}
return v;
}
@Override
public int getCount() {
return super.getCount()-1; // you dont display last item. It is used as hint.
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Daily");
adapter.add("Two Days");
adapter.add("Weekly");
adapter.add("Monthly");
adapter.add("Three Months");
adapter.add("HINT_TEXT_HERE"); //This is the text that will be displayed as hint.
spinner.setAdapter(adapter);
spinner.setSelection(adapter.getCount()); //set the hint the default selection so it appears on launch.
spinner.setOnItemSelectedListener(this);
Inline version:
<a href="http://yoursite.com/" style="text-decoration:none">yoursite</a>
However remember that you should generally separate the content of your website (which is HTML), from the presentation (which is CSS). Therefore you should generally avoid inline styles.
See John's answer to see equivalent answer using CSS.
Something like this should work:
UPDATE
table_Name
SET
column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
ID = @ID
With modern Python Exceptions, you don't need to abuse .message
, or override .__str__()
or .__repr__()
or any of it. If all you want is an informative message when your exception is raised, do this:
class MyException(Exception):
pass
raise MyException("My hovercraft is full of eels")
That will give a traceback ending with MyException: My hovercraft is full of eels
.
If you want more flexibility from the exception, you could pass a dictionary as the argument:
raise MyException({"message":"My hovercraft is full of animals", "animal":"eels"})
However, to get at those details in an except
block is a bit more complicated. The details are stored in the args
attribute, which is a list. You would need to do something like this:
try:
raise MyException({"message":"My hovercraft is full of animals", "animal":"eels"})
except MyException as e:
details = e.args[0]
print(details["animal"])
It is still possible to pass in multiple items to the exception and access them via tuple indexes, but this is highly discouraged (and was even intended for deprecation a while back). If you do need more than a single piece of information and the above method is not sufficient for you, then you should subclass Exception
as described in the tutorial.
class MyError(Exception):
def __init__(self, message, animal):
self.message = message
self.animal = animal
def __str__(self):
return self.message
I would handle it like so:
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'watch-me') {
$('#show-me').show();
}
else {
$('#show-me').hide();
}
});
});
if (text[0] == '\0')
{
/* Code... */
}
Use this if you're coding for micro-controllers with little space on flash and/or RAM. You will waste a lot more flash using strlen
than checking the first byte.
The above example is the fastest and less computation is required.
Possible solution
If you want fix the column you should set width. For example:
<td style="width:100px;">some data</td>
Just to add to others, a note specific to forking.
It's good to realize that technically, cloning the repo and forking the repo are the same thing. Do:
git clone $some_other_repo
and you can tap yourself on the back---you have just forked some other repo.
Git, as a VCS, is in fact all about cloning forking. Apart from "just browsing" using remote UI such as cgit, there is very little to do with git repo that does not involve forking cloning the repo at some point.
However,
when someone says I forked repo X, they mean that they have created a clone of the repo somewhere else with intention to expose it to others, for example to show some experiments, or to apply different access control mechanism (eg. to allow people without Github access but with company internal account to collaborate).
Facts that: the repo is most probably created with other command than
git clone
, that it's most probably hosted somewhere on a server as
opposed to somebody's laptop, and most probably has slightly different
format (it's a "bare repo", ie. without working tree) are all just
technical details.
The fact that it will most probably contain different set of branches, tags or commits is most probably the reason why they did it in the first place.
(What Github does when you click "fork", is just cloning with added sugar: it clones the repo for you, puts it under your account, records the "forked from" somewhere, adds remote named "upstream", and most importantly, plays the nice animation.)
When someone says I cloned repo X, they mean that they have created a clone of the repo locally on their laptop or desktop with intention study it, play with it, contribute to it, or build something from source code in it.
The beauty of Git is that it makes this all perfectly fit together: all these repos share the common part of block commit chain so it's possible to safely (see note below) merge changes back and forth between all these repos as you see fit.
Note: "safely" as long as you don't rewrite the common part of the chain, and as long as the changes are not conflicting.
%PROGRAMFILES%\Git\etc
profile
HOME="c:\location_were_you_want_gitconfig"
Note: The file permissions are usually restricted, so change them accordingly or you won't be able to save your changes.
You may use this
/^(?:(?:\+|0{0,2})91(\s*|[\-])?|[0]?)?([6789]\d{2}([ -]?)\d{3}([ -]?)\d{4})$/
Valid Entries:
6856438922
7856128945
8945562713
9998564723
+91-9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 9883443344
+91-785-612-8945
+91 999 856 4723
Invalid Entries:
WAQU9876567892
ABCD9876541212
0226-895623124
0924645236
0222-895612
098-8956124
022-2413184
Validate it at https://regex101.com/
I had issues with spaces showing in between my output and there was no answer online at all to fix this issue. I literally spend many hours trying to find a solution and found one from playing around with the code to the point that I almost did not even know what I typed in at the time that I got it to work. Here is my fix for the issue: [System.Text.Encoding]::UTF8.GetString(([System.Convert]::FromBase64String($base64string)|?{$_}))
Target-Action allows three different forms of action selector:
- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event
I suggest to instead this lines
<div>
<asp:TextBox runat="server" ID="username" />
<asp:RequiredFieldValidator ErrorMessage="The username is required" ControlToValidate="username" runat="server" Text=" - Required" />
</div>
by this line
<div>
<asp:TextBox runat="server" ID="username" required />
</div>
You can't use named parameters in JDBC itself. You could try using Spring framework, as it has some extensions that allow the use of named parameters in queries.
To post a clarification answer here for those who get directed here by Google.
The document size includes everything in the document including the subdocuments, nested objects etc.
So a document of:
{
"_id": {},
"na": [1, 2, 3],
"naa": [
{ "w": 1, "v": 2, "b": [1, 2, 3] },
{ "w": 5, "b": 2, "h": [{ "d": 5, "g": 7 }, {}] }
]
}
Has a maximum size of 16 MB.
Subdocuments and nested objects are all counted towards the size of the document.
Some cron implementations support the "L" flag to represent the last day of the month.
If you're lucky to be using one of those implementations, it's as simple as:
0 55 23 L * ?
That will run at 11:55 pm on the last day of every month.
http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger
That is because of server SQL Mode - NO_ZERO_DATE.
From the reference: NO_ZERO_DATE
- In strict mode, don't allow '0000-00-00'
as a valid date. You can still insert zero dates with the IGNORE option. When not in strict mode, the date is accepted but a warning is generated.
Or... You can use Blob to achive this.
Like:
pdf.addHTML($('#content'), y, x, options, function () {
var blob = pdf.output("blob");
window.open(URL.createObjectURL(blob));
});
That code let you create a Blob object inside the browser and show it in the new tab.
Unlike centralized version control systems, Git clones the entire repository, so you don't only get the current remote files, but the whole history. You local repository will include all this.
There might have been tags to mark a particular version at the time. If not, you can create them yourself locally. A good way to do this is to use git log
or perhaps more visually with tools like gitk
(perhaps gitk --all
to see all the branches and tags). If you can spot the commits hashes that were used at the time, you can tag them using git tag <hash>
and then check those out in new working copies (for example git checkout -b new_branch_name tag_name
or directly with the hash instead of the tag name).
Here's how I get there using Version 3.0.6 on Windows
Use
[self dismissViewControllerAnimated:NO completion:nil];
I found that The Boolean Expression Reducer is much easier to use than Logic Friday. Plus it doesn't require installation and is multi-platform (Java).
Also in Logic Friday the expression A | B
just returns 3 entries in truth table; I expected 4.
it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.
Way better idea to add that host or ip to the .ssh/config
file like so:
Host (a space separated list of made up aliases you want to use for the host)
User git
Hostname (ip or hostname of git server)
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_(the key you want for this repo)
The first option's text will always display as default title.
<select>
<option value ="">What is the name of your city?</option>
<option value ="sydney">Sydney</option>
<option value ="melbourne">Melbourne</option>
<option value ="cromwell">Cromwell</option>
<option value ="queenstown">Queenstown</option>
</select>
Agreed with Richard Garside's short answer, but instead of using prop()
in $(this).prop("checked")
you can use native JS checked
property of checkbox like,
$("#checkAll").change(function () {_x000D_
$("input:checkbox").prop('checked', this.checked);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form action="#">_x000D_
<p><label><input type="checkbox" id="checkAll"/> Check all</label></p>_x000D_
_x000D_
<fieldset>_x000D_
<legend>Loads of checkboxes</legend>_x000D_
<p><label><input type="checkbox" /> Option 1</label></p>_x000D_
<p><label><input type="checkbox" /> Option 2</label></p>_x000D_
<p><label><input type="checkbox" /> Option 3</label></p>_x000D_
<p><label><input type="checkbox" /> Option 4</label></p>_x000D_
</fieldset>_x000D_
</form>
_x000D_
Or like this:
List< KeyValuePair< string, int > > theList =
new List< KeyValuePair< string,int > >(this.yourDictionary);
for ( int i = 0; i < theList.Count; i++)
{
// the key
Console.WriteLine(theList[i].Key);
}
Tested in mysql 5.Dont know about other versions. If you want to keep the row with the lowest id value:
DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE n1.id > n2.id AND n1.member_id = n2.member_id and n1.answer_num =n2.answer_num
If you want to keep the row with the highest id value:
DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE n1.id < n2.id AND n1.member_id = n2.member_id and n1.answer_num =n2.answer_num
In Eclipse, go to Window → Preferences → General → Network Connections. In the Active Provider combo box, choose "Manual". In the proxy entries table, for each entry click "Edit..." and supply your proxy host, port, username and password details.
Use this JavaScript.
$(":input").inputmask();
$("#phone").inputmask({"mask": "(999) 999-9999"});
You need to apply
the event handler in the context of that element:
var elem = document.getElementById("linkid");
if (typeof elem.onclick == "function") {
elem.onclick.apply(elem);
}
Otherwise this
would reference the context the above code is executed in.
import java.util.Scanner;
import java.util.*;
public class Main
{
public static void main (String[]args) throws Exception
{
Scanner in = new Scanner (System.in);
/*Prints out the welcome message at the top of the screen */
System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf ("%55s", "=================================\n");
String[] codes =
{
"G22", "K13", "I30", "S20"};
System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
codes[3]);
System.out.printf ("Enter one of the above!\n");
String usercode = in.nextLine ();
for (int i = 0; i < codes.length; i++)
{
if (codes[i].equals (usercode))
{
System.out.printf ("What's the matter with you?\n");
}
else
{
System.out.printf ("Youda man!");
}
}
}
}
Probably you've found how to do it, but you can call
ListView.setItemsCanFocus(true)
and now your buttons will catch focus
In my case
-Djava.awt.headless=true
was set (indirectly by a Maven configuration). I had to actively use
-Djava.awt.headless=false
to override this.
I suggest, you use the MaskedTextBox: http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
You can select every column from that sub-query by aliasing it and adding the alias before the *
:
SELECT t.*, a+b AS total_sum
FROM
(
SELECT SUM(column1) AS a, SUM(column2) AS b
FROM table
) t
The height of a binary search tree is equal to number of layers - 1
.
See the diagram at http://en.wikipedia.org/wiki/Binary_tree
Your recursion is good, so just subtract one at the root level.
Also note, you can clean up the function a bit by handling null nodes:
int findHeight(node) {
if (node == null) return 0;
return 1 + max(findHeight(node.left), findHeight(node.right));
}
In Windows, you can follow these steps which worked for me.
git config --system core.longpaths true
This will allow accessing long paths globally
And now you can clone the repository with no issues with long paths
Some compilers might create issues with this - on a Mac C++ compiler, EXIT_SUCCESS worked fine for me but on a Linux C++ complier I had to add cstdlib for it to know what EXIT_SUCCESS is. Other than that, they are one and the same.
You can pass in a pointer to a time_t
object that time
will fill up with the current time (and the return value is the same one that you pointed to). If you pass in NULL
, it just ignores it and merely returns a new time_t
object that represents the current time.
This works for comma separated values
DECLARE @ARC_CHECKNUM VARCHAR(MAX)
SET @ARC_CHECKNUM = 'ABC,135,MED,ASFSDFSF,AXX'
SELECT ' AND (a.arc_checknum LIKE ''%' + REPLACE(@arc_checknum,',','%'' OR a.arc_checknum LIKE ''%') + '%'')''
Evaluates to:
AND (a.arc_checknum LIKE '%ABC%' OR a.arc_checknum LIKE '%135%' OR a.arc_checknum LIKE '%MED%' OR a.arc_checknum LIKE '%ASFSDFSF%' OR a.arc_checknum LIKE '%AXX%')
If you want it to use indexes, you must omit the first '%'
character.
You can do so by creating an array of dtype=object
. If you try to assign a long string to a normal numpy array, it truncates the string:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'],
dtype='|S6')
But when you use dtype=object
, you get an array of python object references. So you can have all the behaviors of python strings:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)
Indeed, because it's an array of objects, you can assign any kind of python object to the array:
>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)
However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:
>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop
Suppose your hex string is something like
>>> hex_string = "deadbeef"
>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"
>>> bytes.fromhex(hex_string) # Python = 3
b'\xde\xad\xbe\xef'
>>> bytearray.fromhex(hex_string)
bytearray(b'\xde\xad\xbe\xef')
Note that bytes
is an immutable version of bytearray
.
see here enter link description here
html
<body>
<p>This is a paragraph.</p>
<div id="myPosition">
</div>
</body>
css
#myPosition{
background-color:red;
height:200px;
width:200px;
}
jquery
$(document).ready(function(){
$("#myPosition").click(function(e){
var elm = $(this);
var xPos = e.pageX - elm.offset().left;
var yPos = e.pageY - elm.offset().top;
alert("X position: " + xPos + ", Y position: " + yPos);
});
});
add
compile 'com.mcxiaoke.volley:library:1.0.19'
compile project('volley')
in the dependencies, under build.gradle file of your app
DO NOT DISTURB THE build.gradle FILE OF YOUR LIBRARY. IT'S YOUR APP'S GRADLE FILE ONLY YOU NEED TO ALTER
PHP-like passthru
import { spawn } from 'child_process';
export default async function passthru(exe, args, options) {
return new Promise((resolve, reject) => {
const env = Object.create(process.env);
const child = spawn(exe, args, {
...options,
env: {
...env,
...options.env,
},
});
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', data => console.log(data));
child.stderr.on('data', data => console.log(data));
child.on('error', error => reject(error));
child.on('close', exitCode => {
console.log('Exit code:', exitCode);
resolve(exitCode);
});
});
}
Usage
const exitCode = await passthru('ls', ['-al'], { cwd: '/var/www/html' })
The JDK has switched locations of java.exe between 1.6 and 1.7!!!
In my case I found that the JAVA_HOME for the JDK had to add the \jre on the end. The mvn bat file is looking for java.exe and it looks for it in JAVA_HOME\bin. Its not there for JDK 1.7; it is in JAVA_HOME\jre\bin. In JDK 1.6 such it IS in JAVA_HOME\bin.
Hope this helps somebody.
There are some good answers already. I'll focus mainly on what I think they lack - an explanation of the "cons" with the copy-and-swap idiom....
What is the copy-and-swap idiom?
A way of implementing the assignment operator in terms of a swap function:
X& operator=(X rhs)
{
swap(rhs);
return *this;
}
The fundamental idea is that:
the most error-prone part of assigning to an object is ensuring any resources the new state needs are acquired (e.g. memory, descriptors)
that acquisition can be attempted before modifying the current state of the object (i.e. *this
) if a copy of the new value is made, which is why rhs
is accepted by value (i.e. copied) rather than by reference
swapping the state of the local copy rhs
and *this
is usually relatively easy to do without potential failure/exceptions, given the local copy doesn't need any particular state afterwards (just needs state fit for the destructor to run, much as for an object being moved from in >= C++11)
When should it be used? (Which problems does it solve [/create]?)
When you want the assigned-to objected unaffected by an assignment that throws an exception, assuming you have or can write a swap
with strong exception guarantee, and ideally one that can't fail/throw
..†
When you want a clean, easy to understand, robust way to define the assignment operator in terms of (simpler) copy constructor, swap
and destructor functions.
† swap
throwing: it's generally possible to reliably swap data members that the objects track by pointer, but non-pointer data members that don't have a throw-free swap, or for which swapping has to be implemented as X tmp = lhs; lhs = rhs; rhs = tmp;
and copy-construction or assignment may throw, still have the potential to fail leaving some data members swapped and others not. This potential applies even to C++03 std::string
's as James comments on another answer:
@wilhelmtell: In C++03, there is no mention of exceptions potentially thrown by std::string::swap (which is called by std::swap). In C++0x, std::string::swap is noexcept and must not throw exceptions. – James McNellis Dec 22 '10 at 15:24
‡ assignment operator implementation that seems sane when assigning from a distinct object can easily fail for self-assignment. While it might seem unimaginable that client code would even attempt self-assignment, it can happen relatively easily during algo operations on containers, with x = f(x);
code where f
is (perhaps only for some #ifdef
branches) a macro ala #define f(x) x
or a function returning a reference to x
, or even (likely inefficient but concise) code like x = c1 ? x * 2 : c2 ? x / 2 : x;
). For example:
struct X
{
T* p_;
size_t size_;
X& operator=(const X& rhs)
{
delete[] p_; // OUCH!
p_ = new T[size_ = rhs.size_];
std::copy(p_, rhs.p_, rhs.p_ + rhs.size_);
}
...
};
On self-assignment, the above code delete's x.p_;
, points p_
at a newly allocated heap region, then attempts to read the uninitialised data therein (Undefined Behaviour), if that doesn't do anything too weird, copy
attempts a self-assignment to every just-destructed 'T'!
? The copy-and-swap idiom can introduce inefficiencies or limitations due to the use of an extra temporary (when the operator's parameter is copy-constructed):
struct Client
{
IP_Address ip_address_;
int socket_;
X(const X& rhs)
: ip_address_(rhs.ip_address_), socket_(connect(rhs.ip_address_))
{ }
};
Here, a hand-written Client::operator=
might check if *this
is already connected to the same server as rhs
(perhaps sending a "reset" code if useful), whereas the copy-and-swap approach would invoke the copy-constructor which would likely be written to open a distinct socket connection then close the original one. Not only could that mean a remote network interaction instead of a simple in-process variable copy, it could run afoul of client or server limits on socket resources or connections. (Of course this class has a pretty horrid interface, but that's another matter ;-P).
While Ansible is still debating to implement state = empty
https://github.com/ansible/ansible-modules-core/issues/902
my_folder: "/home/mydata/web/"
empty_path: "/tmp/empty"
- name: "Create empty folder for wiping."
file:
path: "{{ empty_path }}"
state: directory
- name: "Wipe clean {{ my_folder }} with empty folder hack."
synchronize:
mode: push
#note the backslash here
src: "{{ empty_path }}/"
dest: "{{ nl_code_path }}"
recursive: yes
delete: yes
delegate_to: "{{ inventory_hostname }}"
Note though, with synchronize you should be able to sync your files (with delete) properly anyway.
I think what you want is to have access to the request context, see RequestContext.
Your mistake is using new DateTime()
, which returns January 1, 0001 at 00:00:00.000 instead of current date and time. The correct syntax to get current date and time is DateTime.Now, so change this:
String timeStamp = GetTimestamp(new DateTime());
to this:
String timeStamp = GetTimestamp(DateTime.Now);
This should works for empty dir (You may need to check if the second string starts with /
which should be treat as an absolute path?):
#!/bin/bash
join_path() {
echo "${1:+$1/}$2" | sed 's#//#/#g'
}
join_path "" a.bin
join_path "/data" a.bin
join_path "/data/" a.bin
Output:
a.bin
/data/a.bin
/data/a.bin
Reference: Shell Parameter Expansion
First your code is not compiled. Line Long b = 1113;
is wrong. You have to say
Long b = 1113L;
Second when I fixed this compilation problem the code printed "not equals".
If you want to use data binding you can follow this solution The following solution might be a better one to follow. the layout is in fragment_my.xml
<data>
<variable
name="listener"
type="my_package.MyListener" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/moreTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{() -> listener.onClick()}"
android:text="@string/login"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
And the Fragment would be as follows
class MyFragment : Fragment(), MyListener {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return FragmentMyBinding.inflate(
inflater,
container,
false
).apply {
lifecycleOwner = viewLifecycleOwner
listener = this@MyFragment
}.root
}
override fun onClick() {
TODO("Not yet implemented")
}
}
interface MyListener{
fun onClick()
}
@All the issue is because of the latest major breaking changes in the google play service and firebase June 17, 2019 release.
If you are on Ionic or Cordova project. Please go through all the plugins where it has dependency google play service and firebase service with + mark
Example:
In my firebase cordova integration I had com.google.firebase:firebase-core:+ com.google.firebase:firebase-messaging:+ So the plus always downloading the latest release which was causing error. Change + with version number as per the March 15, 2019 release https://developers.google.com/android/guides/releases
Make sure to replace + symbols with actual version in build.gradle file of cordova library
In Rails 3, Application specific custom configuration data can be placed in the application configuration object. The configuration can be assigned in the initialization files or the environment files -- say for a given application MyApp
:
MyApp::Application.config.custom_config_variable = :my_config_setting
or
Rails.configuration.custom_config_variable = :my_config_setting
To read the setting, simply call the configuration variable without setting it:
Rails.configuration.custom_config_variable
=> :my_config_setting
UPDATE Rails 4
In Rails 4 there a new way for this => http://guides.rubyonrails.org/configuring.html#custom-configuration
The copy
command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;
After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;
With SQL Developer, you could do the following to perform a similar approach to copying objects:
On the tool bar, select Tools>Database copy.
Identify source and destination connections with the copy options you would like.
For object type, select table(s).
The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).
As others have said: return value, not out param.
May I recommend to you the book "Framework Design Guidelines" (2nd ed)? Pages 184-185 cover the reasons for avoiding out params. The whole book will steer you in the right direction on all sorts of .NET coding issues.
Allied with Framework Design Guidelines is the use of the static analysis tool, FxCop. You'll find this on Microsoft's sites as a free download. Run this on your compiled code and see what it says. If it complains about hundreds and hundreds of things... don't panic! Look calmly and carefully at what it says about each and every case. Don't rush to fix things ASAP. Learn from what it is telling you. You will be put on the road to mastery.
"abcd4yyyy" | grep 4 -c
gives the count as 1
Restarting ADB server works for me, but no need to go for it from command line.
Ctrl + Maj + A -> Troubleshoot Device Connections -> Next -> Next -> Restart ADB Server
There is indeed such a tool, Comeau's C++ compiler. . It will generate C code which you can't manually maintain, but that's no problem. You'll maintain the C++ code, and just convert to C on the fly.
By the use of slice operator with step parameter which would cause evaluation of the queryset and create a list.
list_of_answers = answers[::1]
or initially you could have done:
answers = Answer.objects.filter(id__in=[answer.id for answer in
answer_set.answers.all()])[::1]
./
refers to the current working directory, except in the require()
function. When using require()
, it translates ./
to the directory of the current file called. __dirname
is always the directory of the current file.
For example, with the following file structure
/home/user/dir/files/config.json
{
"hello": "world"
}
/home/user/dir/files/somefile.txt
text file
/home/user/dir/dir.js
var fs = require('fs');
console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));
If I cd
into /home/user/dir
and run node dir.js
I will get
{ hello: 'world' }
text file
But when I run the same script from /home/user/
I get
{ hello: 'world' }
Error: ENOENT, no such file or directory './files/somefile.txt'
at Object.openSync (fs.js:228:18)
at Object.readFileSync (fs.js:119:15)
at Object.<anonymous> (/home/user/dir/dir.js:4:16)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
Using ./
worked with require
but not for fs.readFileSync
. That's because for fs.readFileSync
, ./
translates into the cwd (in this case /home/user/
). And /home/user/files/somefile.txt
does not exist.
The latest Java Web Start has been enhanced to allow good offline operation as well as allowing "local installation". It is worth looking into.
EDIT 2018: Java Web Start is no longer bundled with the newest JDK's. Oracle is pushing towards a "deploy your app locally with an enclosed JRE" model instead.
When we are going to migrate JQuery from 1.x to 2x or 3.x in our old existing application , then we will use .done,.fail instead of success,error as JQuery up gradation is going to be deprecated these methods.For example when we make a call to server web methods then server returns promise objects to the calling methods(Ajax methods) and this promise objects contains .done,.fail..etc methods.Hence we will the same for success and failure response. Below is the example(it is for POST request same way we can construct for request type like GET...)
$.ajax({
type: "POST",
url: url,
data: '{"name" :"sheo"}',
contentType: "application/json; charset=utf-8",
async: false,
cache: false
}).done(function (Response) {
//do something when get response })
.fail(function (Response) {
//do something when any error occurs.
});
For quick queries you can allow room to execute it on UI thread.
AppDatabase db = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, DATABASE_NAME).allowMainThreadQueries().build();
In my case I had to figure out of the clicked user in list exists in database or not. If not then create the user and start another activity
@Override
public void onClick(View view) {
int position = getAdapterPosition();
User user = new User();
String name = getName(position);
user.setName(name);
AppDatabase appDatabase = DatabaseCreator.getInstance(mContext).getDatabase();
UserDao userDao = appDatabase.getUserDao();
ArrayList<User> users = new ArrayList<User>();
users.add(user);
List<Long> ids = userDao.insertAll(users);
Long id = ids.get(0);
if(id == -1)
{
user = userDao.getUser(name);
user.setId(user.getId());
}
else
{
user.setId(id);
}
Intent intent = new Intent(mContext, ChatActivity.class);
intent.putExtra(ChatActivity.EXTRAS_USER, Parcels.wrap(user));
mContext.startActivity(intent);
}
}
The Bitwise complement operator(~) is a unary operator.
It works as per the following methods
First it converts the given decimal number to its corresponding binary value.That is in case of 2 it first convert 2 to 0000 0010 (to 8 bit binary number).
Then it converts all the 1 in the number to 0,and all the zeros to 1;then the number will become 1111 1101.
that is the 2's complement representation of -3.
In order to find the unsigned value using complement,i.e. simply to convert 1111 1101 to decimal (=4294967293) we can simply use the %u during printing.
Use option bty = "n"
in legend
to remove the box around the legend. For example:
legend(1, 5,
"This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",
bty = "n")
I couldn't find solution for other browsers. When I posted this question, IE was on the higher priority and gladly I found one for it. If you have a solution for other browsers (firefox, safari, opera) please do share here. Thanks.
VBSCRIPT is much more convenient than creating an ActiveX on VB6 or C#/VB.NET:
<script language='VBScript'>
Sub Print()
OLECMDID_PRINT = 6
OLECMDEXECOPT_DONTPROMPTUSER = 2
OLECMDEXECOPT_PROMPTUSER = 1
call WB.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER,1)
End Sub
document.write "<object ID='WB' WIDTH=0 HEIGHT=0 CLASSID='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2'></object>"
</script>
Now, calling:
<a href="javascript:window.print();">Print</a>
will send print without popup print window.
If you have installed using Homebrew, the below command should be enough.
brew services restart postgresql
This sometimes might not work. In that case, the below two commands should definitely work:
rm /usr/local/var/postgres/postmaster.pid
pg_ctl -D /usr/local/var/postgres start
Here is my approach, including some helper methods
export default class Enum {
constructor(name){
this.name = name;
}
static get values(){
return Object.values(this);
}
static forName(name){
for(var enumValue of this.values){
if(enumValue.name === name){
return enumValue;
}
}
throw new Error('Unknown value "' + name + '"');
}
toString(){
return this.name;
}
}
-
import Enum from './enum.js';
export default class ColumnType extends Enum {
constructor(name, clazz){
super(name);
this.associatedClass = clazz;
}
}
ColumnType.Integer = new ColumnType('Integer', Number);
ColumnType.Double = new ColumnType('Double', Number);
ColumnType.String = new ColumnType('String', String);
If folks want to read tags from the RedHat registry at https://registry.redhat.io/v2
then the steps are:
# example nodejs-12 image
IMAGE_STREAM=nodejs-12
REDHAT_REGISTRY_API="https://registry.redhat.io/v2/rhel8/$IMAGE_STREAM"
# Get an oAuth token based on a service account username and password https://access.redhat.com/articles/3560571
TOKEN=$(curl --silent -u "$REGISTRY_USER":"$REGISTRY_PASSWORD" "https://sso.redhat.com/auth/realms/rhcc/protocol/redhat-docker-v2/auth?service=docker-registry&client_id=curl&scope=repository:rhel:pull" | jq --raw-output '.token')
# Grab the tags
wget -q --header="Accept: application/json" --header="Authorization: Bearer $TOKEN" -O - "$REDHAT_REGISTRY_API/tags/list" | jq -r '."tags"[]'
If you want to compare what you have in your local openshift registry against what is in the upstream registry.redhat.com then here is a complete script.
This doesn't work in IE6, which may be an issue, but it'll work in IE7+ and Firefox, Safari etc. It'll align the 3rd column right and all of the subsequent columns left.
td + td + td { text-align: right; }
td + td + td + td { text-align: left; }
Sounds like you're expecting size_t
to be the same as unsigned long
(possibly 64 bits) when it's actually an unsigned int
(32 bits). Try using %zu
in both cases.
I'm not entirely certain though.
First of all, you can't pass to alert
second argument, use concatenation instead
alert("Input is " + inputValue);
However in order to get values from input better to use states like this
var MyComponent = React.createClass({_x000D_
getInitialState: function () {_x000D_
return { input: '' };_x000D_
},_x000D_
_x000D_
handleChange: function(e) {_x000D_
this.setState({ input: e.target.value });_x000D_
},_x000D_
_x000D_
handleClick: function() {_x000D_
console.log(this.state.input);_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<input type="text" onChange={ this.handleChange } />_x000D_
<input_x000D_
type="button"_x000D_
value="Alert the text input"_x000D_
onClick={this.handleClick}_x000D_
/>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
<MyComponent />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
As mentioned, there are crawler frameworks all ready for customizing out there, but if what you're doing is as simple as you mentioned, you could make it from scratch pretty easily.
Scraping the links: http://www.phpro.org/examples/Get-Links-With-DOM.html
Dumping results to a file: http://www.tizag.com/phpT/filewrite.php
Minor improvements to @Alex's answer that enables updating of dictionaries of differing depths as well as limiting the depth that the update dives into the original nested dictionary (but the updating dictionary depth is not limited). Only a few cases have been tested:
def update(d, u, depth=-1):
"""
Recursively merge or update dict-like objects.
>>> update({'k1': {'k2': 2}}, {'k1': {'k2': {'k3': 3}}, 'k4': 4})
{'k1': {'k2': {'k3': 3}}, 'k4': 4}
"""
for k, v in u.iteritems():
if isinstance(v, Mapping) and not depth == 0:
r = update(d.get(k, {}), v, depth=max(depth - 1, -1))
d[k] = r
elif isinstance(d, Mapping):
d[k] = u[k]
else:
d = {k: u[k]}
return d
The first thing I would suggest would be to split up the actual comparison so that it's a bit more readable (I've also taken out the ToString() - is that needed?):
else {
object originalProperty = sourceType.GetProperty(pi.Name).GetValue(this, null);
object comparisonProperty = destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null);
if (originalProperty != comparisonProperty)
return false;
The next suggestion would be to minimise the use of reflection as much as possible - it's really slow. I mean, really slow. If you are going to do this, I would suggest caching the property references. I'm not intimately familiar with the Reflection API, so if this is a bit off, just adjust to make it compile:
// elsewhere
Dictionary<object, Property[]> lookupDictionary = new Dictionary<object, Property[]>;
Property[] objectProperties = null;
if (lookupDictionary.ContainsKey(sourceType)) {
objectProperties = lookupProperties[sourceType];
} else {
// build array of Property references
PropertyInfo[] sourcePropertyInfos = sourceType.GetProperties();
Property[] sourceProperties = new Property[sourcePropertyInfos.length];
for (int i=0; i < sourcePropertyInfos.length; i++) {
sourceProperties[i] = sourceType.GetProperty(pi.Name);
}
// add to cache
objectProperties = sourceProperties;
lookupDictionary[object] = sourceProperties;
}
// loop through and compare against the instances
However, I have to say that I agree with the other posters. This smells lazy and inefficient. You should be implementing IComparable instead :-).
class Program
{
static void Main(string[] args)
{
Console.WriteLine("223232-1.jpg".GetUntilOrEmpty());
Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
Console.WriteLine("34443553-5.jpg".GetUntilOrEmpty());
Console.ReadKey();
}
}
static class Helper
{
public static string GetUntilOrEmpty(this string text, string stopAt = "-")
{
if (!String.IsNullOrWhiteSpace(text))
{
int charLocation = text.IndexOf(stopAt, StringComparison.Ordinal);
if (charLocation > 0)
{
return text.Substring(0, charLocation);
}
}
return String.Empty;
}
}
Results:
223232
443
34443553
344
34
this.getClass().getClassLoader().getResource("").getPath()
Maybe you can leverage the std::bitset
type available in C++11. It can be used to represent a fixed sequence of N
bits, which can be manipulated by conventional logic.
#include<iostream>
#include<bitset>
class MissileLauncher {
public:
MissileLauncher() {}
void show_bits() const {
std::cout<<m_abc[2]<<", "<<m_abc[1]<<", "<<m_abc[0]<<std::endl;
}
bool toggle_a() {
// toggles (i.e., flips) the value of `a` bit and returns the
// resulting logical value
m_abc[0].flip();
return m_abc[0];
}
bool toggle_c() {
// toggles (i.e., flips) the value of `c` bit and returns the
// resulting logical value
m_abc[2].flip();
return m_abc[2];
}
bool matches(const std::bitset<3>& mask) {
// tests whether all the bits specified in `mask` are turned on in
// this instance's bitfield
return ((m_abc & mask) == mask);
}
private:
std::bitset<3> m_abc;
};
typedef std::bitset<3> Mask;
int main() {
MissileLauncher ml;
// notice that the bitset can be "built" from a string - this masks
// can be made available as constants to test whether certain bits
// or bit combinations are "on" or "off"
Mask has_a("001"); // the zeroth bit
Mask has_b("010"); // the first bit
Mask has_c("100"); // the second bit
Mask has_a_and_c("101"); // zeroth and second bits
Mask has_all_on("111"); // all on!
Mask has_all_off("000"); // all off!
// I can even create masks using standard logic (in this case I use
// the or "|" operator)
Mask has_a_and_b = has_a | has_b;
std::cout<<"This should be 011: "<<has_a_and_b<<std::endl;
// print "true" and "false" instead of "1" and "0"
std::cout<<std::boolalpha;
std::cout<<"Bits, as created"<<std::endl;
ml.show_bits();
std::cout<<"is a turned on? "<<ml.matches(has_a)<<std::endl;
std::cout<<"I will toggle a"<<std::endl;
ml.toggle_a();
std::cout<<"Resulting bits:"<<std::endl;
ml.show_bits();
std::cout<<"is a turned on now? "<<ml.matches(has_a)<<std::endl;
std::cout<<"are both a and c on? "<<ml.matches(has_a_and_c)<<std::endl;
std::cout<<"Toggle c"<<std::endl;
ml.toggle_c();
std::cout<<"Resulting bits:"<<std::endl;
ml.show_bits();
std::cout<<"are both a and c on now? "<<ml.matches(has_a_and_c)<<std::endl;
std::cout<<"but, are all bits on? "<<ml.matches(has_all_on)<<std::endl;
return 0;
}
Compiling using gcc 4.7.2
g++ example.cpp -std=c++11
I get:
This should be 011: 011
Bits, as created
false, false, false
is a turned on? false
I will toggle a
Resulting bits:
false, false, true
is a turned on now? true
are both a and c on? false
Toggle c
Resulting bits:
true, false, true
are both a and c on now? true
but, are all bits on? false
Add it in milliseconds:
var currentDate = new Date();
var twentyMinutesLater = new Date(currentDate.getTime() + (20 * 60 * 1000));
I think that is a bad solution. If you want to pass a Function into component with @Input()
, @Output()
decorator is what you are looking for.
export class SuggestionMenuComponent {
@Output() onSuggest: EventEmitter<any> = new EventEmitter();
suggestionWasClicked(clickedEntry: SomeModel): void {
this.onSuggest.emit([clickedEntry, this.query]);
}
}
<suggestion-menu (onSuggest)="insertSuggestion($event[0],$event[1])">
</suggestion-menu>
Swift 5, XCode 11 storyboard way. I think this works for iOS 9 and higher. You want for example "Description" label to get the dynamic height, follow the steps:
1) Select description label -> Go to Attributes Inspector (pencil icon), set: Lines: 0 Line Break: Word Wrap
2) Select your UILabel from storyboard and go to Size Inspector (ruler icon), 3) Go down to "Content Compression Resistance Priority to 1 for all other UIView (lables, buttons, imageview, etc) components that are interacting with your label.
For example, I have UIImageView, Title Label, and Description Label vertically in my view. I set Content Compression Resistance Priority to UIImageView and title label to 1 and for description label to 750. This will make a description label to take as much as needed height.
Use the web browser control. This requires Adobe reader to be installed but most likely you have it anyway. Set the UrL of the control to the file location.
I just came up with a tricky way to get almost the same functionality. Instead of protecting the sheet the normal way, use an event handler to undo anything the user tries to do.
Add the following to the worksheet's module:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Locked = True Then
Application.EnableEvents = False
Application.Undo
Application.EnableEvents = True
End If
End Sub
If the user does anything to change a cell that's locked, the action will get immediately undone. The temporary disabling of events is to keep the undoing itself from triggering this event, resulting in an infinite loop.
Sorting and filtering do not trigger the Change event, so those functions remain enabled.
Note that this solution prevents changing or clearing cell contents, but does not prevent changing formats. A determined user could get around it by simply setting the cells to be unlocked.
In webpack.config.js replace loaders: [..] with rules: [..] It worked for me.
If you're in local machine then use this command
/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
For remote machine, use below one
/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
It's worth remembering C++'s origins in, and compatibility with, C.
C has structs, it has no concept of encapsulation, so everything is public.
Being public by default is generally considered a bad idea when taking an object-oriented approach, so in making a form of C that is natively conducive to OOP (you can do OO in C, but it won't help you) which was the idea in C++ (originally "C With Classes"), it makes sense to make members private by default.
On the other hand, if Stroustrup had changed the semantics of struct
so that its members were private by default, it would have broken compatibility (it is no longer as often true as the standards diverged, but all valid C programs were also valid C++ programs, which had a big effect on giving C++ a foothold).
So a new keyword, class
was introduced to be exactly like a struct, but private by default.
If C++ had come from scratch, with no history, then it would probably have only one such keyword. It also probably wouldn't have made the impact it made.
In general, people will tend to use struct when they are doing something like how structs are used in C; public members, no constructor (as long as it isn't in a union, you can have constructors in structs, just like with classes, but people tend not to), no virtual methods, etc. Since languages are as much to communicate with people reading the code as to instruct machines (or else we'd stick with assembly and raw VM opcodes) it's a good idea to stick with that.
Try to use 3rd party tool, such as SQL Data Examiner which compares Oracle databases and shows you differences.
var href = '(text-1) (red) (text-3) (text-4) (text-5)';_x000D_
_x000D_
var test = href.replace(/\((\b(?!red\b)[\s\S]*?)\)/g, testF); _x000D_
_x000D_
function testF(match, p1, p2, offset, str_full) {_x000D_
p1 = "-"+p1+"-";_x000D_
return p1;_x000D_
}_x000D_
_x000D_
console.log(test);
_x000D_
var href = '(text-1) (frede) (text-3) (text-4) (text-5)';_x000D_
_x000D_
var test = href.replace(/\(([\s\S]*?)\)/g, testF); _x000D_
_x000D_
function testF(match, p1, p2, offset, str_full) {_x000D_
p1 = p1.replace(/red/g, '');_x000D_
p1 = "-"+p1+"-";_x000D_
return p1;_x000D_
}_x000D_
_x000D_
console.log(test);
_x000D_
This could also happens if you put a @PreAuthorize
or @PostAuthorize
in a Bean in creation. I would recommend to move such annotations to methods of interest.
Just use the PHP magic constant __FILE__
to get the current filename.
But it seems you want the part without .php
. So...
basename(__FILE__, '.php');
A more generic file extension remover would look like this...
function chopExtension($filename) {
return pathinfo($filename, PATHINFO_FILENAME);
}
var_dump(chopExtension('bob.php')); // string(3) "bob"
var_dump(chopExtension('bob.i.have.dots.zip')); // string(15) "bob.i.have.dots"
Using standard string library functions is much quicker, as you'd expect.
function chopExtension($filename) {
return substr($filename, 0, strrpos($filename, '.'));
}
I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....
they are very handy but you have to learn their options etc.
A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)
AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.
a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.
Instance variable is the variable declared inside a class, but outside a method: something like:
class IronMan {
/** These are all instance variables **/
public String realName;
public String[] superPowers;
public int age;
/** Getters and setters here **/
}
Now this IronMan Class can be instantiated in another class to use these variables. Something like:
class Avengers {
public static void main(String[] a) {
IronMan ironman = new IronMan();
ironman.realName = "Tony Stark";
// or
ironman.setAge(30);
}
}
This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.
The difference between different date/time formats in ActiveRecord has little to do with Rails and everything to do with whatever database you're using.
Using MySQL as an example (if for no other reason because it's most popular), you have DATE
, DATETIME
, TIME
and TIMESTAMP
column data types; just as you have CHAR
, VARCHAR
, FLOAT
and INTEGER
.
So, you ask, what's the difference? Well, some of them are self-explanatory. DATE
only stores a date, TIME
only stores a time of day, while DATETIME
stores both.
The difference between DATETIME
and TIMESTAMP
is a bit more subtle: DATETIME
is formatted as YYYY-MM-DD HH:MM:SS
. Valid ranges go from the year 1000 to the year 9999 (and everything in between. While TIMESTAMP
looks similar when you fetch it from the database, it's really a just a front for a unix timestamp. Its valid range goes from 1970 to 2038. The difference here, aside from the various built-in functions within the database engine, is storage space. Because DATETIME
stores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. As TIMESTAMP
only stores the number of seconds since 1970-01-01, it uses 4 bytes.
You can read more about the differences between time formats in MySQL here.
In the end, it comes down to what you need your date/time column to do. Do you need to store dates and times before 1970 or after 2038? Use DATETIME
. Do you need to worry about database size and you're within that timerange? Use TIMESTAMP
. Do you only need to store a date? Use DATE
. Do you only need to store a time? Use TIME
.
Having said all of this, Rails actually makes some of these decisions for you. Both :timestamp
and :datetime
will default to DATETIME
, while :date
and :time
corresponds to DATE
and TIME
, respectively.
This means that within Rails, you only have to decide whether you need to store date, time or both.