You can Zoom In and Zoom Out the entire user interface from the View menu.
Right now i'm using version 1.21.1 and there in view menu you can get the Zoom in and Zoom out option which are the 2nd and 3rd last options. You can do it by using Ctrl + + and Ctrl + -.
You can reset the zoom at any time by selecting Reset Zoom option.
CMD.exe
Start a new CMD shell
Syntax
CMD [charset] [options] [My_Command]
Options
**/C Carries out My_Command and then
terminates**
From the help.
A working solution in pure CSS:
The trick is to suppose there's a dom element after the text-field.
/*_x000D_
* The trick is here:_x000D_
* this selector says "take the first dom element after_x000D_
* the input text (+) and set its before content to the_x000D_
* value (:before)._x000D_
*/_x000D_
input#myTextField + *:before {_x000D_
content: "";_x000D_
}
_x000D_
<input id="myTextField" class="mystyle" type="text" value="someValue" />_x000D_
<!--_x000D_
There's maybe something after a input-text_x000D_
Does'nt matter what it is (*), I use it._x000D_
-->_x000D_
<span></span>
_x000D_
(*) Limited solution, though:
But in most cases, we know our code so this solution seems efficient and 100% CSS and 0% jQuery.
As to me, you can first(find version.hpp the version variable is in it, if you know where it is(in ubuntu it usually in /usr/include/boost/version.hpp
by default install)):
locate `boost/version.hpp`
Second show it's version by:
grep BOOST_LIB_VERSION /usr/include/boost/version.hpp
or
grep BOOST_VERSION /usr/include/boost/version.hpp.
As to me, I have two version boost installed in my system. Output as below:
xy@xy:~$ locate boost/version.hpp |grep boost
/home/xy/boost_install/boost_1_61_0/boost/version.hpp
/home/xy/boost_install/lib/include/boost/version.hpp
/usr/include/boost/version.hpp
xy@xy:~$ grep BOOST_VERSION /usr/include/boost/version.hpp
#ifndef BOOST_VERSION_HPP
#define BOOST_VERSION_HPP
// BOOST_VERSION % 100 is the patch level
// BOOST_VERSION / 100 % 1000 is the minor version
// BOOST_VERSION / 100000 is the major version
#define BOOST_VERSION 105800
// BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
# or this way more readable
xy@xy:~$ grep BOOST_LIB_VERSION /usr/include/boost/version.hpp
// BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
#define BOOST_LIB_VERSION "1_58"
Show local installed version:
xy@xy:~$ grep BOOST_LIB_VERSION /home/xy/boost_install/lib/include/boost/version.hpp
// BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
#define BOOST_LIB_VERSION "1_61"
There is a handy bash utility - dos2unix
- which is a DOS/MAC to UNIX text file format converter, that if not already installed on your distro, should be able to be easily installed via a package manager. dos2unix man page
If you call it like this: $ python myfile.py var1 var2 var3
import sys
var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]
Similar to arrays you also have sys.argv[0]
which is always the current working directory.
your panel class don't have a constructor that accepts a string
try change
RLS_strid_panel p = new RLS_strid_panel(namn1);
to
RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);
Tagging this answer which helped me, might not answer the actual question
If you are using password instead of private key, please refer to this answer for tested working solution on Ubuntu 16.04.5 and 20.04.1
While
constructs are terminated not with an End While
but with a Wend
.
While counter < 20
counter = counter + 1
Wend
Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.
Also in the VBA help file:
Tip The
Do...Loop
statement provides a more structured and flexible way to perform looping.
.focus()
and then .blur()
something else arbitrary on your page. Since only one element can have the focus, it is transferred to that element and then removed.
I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:
http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html
there is no color parameter listed where you might be able to set the colors for your bar graph.
However, the Series.plot() docs state the following at the end of the parameter list:
kwds : keywords
Options to pass to matplotlib plotting method
What that means is that when you specify the kind argument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().
If you examine the docs for the matplotlib.pyplot.bar() method here:
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar
..it also accepts keyword arguments at the end of it's parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.
Putting it all together, if you specify the color keyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:
import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series(
[5, 4, 4, 1, 12],
index = ["AK", "AX", "GA", "SQ", "WN"]
)
#Set descriptions:
plt.title("Total Delay Incident Caused by Carrier")
plt.ylabel('Delay Incident')
plt.xlabel('Carrier')
#Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='red')
#Plot the data:
my_colors = 'rgbkymc' #red, green, blue, black, etc.
pd.Series.plot(
s,
kind='bar',
color=my_colors,
)
plt.show()
Note that if there are more bars than colors in your sequence, the colors will repeat.
In onCreate:
SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);
String mySetting = sharedPref.getString("mySetting", null);
In onDestroy or equivalent:
SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("mySetting", "Hello Android");
editor.commit();
I think a better formula was posted here: http://www.mathworks.com/matlabcentral/answers/16243-angle-between-two-vectors-in-3d
angle = atan2(norm(cross(a,b)), dot(a,b))
So this formula works in 2 or 3 dimensions. For 2 dimensions this formula simplifies to the one stated above.
a javascript only solution that's based on @HoldOffHunger and @bobince answers
<div id="doublescroll">
.
function DoubleScroll(element) {
var scrollbar= document.createElement('div');
scrollbar.appendChild(document.createElement('div'));
scrollbar.style.overflow= 'auto';
scrollbar.style.overflowY= 'hidden';
scrollbar.firstChild.style.width= element.scrollWidth+'px';
scrollbar.firstChild.style.paddingTop= '1px';
scrollbar.firstChild.appendChild(document.createTextNode('\xA0'));
var running = false;
scrollbar.onscroll= function() {
if(running) {
running = false;
return;
}
running = true;
element.scrollLeft= scrollbar.scrollLeft;
};
element.onscroll= function() {
if(running) {
running = false;
return;
}
running = true;
scrollbar.scrollLeft= element.scrollLeft;
};
element.parentNode.insertBefore(scrollbar, element);
}
DoubleScroll(document.getElementById('doublescroll'));
I've experienced a problem with length of None, which leads to Internal Server Error: TypeError: object of type 'NoneType' has no len()
My workaround is just displaying 0 if object is None and calculate length of other types, like list in my case:
{{'0' if linked_contacts == None else linked_contacts|length}}
Use this code
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp"
android:radius="0.1dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp" />
<solid android:color="#Efffff" />
<stroke
android:width="2dp"
android:color="#25aaff" />
</shape>
I ran into a similar issue, so maybe this answer will help someone.
The reason for the Error: no display specified
error is that Firefox is being launched, but there is no X server (GUI) running on the remote host. You can use X11 forwarding to run Firefox on the remote host, but display it on your local host. On Mac OS X, you will need to download XQuartz in order to use X11 forwarding. Without it, you won't have a $DISPLAY
variable set, so if you try and echo $DISPLAY
, it will be blank.
Initially I was just trying the method:
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
but after using this along with:
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
problem was solved. Sample Program-
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 30.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIView *sampleView = [[UIView alloc] init];
sampleView.frame = CGRectMake(SCREEN_WIDTH/2, 5, 60, 4);
sampleView.backgroundColor = [UIColor blackColor];
return sampleView;
}
and include UITableViewDelegate protocol.
@interface TestViewController : UIViewController <UITableViewDelegate>
You can do that just combining the script name ($0
) with realpath
and/or dirname
. It works for Bash and Shell.
#!/usr/bin/env bash
RELATIVE_PATH="${0}"
RELATIVE_DIR_PATH="$(dirname "${0}")"
FULL_DIR_PATH="$(realpath "${0}" | xargs dirname)"
FULL_PATH="$(realpath "${0}")"
echo "RELATIVE_PATH->${RELATIVE_PATH}<-"
echo "RELATIVE_DIR_PATH->${RELATIVE_DIR_PATH}<-"
echo "FULL_DIR_PATH->${FULL_DIR_PATH}<-"
echo "FULL_PATH->${FULL_PATH}<-"
The output will be something like this:
# RELATIVE_PATH->./bin/startup.sh<-
# RELATIVE_DIR_PATH->./bin<-
# FULL_DIR_PATH->/opt/my_app/bin<-
# FULL_PATH->/opt/my_app/bin/startup.sh<-
$0 is the name of the script itself
An example: LozanoMatheus/get_script_paths.sh
In my situation, the problem was due to running powershell as an admin, so it was looking for the aws credentials in the root of my admin user. There's probably a better way to resolve this, but what worked quickly for me was recreating my .aws folder in the root of my admin user.
the above solutions wont work on ipad-2
recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers this blog and now my map search is working smoothly on ipad-2 :)
Just simply right A
{{ date('h:i A', strtotime($varname->created_at))}}
Adding to Jacks solution. I need to Deserialize using the JsonProperty and Serialize while ignoring the JsonProperty (or vice versa). ReflectionHelper and Attribute Helper are just helper classes that get a list of properties or attributes for a property. I can include if anyone actually cares. Using the example below you can serialize the viewmodel and get "Amount" even though the JsonProperty is "RecurringPrice".
/// <summary>
/// Ignore the Json Property attribute. This is usefule when you want to serialize or deserialize differently and not
/// let the JsonProperty control everything.
/// </summary>
/// <typeparam name="T"></typeparam>
public class IgnoreJsonPropertyResolver<T> : DefaultContractResolver
{
private Dictionary<string, string> PropertyMappings { get; set; }
public IgnoreJsonPropertyResolver()
{
this.PropertyMappings = new Dictionary<string, string>();
var properties = ReflectionHelper<T>.GetGetProperties(false)();
foreach (var propertyInfo in properties)
{
var jsonProperty = AttributeHelper.GetAttribute<JsonPropertyAttribute>(propertyInfo);
if (jsonProperty != null)
{
PropertyMappings.Add(jsonProperty.PropertyName, propertyInfo.Name);
}
}
}
protected override string ResolvePropertyName(string propertyName)
{
string resolvedName = null;
var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}
Usage:
var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new IgnoreJsonPropertyResolver<PlanViewModel>();
var model = new PlanViewModel() {Amount = 100};
var strModel = JsonConvert.SerializeObject(model,settings);
Model:
public class PlanViewModel
{
/// <summary>
/// The customer is charged an amount over an interval for the subscription.
/// </summary>
[JsonProperty(PropertyName = "RecurringPrice")]
public double Amount { get; set; }
/// <summary>
/// Indicates the number of intervals between each billing. If interval=2, the customer would be billed every two
/// months or years depending on the value for interval_unit.
/// </summary>
public int Interval { get; set; } = 1;
/// <summary>
/// Number of free trial days that can be granted when a customer is subscribed to this plan.
/// </summary>
public int TrialPeriod { get; set; } = 30;
/// <summary>
/// This indicates a one-time fee charged upfront while creating a subscription for this plan.
/// </summary>
[JsonProperty(PropertyName = "SetupFee")]
public double SetupAmount { get; set; } = 0;
/// <summary>
/// String representing the type id, usually a lookup value, for the record.
/// </summary>
[JsonProperty(PropertyName = "TypeId")]
public string Type { get; set; }
/// <summary>
/// Billing Frequency
/// </summary>
[JsonProperty(PropertyName = "BillingFrequency")]
public string Period { get; set; }
/// <summary>
/// String representing the type id, usually a lookup value, for the record.
/// </summary>
[JsonProperty(PropertyName = "PlanUseType")]
public string Purpose { get; set; }
}
Another correct way to get selected value would be using this selector:
$("option[value="0"]:selected")
Best for you!
Wrap your OutputStream with a PrintWriter and use the print methods on that class. They take in a String and do the work for you.
JDK8 - Java Time Module way:
LocalDateTime todayMidnight = LocalDate.now().atStartOfDay();
Also work:
LocalDateTime todayMidnight = LocalDateTime.now().with(LocalTime.MIDNIGHT);
Here is a extension method, this allows coding like the SQL IN command.
public static bool In<T>(this T o, params T[] values)
{
if (values == null) return false;
return values.Contains(o);
}
public static bool In<T>(this T o, IEnumerable<T> values)
{
if (values == null) return false;
return values.Contains(o);
}
This allows stuff like that:
List<int> ints = new List<int>( new[] {1,5,7});
int i = 5;
bool isIn = i.In(ints);
Or:
int i = 5;
bool isIn = i.In(1,2,3,4,5);
Try something like this:
foreach (ListItem listItem in YrChkBox.Items)
{
if (listItem.Selected)
{
//do some work
}
else
{
//do something else
}
}
thanks for all of posts.... I have done it with using Linq Query, to view this please visit the following link
http://codenicely.blogspot.com/2012/02/converting-your-datatable-into-list.html
As you are looking for 1 record, (LIMIT 1) then this will work.
(SELECT field1 FROM table WHERE id = 123)
UNION
(SELECT 'default_value_if_no_record')
LIMIT 1;
Can be a handy way to display default values, or indicate no results found. I use it for reports.
See also http://blogs.uoregon.edu/developments/2011/03/31/add-a-header-row-to-mysql-query-results/ for a way to use this to create headers in reports.
When I ran into this problem, trying to run an async method synchronicity from either a setter or a constructor got me into a deadlock on the UI thread, and using an event handler required too many changes in the general design.
The solution was, as often is, to just write explicitly what I wanted to happen implicitly, which was to have another thread handle the operation and to get the main thread to wait for it to finish:
string someValue=null;
var t = new Thread(() =>someValue = SomeAsyncMethod().Result);
t.Start();
t.Join();
You could argue that I abuse the framework, but it works.
<div ng-hide="myvar == null"></div>
or
<div ng-show="myvar != null"></div>
You were looking for help on installations with pip. You can find it with the following command:
pip install --help
Running pip install -e /path/to/package
installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.
Just need to set the value property in a convenient place (such as InitializeComponent()
):
dateTimePicker1.Value = DateTime.Today.AddDays(-1);
You can put the control you want to center inside a Panel and set the left and right padding values to something larger than the default. As long as they are equal and your control is anchored to the sides of the Panel, then it will appear centered in that Panel. Then you can anchor the container Panel to its parent as needed.
keystore simply stores private keys, wheras truststore stores public keys. You will want to generate a java certificate for SSL communication. You can use a keygen command in windows, this will probably be the most easy solution.
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
onChange doesn't fire until you lose focus later. If you want to be really strict with instantaneous changes of all sorts, use:
<input
type = "text"
onchange = "myHandler();"
onkeypress = "this.onchange();"
onpaste = "this.onchange();"
oninput = "this.onchange();"
/>
Do you mean like this?
var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);
To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll()
to accomplish this:
HTML
<div class="abc"></div>
<div class="abc"></div>
JS
var abcElements = document.querySelectorAll('.abc');
// Set their ids
for (var i = 0; i < abcElements.length; i++)
abcElements[i].id = 'abc-' + i;
This will assign the ID 'abc-<index number>'
to each element. So it would come out like this:
<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>
To create an element and assign an id
we can use document.createElement()
and then appendChild()
.
var div = document.createElement('div');
div.id = 'hello1';
var body = document.querySelector('body');
body.appendChild(div);
Update
You can set the id
on your element like this if your script is in your HTML file.
<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">
<script type="text/javascript">
var s = document.getElementsByClassName('assign-me')[0];
s.id = btoa({{str(produit["avt"]["fto"])}});
</script>
Your requirements still aren't 100% clear though.
Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.
I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.
You can use the INSERT ... SELECT
statement to get the MAX()+1
value and insert at the same time:
INSERT INTO
customers( customer_id, firstname, surname )
SELECT MAX( customer_id ) + 1, 'jim', 'sock' FROM customers;
Note: You need to drop the VALUES
from your INSERT
and make sure the SELECT
selected fields match the INSERT
declared fields.
Just putting .encode('utf-8')
at the end of object will do the job in recent versions of Python.
Note that this algorithm has an n factorial
time complexity, where n
is the length of the input list
Print the results on the run:
global result
result = []
def permutation(li):
if li == [] or li == None:
return
if len(li) == 1:
result.append(li[0])
print result
result.pop()
return
for i in range(0,len(li)):
result.append(li[i])
permutation(li[:i] + li[i+1:])
result.pop()
Example:
permutation([1,2,3])
Output:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
strScriptFullname = WScript.ScriptFullName
strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\"))
A lot of the tutorials are outdated, and even the current code doesn't account for when device registration_ids are updated or devices unregister. If those items go unchecked, it will eventually cause issues that prevent messages from being received. http://forum.loungekatt.com/viewtopic.php?t=63#p181
Wrap the value passed in different classes that might be helpful doing the trick, check below for more real example:
class Ref<T>{
T s;
public void set(T value){
s = value;
}
public T get(){
return s;
}
public Ref(T value) {
s = value;
}
}
class Out<T>{
T s;
public void set(T value){
s = value;
}
public T get(){
return s;
}
public Out() {
}
}
public static void doAndChangeRefs (Ref<String> str, Ref<Integer> i, Out<String> str2){
//refs passed .. set value
str.set("def");
i.set(10);
//out param passed as null .. instantiate and set
str2 = new Out<String>();
str2.set("hello world");
}
public static void main(String args[]) {
Ref<Integer> iRef = new Ref<Integer>(11);
Out<String> strOut = null;
doAndChangeRefs(new Ref<String>("test"), iRef, strOut);
System.out.println(iRef.get());
System.out.println(strOut.get());
}
As for front-end developer many time we are dealing with the forms in which we have to handle the dropdowns and we have to use the value of selected dropdown to perform some action or the send the value on the Server, it's very simple you have to write the simple dropdown in HTML just put the one onChange method for the selection in the dropdown whenever user change the value of dropdown set that value to state so you can easily access it in AvFeaturedPlayList 1 remember you will always get the result as option value and not the dropdown text which is displayed on the screen
import React, { Component } from "react";
import { Server } from "net";
class InlineStyle extends Component {
constructor(props) {
super(props);
this.state = {
selectValue: ""
};
this.handleDropdownChange = this.handleDropdownChange.bind(this);
}
handleDropdownChange(e) {
this.setState({ selectValue: e.target.value });
}
render() {
return (
<div>
<div>
<div>
<select id="dropdown" onChange={this.handleDropdownChange}>
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div>Selected value is : {this.state.selectValue}</div>
</div>
</div>
);
}
}
export default InlineStyle;
On my iSeries I have to run this command from iNavigator:
select *
from QSYS2.SYSTABLES
where TABLE_SCHEMA
like 'SCHEMA_NAME'
and TYPE = 'T';
You can use destructuring to only focus on the part of your interest.
So you can do:
let str = "My cow always gives milk";
let [, result] = str.match(/\bcow\s+(.*?)\s+milk\b/) || [];
console.log(result);
_x000D_
In this way you ignore the first part (the complete match) and only get the capture group's match. The addition of || []
may be interesting if you are not sure there will be a match at all. In that case match
would return null
which cannot be destructured, and so we return []
instead in that case, and then result
will be null
.
The additional \b
ensures the surrounding words "cow" and "milk" are really separate words (e.g. not "milky"). Also \s+
is needed to avoid that the match includes some outer spacing.
Quoting http://php.net/manual/en/intro.mssql.php:
The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
Once you downloaded that, follow the instructions at this page:
In a nutshell:
Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:extension=php_sqlsrv_53_nts_vc9.dll
Restart the Web server.
See Also (copied from that page)
The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:
The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.
The drivers can also be used with PDO.
find -regex ".*\.\(jpg\|gif\|png\|jpeg\)"
If you work with Visual Studio then it is pretty easy to get persistable settings. Right click on the project in Solution Explorer and choose Properties. Select the Settings tab and click on the hyperlink if settings doesn't exist.
Use the Settings tab to create application settings. Visual Studio creates the files Settings.settings
and Settings.Designer.settings
that contain the singleton class Settings
inherited from ApplicationSettingsBase. You can access this class from your code to read/write application settings:
Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file
This technique is applicable both for console, Windows Forms, and other project types.
Note that you need to set the scope property of your settings. If you select Application scope then Settings.Default.<your property> will be read-only.
Reference: How To: Write User Settings at Run Time with C# - Microsoft Docs
See the documentation for the print function: print()
The content of end
is printed after the thing you want to print. By default it contains a newline ("\n"
) but it can be changed to something else, like an empty string.
One possible reason is that you have multiple python executables in your environment, for example 2.6.x, 2.7.x or virtaulenv. You might install the package into one of them and run your script with another.
Type python in the prompt, and press the tab key to see what versions of Python in your environment.
<style type="text/css">
.topcorner{
position:absolute;
top:10;
right:15;
}
</style>
You ca also use this in CSS external file.
You can do something like this instead.
return new DateTime(2010, Month, 1).ToString("MMM");
You can get all the http/https, host, port, path as well as query by using Uri object in .NET. just the difficult task is to break the host into sub domain, domain name and TLD.
There is no standard to do so and can't be simply use string parsing or RegEx to produce the correct result. At first, I am using RegEx function but not all URL can be parse the subdomain correctly. The practice way is to use a list of TLDs. After a TLD for a URL is defined the left part is domain and the remaining is sub domain.
However the list need to maintain it since new TLDs is possible. The current moment I know is publicsuffix.org maintain the latest list and you can use domainname-parser tools from google code to parse the public suffix list and get the sub domain, domain and TLD easily by using DomainName object: domainName.SubDomain, domainName.Domain and domainName.TLD.
This answers also helpfull: Get the subdomain from a URL
CaLLMeLaNN
Wikipedia is a decent source for this info.
To learn about static library files like .a read Static libarary
To learn about shared library files like .so read Library_(computing)#Shared_libraries On this page, there is also useful info in the File naming section.
renderItem(item)
{
const width = '80%';
var items = [];
for(let i = 0; i < item.count; i++){
items.push( <View style={{ padding: 10, borderBottomColor: "#f2f2f2", borderBottomWidth: 10, flexDirection: 'row' }}>
<View style={{ width }}>
<Text style={styles.name}>{item.title}</Text>
<Text style={{ color: '#818181', paddingVertical: 10 }}>{item.taskDataElements[0].description + " "}</Text>
<Text style={styles.begin}>BEGIN</Text>
</View>
<Text style={{ backgroundColor: '#fcefec', padding: 10, color: 'red', height: 40 }}>{this.msToTime(item.minTatTimestamp) <= 0 ? "NOW" : this.msToTime(item.minTatTimestamp) + "hrs"}</Text>
</View> )
}
return items;
}
render() {
return (this.renderItem(this.props.item))
}
Here is the sample code.
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
writer.Write("Hello its my sample file");
writer.Flush();
writer.Dispose();
ms.Position = 0;
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
attach.ContentDisposition.FileName = "myFile.txt";
// I guess you know how to send email with an attachment
// after sending email
ms.Close();
Edit 1
You can specify other file types by System.Net.Mime.MimeTypeNames like System.Net.Mime.MediaTypeNames.Application.Pdf
Based on Mime Type you need to specify correct extension in FileName for instance "myFile.pdf"
You can't use "disable" to disable a click event. I don't know how or if it worked in IE6-9, but it didn't work on Chrome, and it shouldn't work on IE10 like that.
You can disable the onclick event, too, by attaching an event that cancels:
;(function () {
function cancel () { return false; };
document.getElementById("test").disabled = true;
var nodes = document.getElementById("test").getElementsByTagName('*');
console.log(nodes);
for (var i = 0; i < nodes.length; i++) {
nodes[i].setAttribute('disabled', true);
nodes[i].onclick = cancel;
}
}());
Furthermore, setting "disabled" on a node directly doesn't necessarily add the attribute- using setAttribute does.
To get a faster result, the function that obtains the size could be found in resultSize
:
Size original = new Size(640, 480);
int maxSize = 100;
float percent = (new List<float> { (float)maxSize / (float)original.Width , (float)maxSize / (float)original.Height }).Min();
Size resultSize = new Size((int)Math.Floor(original.Width * percent), (int)Math.Floor(original.Height * percent));
Uses Linq
to minimize variable and recalculations, as well as unnecesary if/else
statements
This will remove all whitespace and newlines from both the beginning and end of a string:
>>> s = " \n\t \n some \n text \n "
>>> re.sub("^\s+|\s+$", "", s)
>>> "some \n text"
I had the same error recently, and all the solutions I've found did not work.
After some digging, I found that setting app.use(express.bodyParser({limit: '50mb'}));
did set the limit correctly.
When adding a console.log('Limit file size: '+limit);
in node_modules/express/node_modules/connect/lib/middleware/json.js:46
and restarting node, I get this output in the console:
Limit file size: 1048576
connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0
Limit file size: 52428800
Express server listening on port 3002
We can see that at first, when loading the connect
module, the limit is set to 1mb (1048576 bytes). Then when I set the limit, the console.log
is called again and this time the limit is 52428800 (50mb). However, I still get a 413 Request entity too large
.
Then I added console.log('Limit file size: '+limit);
in node_modules/express/node_modules/connect/node_modules/raw-body/index.js:10
and saw another line in the console when calling the route with a big request (before the error output) :
Limit file size: 1048576
This means that somehow, somewhere, connect
resets the limit parameter and ignores what we specified. I tried specifying the bodyParser
parameters in the route definition individually, but no luck either.
While I did not find any proper way to set it permanently, you can "patch" it in the module directly. If you are using Express 3.4.4, add this at line 46 of node_modules/express/node_modules/connect/lib/middleware/json.js
:
limit = 52428800; // for 50mb, this corresponds to the size in bytes
The line number might differ if you don't run the same version of Express. Please note that this is bad practice and it will be overwritten if you update your module.
So this temporary solution works for now, but as soon as a solution is found (or the module fixed, in case it's a module problem) you should update your code accordingly.
I have opened an issue on their GitHub about this problem.
[edit - found the solution]
After some research and testing, I found that when debugging, I added app.use(express.bodyParser({limit: '50mb'}));
, but after app.use(express.json());
. Express would then set the global limit to 1mb because the first parser he encountered when running the script was express.json()
. Moving bodyParser
above it did the trick.
That said, the bodyParser()
method will be deprecated in Connect 3.0 and should not be used. Instead, you should declare your parsers explicitly, like so :
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));
In case you need multipart (for file uploads) see this post.
[second edit]
Note that in Express 4, instead of express.json()
and express.urlencoded()
, you must require the body-parser module and use its json()
and urlencoded()
methods, like so:
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
If the extended
option is not explicitly defined for bodyParser.urlencoded()
, it will throw a warning (body-parser deprecated undefined extended: provide extended option
). This is because this option will be required in the next version and will not be optional anymore. For more info on the extended
option, you can refer to the readme of body-parser
.
[third edit]
It seems that in Express v4.16.0 onwards, we can go back to the initial way of doing this (thanks to @GBMan for the tip):
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));
I assume this is either difficult or impossible for the compiler team to implement for some reason.
No, it is not at all difficult or impossible to implement -- the fact that you implemented it yourself is a testament to that fact. Rather, it is an incredibly bad idea and so we don't allow it, so as to protect you from making this mistake.
call to Monitor.Exit within ExitDisposable.Dispose seems to block indefinitely (most of the time) causing deadlocks as other threads attempt to acquire the lock. I suspect the unreliability of my work around and the reason await statements are not allowed in lock statement are somehow related.
Correct, you have discovered why we made it illegal. Awaiting inside a lock is a recipe for producing deadlocks.
I'm sure you can see why: arbitrary code runs between the time the await returns control to the caller and the method resumes. That arbitrary code could be taking out locks that produce lock ordering inversions, and therefore deadlocks.
Worse, the code could resume on another thread (in advanced scenarios; normally you pick up again on the thread that did the await, but not necessarily) in which case the unlock would be unlocking a lock on a different thread than the thread that took out the lock. Is that a good idea? No.
I note that it is also a "worst practice" to do a yield return
inside a lock
, for the same reason. It is legal to do so, but I wish we had made it illegal. We're not going to make the same mistake for "await".
I surprise no one had mentioned this possible easy approach in visual studio code.
Install VS Code and Apache maven ( just as mentioned by @Steve Chambers)
After installing this extension vscode:extension/vscjava.vscode-java-pack
In the java overview page , there is a an option which reads 'Create Maven Project' which further takes to a simple wizard to generate maven project.
Its pretty quick which is intutitive enough, even newbies can very well start with a Maven project.
Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.
$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'
& $app $arg1 $arg2 $arg3
Given that your strings are all fixed-length (presumably at compile-time?), you can do the following:
char (*orderedIds)[ID_LEN+1]
= malloc(variableNumberOfElements * sizeof(*orderedIds));
// Clear-up
free(orderedIds);
A more cumbersome, but more general, solution, is to assign an array of pointers, and psuedo-initialising them to point at elements of a raw backing array:
char *raw = malloc(variableNumberOfElements * (ID_LEN + 1));
char **orderedIds = malloc(sizeof(*orderedIds) * variableNumberOfElements);
// Set each pointer to the start of its corresponding section of the raw buffer.
for (i = 0; i < variableNumberOfElements; i++)
{
orderedIds[i] = &raw[i * (ID_LEN+1)];
}
...
// Clear-up pointer array
free(orderedIds);
// Clear-up raw array
free(raw);
VB6:
Listview1.selecteditem
VB10:
Listview1.FocusedItem.Text
I was looking to find the answer to this question too, but the accepted answer was breaking for me. Apparently using window.innerWidth isn't portable. It does work in some browsers, but I noticed Firefox didn't like it.
Gregg Tavares posted a great resource here that addresses this issue directly: http://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html (See anti-pattern #'s 3 and 4).
Using canvas.clientWidth instead of window.innerWidth seems to work nicely.
Here's Gregg's suggested render loop:
function resize() {
var width = gl.canvas.clientWidth;
var height = gl.canvas.clientHeight;
if (gl.canvas.width != width ||
gl.canvas.height != height) {
gl.canvas.width = width;
gl.canvas.height = height;
return true;
}
return false;
}
var needToRender = true; // draw at least once
function checkRender() {
if (resize() || needToRender) {
needToRender = false;
drawStuff();
}
requestAnimationFrame(checkRender);
}
checkRender();
//but i cannot really get the id and assign it to an array that is not with in the scope?(or can I)
Yes, you can!
var IDs = [];
$("#mydiv").find("span").each(function(){ IDs.push(this.id); });
This is the beauty of closures.
Note that while you were on the right track, sighohwell and cletus both point out more reliable and concise ways of accomplishing this, taking advantage of attribute filters (to limit matched elements to those with IDs) and jQuery's built-in map()
function:
var IDs = $("#mydiv span[id]") // find spans with ID attribute
.map(function() { return this.id; }) // convert to set of IDs
.get(); // convert to instance of Array (optional)
The one below performs faster than the others above. Take a look
''.join([x if x in string.printable else '' for x in Str])
I've updated polkovnikov.ph solution to React 16 / ES6 with enhancements like touch handling and snapping to a grid which is what I need for a game. Snapping to a grid alleviates the performance issues.
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
class Draggable extends React.Component {
constructor(props) {
super(props);
this.state = {
relX: 0,
relY: 0,
x: props.x,
y: props.y
};
this.gridX = props.gridX || 1;
this.gridY = props.gridY || 1;
this.onMouseDown = this.onMouseDown.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
this.onMouseUp = this.onMouseUp.bind(this);
this.onTouchStart = this.onTouchStart.bind(this);
this.onTouchMove = this.onTouchMove.bind(this);
this.onTouchEnd = this.onTouchEnd.bind(this);
}
static propTypes = {
onMove: PropTypes.func,
onStop: PropTypes.func,
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
gridX: PropTypes.number,
gridY: PropTypes.number
};
onStart(e) {
const ref = ReactDOM.findDOMNode(this.handle);
const body = document.body;
const box = ref.getBoundingClientRect();
this.setState({
relX: e.pageX - (box.left + body.scrollLeft - body.clientLeft),
relY: e.pageY - (box.top + body.scrollTop - body.clientTop)
});
}
onMove(e) {
const x = Math.trunc((e.pageX - this.state.relX) / this.gridX) * this.gridX;
const y = Math.trunc((e.pageY - this.state.relY) / this.gridY) * this.gridY;
if (x !== this.state.x || y !== this.state.y) {
this.setState({
x,
y
});
this.props.onMove && this.props.onMove(this.state.x, this.state.y);
}
}
onMouseDown(e) {
if (e.button !== 0) return;
this.onStart(e);
document.addEventListener('mousemove', this.onMouseMove);
document.addEventListener('mouseup', this.onMouseUp);
e.preventDefault();
}
onMouseUp(e) {
document.removeEventListener('mousemove', this.onMouseMove);
document.removeEventListener('mouseup', this.onMouseUp);
this.props.onStop && this.props.onStop(this.state.x, this.state.y);
e.preventDefault();
}
onMouseMove(e) {
this.onMove(e);
e.preventDefault();
}
onTouchStart(e) {
this.onStart(e.touches[0]);
document.addEventListener('touchmove', this.onTouchMove, {passive: false});
document.addEventListener('touchend', this.onTouchEnd, {passive: false});
e.preventDefault();
}
onTouchMove(e) {
this.onMove(e.touches[0]);
e.preventDefault();
}
onTouchEnd(e) {
document.removeEventListener('touchmove', this.onTouchMove);
document.removeEventListener('touchend', this.onTouchEnd);
this.props.onStop && this.props.onStop(this.state.x, this.state.y);
e.preventDefault();
}
render() {
return <div
onMouseDown={this.onMouseDown}
onTouchStart={this.onTouchStart}
style={{
position: 'absolute',
left: this.state.x,
top: this.state.y,
touchAction: 'none'
}}
ref={(div) => { this.handle = div; }}
>
{this.props.children}
</div>;
}
}
export default Draggable;
You need to drop the table and then recreate it and then load it again
git add .
git commit -m "initial commit"
git config --local credential.helper ""
git push https://github.com/youraccount/repo.git --all
After this push command, a username password prompt will be opened.
I got here with an MS Access problem.
Backticks are good for MySQL, but they create weird errors, like "Invalid Query Name: Query1" in MS Access, for MS Access only, use square brackets:
It should look like this
SELECT Customer.[Customer ID], Customer.[Full Name] ...
Just because everyone is using strtotime() and date() functions, I will show DateTime example:
$dt = DateTime::createFromFormat('!m', $result['month']);
echo $dt->format('F');
Many integrated products (especially by Apple) such as iPods, iPads are a good example of tight coupling: once the battery dies you might as well buy a new device because the battery is soldered fixed and won't come loose, thus making replacing very expensive. A loosely coupled player would allow effortlessly changing the battery.
The same goes for software development: it is generally (much) better to have loosely coupled code to facilitate extension and replacement (and to make individual parts easier to understand). But, very rarely, under special circumstances tight coupling can be advantageous because the tight integration of several modules allows for better optimisation.
0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.
There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.
I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException
and Application.ThreadException
, as appropriate.
I know that in SQL 2012 (may work in other versions) you can do the following:
That will give you a list of the top 1000 tables and then you can order it by data size etc.
Here is a simple solution that strips HTML tags and decodes HTML entities based on the amazingly fast lxml
library:
from lxml import html
def strip_html(s):
return str(html.fromstring(s).text_content())
strip_html('Ein <a href="">schöner</a> Text.') # Output: Ein schöner Text.
This Python snippet will git mv --force
all files in a directory to be lowercase. For example, foo/Bar.js will become foo/bar.js via git mv foo/Bar.js foo/bar.js --force
.
Modify it to your liking. I just figured I'd share :)
import os
import re
searchDir = 'c:/someRepo'
exclude = ['.git', 'node_modules','bin']
os.chdir(searchDir)
for root, dirs, files in os.walk(searchDir):
dirs[:] = [d for d in dirs if d not in exclude]
for f in files:
if re.match(r'[A-Z]', f):
fullPath = os.path.join(root, f)
fullPathLower = os.path.join(root, f[0].lower() + f[1:])
command = 'git mv --force ' + fullPath + ' ' + fullPathLower
print(command)
os.system(command)
You can use method shown here and replace isNull
with isnan
:
from pyspark.sql.functions import isnan, when, count, col
df.select([count(when(isnan(c), c)).alias(c) for c in df.columns]).show()
+-------+----------+---+
|session|timestamp1|id2|
+-------+----------+---+
| 0| 0| 3|
+-------+----------+---+
or
df.select([count(when(isnan(c) | col(c).isNull(), c)).alias(c) for c in df.columns]).show()
+-------+----------+---+
|session|timestamp1|id2|
+-------+----------+---+
| 0| 0| 5|
+-------+----------+---+
The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.
I think ADTC's solution is better, but mine's also works.
Here is the other solution I found
select p.name
from person p
where instr(p.name,chr(8211)) > 0; --contains the character chr(8211)
--at least 1 time
Thank you.
1- Select LinearLayout findViewById
LinearLayout llayout =(LinearLayout) findViewById(R.id.llayoutId);
2- Set color from R.color.colorId
llayout.setBackgroundColor(getResources().getColor(R.color.colorId));
final LayerDrawable layers = (LayerDrawable) progressBar.getProgressDrawable();
layers.getDrawable(2).setColorFilter(color,PorterDuff.Mode.SRC_IN);
Or better
window.location.assign("relative or absolute address");
that tends to work best across all browsers and mobile
use mod_rewrite to redirect the call to file.html to image.png without the url changing for the user
Have you tried just renaming the image.png file to file.html? I think most browser take mime header over file extension :)
found this site supply a CDN for
nosniff
http headermime type
by ext nameand this site:
NOTE: RawGit has reached the end of its useful life
Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so
<project>
...
<dependencies>
<dependency>
<groupId>yourgroup</groupId>
<artifactId>myejbproject</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>path/to/myejbproject.jar</systemPath>
</dependency>
</dependencies>
...
</project>
That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.
If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:
parent
|- pom.xml
|- MyEJBProject
| `- pom.xml
`- MyWarProject
`- pom.xml
The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)
<project>
...
<artifactId>myparentproject</artifactId>
<groupId>...</groupId>
<version>...</version>
<packaging>pom</packaging>
...
<modules>
<module>MyEJBModule</module>
<module>MyWarModule</module>
</modules>
...
</project>
That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects
Finally, if your projects are not in related directories, you might try to give them as relative modules:
filesystem
|- mywarproject
| `pom.xml
|- myejbproject
| `pom.xml
`- parent
`pom.xml
now you could just do this (worked in maven 2, just tried it):
<!--parent-->
<project>
<modules>
<module>../mywarproject</module>
<module>../myejbproject</module>
</modules>
</project>
Use Apache Commons IO api. Its simple
Use API as
FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");
Maven Dependency
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
I had the same issue too and this worked for me try:
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res) => {
let resSTR = JSON.stringify(res);
let resJSON = JSON.parse(resStr);
console.log(resJSON._body);
})
With docker-compose try docker-compose up -d --build --force-recreate
Online Viewstate Viewer made by Lachlan Keown:
http://lachlankeown.blogspot.com/2008/05/online-viewstate-viewer-decoder.html
It's not clear to me at all what the OP is actually after, given the follow-up comments. It's possible they are actually looking for a way to write the data to file.
But let's assume that we're really after a way to cbind
multiple data frames of differing lengths.
cbind
will eventually call data.frame
, whose help files says:
Objects passed to data.frame should have the same number of rows, but atomic vectors, factors and character vectors protected by I will be recycled a whole number of times if necessary (including as from R 2.9.0, elements of list arguments).
so in the OP's actual example, there shouldn't be an error, as R ought to recycle the shorter vectors to be of length 50. Indeed, when I run the following:
set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
cbind(dat1,dat2)
I get no errors and the shorter data frame is recycled as expected. However, when I run this:
set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(9), e = runif(9))
cbind(dat1,dat2)
I get the following error:
Error in data.frame(..., check.names = FALSE) :
arguments imply differing number of rows: 50, 9
But the wonderful thing about R is that you can make it do almost anything you want, even if you shouldn't. For example, here's a simple function that will cbind
data frames of uneven length and automatically pad the shorter ones with NA
s:
cbindPad <- function(...){
args <- list(...)
n <- sapply(args,nrow)
mx <- max(n)
pad <- function(x, mx){
if (nrow(x) < mx){
nms <- colnames(x)
padTemp <- matrix(NA, mx - nrow(x), ncol(x))
colnames(padTemp) <- nms
if (ncol(x)==0) {
return(padTemp)
} else {
return(rbind(x,padTemp))
}
}
else{
return(x)
}
}
rs <- lapply(args,pad,mx)
return(do.call(cbind,rs))
}
which can be used like this:
set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
dat3 <- data.frame(d = runif(9), e = runif(9))
cbindPad(dat1,dat2,dat3)
I make no guarantees that this function works in all cases; it is meant as an example only.
EDIT
If the primary goal is to create a csv or text file, all you need to do it alter the function to pad using ""
rather than NA
and then do something like this:
dat <- cbindPad(dat1,dat2,dat3)
rs <- as.data.frame(apply(dat,1,function(x){paste(as.character(x),collapse=",")}))
and then use write.table
on rs
.
This isn't exactly the issue I had, but if anyone is looking to convert a BindingList of any type to List of the same type, then this is how it is done:
var list = bindingList.ToDynamicList();
Also, if you're assigning BindingLists of dynamic types to a DataGridView.DataSource, then make sure you declare it first as IBindingList so the above works.
I also faced similar problem while working on Affable Bean e-commerce site development. I received an error:
Module has not been deployed.
I checked the sun-resources.xml
file and found the following statements which resulted in the error.
<resources>
<jdbc-resource enabled="true"
jndi-name="jdbc/affablebean"
object-type="user"
pool-name="AffableBeanPool">
</jdbc-resource>
<jdbc-connection-pool allow-non-component-callers="false"
associate-with-thread="false"
connection-creation-retry-attempts="0"
connection-creation-retry-interval-in-seconds="10"
connection-leak-reclaim="false"
connection-leak-timeout-in-seconds="0"
connection-validation-method="auto-commit"
datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
fail-all-connections="false"
idle-timeout-in-seconds="300"
is-connection-validation-required="false"
is-isolation-level-guaranteed="true"
lazy-connection-association="false"
lazy-connection-enlistment="false"
match-connections="false"
max-connection-usage-count="0"
max-pool-size="32"
max-wait-time-in-millis="60000"
name="AffableBeanPool"
non-transactional-connections="false"
pool-resize-quantity="2"
res-type="javax.sql.ConnectionPoolDataSource"
statement-timeout-in-seconds="-1"
steady-pool-size="8"
validate-atmost-once-period-in-seconds="0"
wrap-jdbc-objects="false">
<description>Connects to the affablebean database</description>
<property name="URL" value="jdbc:mysql://localhost:3306/affablebean"/>
<property name="User" value="root"/>
<property name="Password" value="nbuser"/>
</jdbc-connection-pool>
</resources>
Then I changed the statements to the following which is simple and works. I was able to run the file successfully.
<resources>
<jdbc-resource enabled="true" jndi-name="jdbc/affablebean" object-type="user" pool-name="AffablebeanPool">
<description/>
</jdbc-resource>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="AffablebeanPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.ConnectionPoolDataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="URL" value="jdbc:mysql://localhost:3306/AffableBean"/>
<property name="User" value="root"/>
<property name="Password" value="nbuser"/>
</jdbc-connection-pool>
</resources>
Actually correct one to one implementation is:
int n;
int[] ia = s1.Split(';').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();
You can use NGBindHTML or NGbindHtmlUnsafe this will not escape the html
content of your model.
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text">
{{ opt.text }}
</li>
</ul>
<p>{{opt}}</p>
</div>
This works, anyway you should be very careful when using unsanitized
html
content, you should really trust the source of the content.
I am using ubuntu 14.04. I have genymotion installed on virtualbox. Every time I start genymotion I had no problem, but suddenly one time it said unable to load virtualbox engine and it didn't open. I went through the log file and found out it could not create a new host only network because it has already created all possible host only networks. And the problem is that it cannot allocate memory for a new network.
Fix: go to your virtual box File --> Preferences --> Network
Click the host-only tab and just delete some of the host-only networks so that you will get some memory freed and next time, a new network can be created easily.
Deletion fixed my problem.
select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1
The answers on this question are not only wrong, but dangerous. CTRL+ALT+SHIFT+B will not indent HTML but XML. Consider the following HTML code:
<span class="myClass"></span>
The function 'Notepad++ -> Plugins -> XmlTools -> Pretty print (Xml only with line breaks)' (CTRL+ALT+SHIFT+B) will transform this to:
<span class="myClass"/>
which will not be displayed correctly anymore by your browser! I strongly advice against using this function to indent HTML.
Instead use the plugin Tidy2. This will indent the HTML correctly without bad side-effects (but it will also create <html>, <head>, <body>, ...
elements around your code, if these are not there).
EXPLAIN PLAN FOR
In SQL Developer, you don't have to use EXPLAIN PLAN FOR
statement. Press F10
or click the Explain Plan icon.
It will be then displayed in the Explain Plan window.
If you are using SQL*Plus then use DBMS_XPLAN.
For example,
SQL> EXPLAIN PLAN FOR
2 SELECT * FROM DUAL;
Explained.
SQL> SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------
Plan hash value: 272002086
--------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 2 | 2 (0)| 00:00:01 |
| 1 | TABLE ACCESS FULL| DUAL | 1 | 2 | 2 (0)| 00:00:01 |
--------------------------------------------------------------------------
8 rows selected.
SQL>
@zdan. Good answer. I'd improve it like this...
I think that the closest you can come to a true return value in PowerShell is to use a local variable to pass the value and never to use return
as it may be 'corrupted' by any manner of output situations
function CheckRestart([REF]$retval)
{
# Some logic
$retval.Value = $true
}
[bool]$restart = $false
CheckRestart( [REF]$restart)
if ( $restart )
{
Restart-Computer -Force
}
The $restart
variable is used either side of the call to the function CheckRestart
making clear the scope of the variable. The return value can by convention be either the first or last parameter declared. I prefer last.
SOLVED: I got this error when I installed an update to the Git windows installer. What happened is that I did not install it with administrator rights, so Git was installed in "C:\Users\my_name\AppData\Local\Programs" instead of "C:\program Files". re-installing Git as administrator allowed to put it in C:\program Files and everything went fine again !
The "normal" way is to:
cd
to the resulting directorypython setup.py install
Another solution is to use easy_install
. Go to http://peak.telecommunity.com/DevCenter/EasyInstall), install the package using the instructions on that page, and then type, in a Terminal window:
easy_install BeautifulSoup4
# for older v3:
# easy_install BeautifulSoup
easy_install
will take care of downloading, unpacking, building, and installing the package. The advantage to using easy_install
is that it knows how to search for many different Python packages, because it queries the PyPI registry. Thus, once you have easy_install
on your machine, you install many, many different third-party packages simply by one command at a shell.
There isn't currently a better way to do it than Ctrl+C in the terminal.
We're thinking about how to have an explicit shutdown, but there's some tension between the notebook as a single-user application, where the user is free to stop it, and as a multi-user server, where only an admin should be able to stop it. We haven't quite worked out how to handle the differences yet.
(For future readers, this is the situation with 0.12 released and 0.13 in development.)
Update December 2017
The IPython Notebook has become the Jupyter Notebook. A recent version has added a jupyter notebook stop
shell command which will shut down a server running on that system. You can pass the port number at the command line if it's not the default port 8888.
You can also use nbmanager, a desktop application which can show running servers and shut them down.
Finally, we are working on adding:
If anyone of you are using a product from Intellij, the solution for this it's the following:
Other File Types
.Use tab character
and be careful, Tab size
and Indent
values must be 4.var str = "This is my string"
print(str.replacingOccurrences(of: " ", with: "+"))
Output is
This+is+my+string
Try GIT_CURL_VERBOSE=1 git push
...Your problem may occur due to proxy settings, for instance if git is trying to reach github.com via a proxy server and the proxy is not responding.
With GIT_CURL_VERBOSE=1 it will show the target IP address and some information. You can compare this IP address with the output of the command: host www.github.com
. If these IPs are different then you can set https_proxy=""
and try again.
This stratify
parameter makes a split so that the proportion of values in the sample produced will be the same as the proportion of values provided to parameter stratify
.
For example, if variable y
is a binary categorical variable with values 0
and 1
and there are 25% of zeros and 75% of ones, stratify=y
will make sure that your random split has 25% of 0
's and 75% of 1
's.
PS> I posted this answer on a related question. Here's how I got round the issue of my async ajax request losing the trusted context:
I opened the popup directly on the users click, directed the url to about:blank
and got a handle on that window. You could probably direct the popup to a 'loading' url while your ajax request is made
var myWindow = window.open("about:blank",'name','height=500,width=550');
Then, when my request is successful, I open my callback url in the window
function showWindow(win, url) {
win.open(url,'name','height=500,width=550');
}
I believe you may simply do:
ImageConverter converter = new ImageConverter();
var bytes = (byte[])converter.ConvertTo(img, typeof(byte[]));
Not /gi but /g
var fname = "My Family File.jpg"
fname = fname.replace(/ /g,"_");
console.log(fname);
gives
"My_Family_File.jpg"
It happens sometimes for the files downloaded with "wget" command. Just 10 minutes ago, I was trying to install something to server from the command screen and the same thing happened. As a solution, I just downloaded the .tar.gz file to my machine from the web then uploaded it to the server via FTP. After that, the "tar" command worked as it was expected.
You could do it a couple of ways:
1. Use the forceUpdate()
method:
There are some glitches that may happen when using the forceUpdate()
method. One example is that it ignores the shouldComponentUpdate()
method and will re-render the view regardless of whether shouldComponentUpdate()
returns false. Because of this using forceUpdate() should be avoided when at all possible.
2. Passing this.state to the setState()
method
The following line of code overcomes the problem with the previous example:
this.setState(this.state);
Really all this is doing is overwriting the current state with the current state which triggers a re-rendering. This still isn't necessarily the best way to do things, but it does overcome some of the glitches you might encounter using the forceUpdate() method.
It is very easy to connect remote MySQL Server Using PHP, what you have to do is:
Create a MySQL User in remote server.
Give Full privilege to the User.
Connect to the Server using PHP Code (Sample Given Below)
$link = mysql_connect('your_my_sql_servername or IP Address', 'new_user_which_u_created', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db('sandsbtob',$link) or die ("could not open db".mysql_error());
// we connect to localhost at port 3306
Add to the info plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
import Alamofire
class AlamofireDataManager {
fileprivate let queue: DispatchQueue
init(queue: DispatchQueue) { self.queue = queue }
private func createError(message: String, code: Int) -> Error {
return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
}
private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((Result<[String: Any]>) -> Void)?) {
Alamofire.request(request).responseJSON { response in
let complete: (Result<[String: Any]>) ->() = { result in DispatchQueue.main.async { closure?(result) } }
switch response.result {
case .success(let value): complete(.success(value as! [String: Any]))
case .failure(let error): complete(.failure(error))
}
}
}
func searchRequest(term: String, closure: ((Result<[String: Any]>) -> Void)?) {
guard let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))") else { return }
let request = URLRequest(url: url)
make(request: request) { response in closure?(response) }
}
}
private lazy var alamofireDataManager = AlamofireDataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
//.........
alamofireDataManager.searchRequest(term: "jack johnson") { result in
print(result.value ?? "no data")
print(result.error ?? "no error")
}
import Foundation
class DataManager {
fileprivate let queue: DispatchQueue
init(queue: DispatchQueue) { self.queue = queue }
private func createError(message: String, code: Int) -> Error {
return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
}
private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
let task = session.dataTask(with: request) { [weak self] data, response, error in
self?.queue.async {
let complete: (_ json: [String: Any]?, _ error: Error?) ->() = { json, error in DispatchQueue.main.async { closure?(json, error) } }
guard let self = self, error == nil else { complete(nil, error); return }
guard let data = data else { complete(nil, self.createError(message: "No data", code: 999)); return }
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
complete(json, nil)
}
} catch let error { complete(nil, error); return }
}
}
task.resume()
}
func searchRequest(term: String, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))")
let request = URLRequest(url: url!)
make(request: request) { json, error in closure?(json, error) }
}
}
private lazy var dataManager = DataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
// .......
dataManager.searchRequest(term: "jack johnson") { json, error in
print(error ?? "nil")
print(json ?? "nil")
print("Update views")
}
Here's a short one-liner using regular expressions:
print [re.compile(r"8").sub("", m) for m in mylist]
If we separate the regex operations and improve the namings:
pattern = re.compile(r"8") # Create the regular expression to match
res = [pattern.sub("", match) for match in mylist] # Remove match on each element
print res
I had to add this line to settings.py in order to make it work (otherwise it showed an error when accessed from another computer)
ALLOWED_HOSTS = ['*']
then ran the server with:
python manage.py runserver 0.0.0.0:9595
Also ensure that the firewall allows connections to that port
You can double click directly on the .cs file representing your form in the Solution Explorer :
This will open Form1.cs [Design]
, which contains the drag&drop controls.
If you are directly in the code behind (The file named Form1.cs
, without "[Design]"), you can press Shift + F7 (or only F7 depending on the project type) instead to open it.
From the design view, you can switch back to the Code Behind by pressing F7.
xml was not in the WEB-INF folder, thats why i was getting this error, make sure that web.xml and xxx-servlet.xml is inside WEB_INF folder and not in the webapp folder .
Using io.Copy
package main
import (
"io"
"log"
"os"
)
func main () {
// open files r and w
r, err := os.Open("input.txt")
if err != nil {
panic(err)
}
defer r.Close()
w, err := os.Create("output.txt")
if err != nil {
panic(err)
}
defer w.Close()
// do the actual work
n, err := io.Copy(w, r)
if err != nil {
panic(err)
}
log.Printf("Copied %v bytes\n", n)
}
If you don't feel like reinventing the wheel, the io.Copy
and io.CopyN
may serve you well. If you check the source of the io.Copy function, it is nothing but one of the Mostafa's solutions (the 'basic' one, actually) packaged in the Go library. They are using a significantly larger buffer than he is, though.
Here's an easier way:
sudo apt-get install maven
More details are here.
Firstly,the crash reason is decorView's index is -1,we can knew it from Android source code ,there is code snippet:
class:android.view.WindowManagerGlobal
file:WindowManagerGlobal.java
private int findViewLocked(View view, boolean required) {
final int index = mViews.indexOf(view);
//here, view is decorView,comment by OF
if (required && index < 0) {
throw new IllegalArgumentException("View=" + view + " not attached to window manager");
}
return index;
}
so we get follow resolution,just judge decorView's index,if it more than 0 then continue or just return and give up dismiss,code as follow:
try {
Class<?> windowMgrGloable = Class.forName("android.view.WindowManagerGlobal");
try {
Method mtdGetIntance = windowMgrGloable.getDeclaredMethod("getInstance");
mtdGetIntance.setAccessible(true);
try {
Object windownGlobal = mtdGetIntance.invoke(null,null);
try {
Field mViewField = windowMgrGloable.getDeclaredField("mViews");
mViewField.setAccessible(true);
ArrayList<View> mViews = (ArrayList<View>) mViewField.get(windownGlobal);
int decorViewIndex = mViews.indexOf(pd.getWindow().getDecorView());
Log.i(TAG,"check index:"+decorViewIndex);
if (decorViewIndex < 0) {
return;
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (pd.isShowing()) {
pd.dismiss();
}
I was able to solve "ORA-00604: error" by Droping with purge.
DROP TABLE tablename PURGE
Do make sure that you haven't written your unit tests in a .NET Standard 2.0 Class Library. The visualstudio runner does not support running tests in netstandard2.0 class libraries at the time of this writing.
Check here for the Test Runner Compatibility matrix:
$focusable:
'a[href]',
'area[href]',
'button',
'details',
'input',
'iframe',
'select',
'textarea',
// these are actually case sensitive but i'm not listing out all the possible variants
'[contentEditable=""]',
'[contentEditable="true"]',
'[contentEditable="TRUE"]',
'[tabindex]:not([tabindex^="-"])',
':not([disabled])';
I'm creating a SCSS list of all focusable elements and I thought this might help someone due to this question's Google rank.
A few things to note:
:not([tabindex="-1"])
to :not([tabindex^="-"])
because it's perfectly plausible to generate -2
somehow. Better safe than sorry right?:not([tabindex^="-"])
to all the other focusable selectors is completely pointless. When using [tabindex]:not([tabindex^="-"])
it already includes all elements that you'd be negating with :not
!:not([disabled])
because disabled elements can never be focusable. So again it's useless to add it to every single element.Looping over arrays and objects is a pretty common task, and it's good that you're wanting to learn how to do it. Generally speaking you can do a foreach
loop which cycles over each member, assigning it a new temporary name, and then lets you handle that particular member via that name:
foreach ($arr as $item) {
echo $item->sm_id;
}
In this example each of our values in the $arr
will be accessed in order as $item
. So we can print our values directly off of that. We could also include the index if we wanted:
foreach ($arr as $index => $item) {
echo "Item at index {$index} has sm_id value {$item->sm_id}";
}
What about angular-scroll, it's actively maintained and there is no dependency to jQuery..
You would read from System.in
just like you would for keyboard input using, for example, InputStreamReader or Scanner.
If you were like me, running maven compile deploy from eclipse's maven run configuration, the issue could be related to eclipse's own embedded maven as described in https://bugs.eclipse.org/bugs/show_bug.cgi?id=562847
The workaround is to run mvn compile deploy from CLI such as bash, or to NOT use embedded maven in the eclipse's maven run configuration, and add an external maven (mine is in /usr/share/mvn), and voila, it'll say BUILD SUCCESS.
Even if your data falls within your specified limits (e.g. c(0, 335)
), adding a geom_jitter()
statement could push some points outside those limits, producing the same error message.
library(ggplot2)
range(mtcars$hp)
#> [1] 52 335
# No jitter -- no error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
scale_y_continuous(limits=c(0,335))
# Jitter is too large -- this generates the error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
geom_jitter(position = position_jitter(w = 0.2, h = 0.2)) +
scale_y_continuous(limits=c(0,335))
#> Warning: Removed 1 rows containing missing values (geom_point).
Created on 2020-08-24 by the reprex package (v0.3.0)
Here's another practical example from my CUDA Convolutional neural network library. I have the following class template:
template <class T> class Tensor
which is actually implements n-dimensional matrices manipulation. There's also a child class template:
template <class T> class TensorGPU : public Tensor<T>
which implements the same functionality but in GPU. Both templates can work with all basic types, like float, double, int, etc And I also have a class template (simplified):
template <template <class> class TT, class T> class CLayerT: public Layer<TT<T> >
{
TT<T> weights;
TT<T> inputs;
TT<int> connection_matrix;
}
The reason here to have template template syntax is because I can declare implementation of the class
class CLayerCuda: public CLayerT<TensorGPU, float>
which will have both weights and inputs of type float and on GPU, but connection_matrix will always be int, either on CPU (by specifying TT = Tensor) or on GPU (by specifying TT=TensorGPU).
Function strlen
shows the number of character before \0
and using it for std::string
may report wrong length.
strlen(str.c_str()); // It may return wrong length.
In C++, a string can contain \0
within the characters but C-style-zero-terminated strings can not but at the end. If the std::string
has a \0
before the last character then strlen
reports a length less than the actual length.
Try to use .length()
or .size()
, I prefer second one since another standard containers have it.
str.size()
In swift...
This is inclusive, calling random(1,2)
will return a 1 or a 2, This will also work with negative numbers.
func random(min: Int, _ max: Int) -> Int {
guard min < max else {return min}
return Int(arc4random_uniform(UInt32(1 + max - min))) + min
}
@miyuru. As suggested by him run all the steps.
Ubuntu version 16.04
Still when I ran docker --version
it was returning a version. So to uninstall it completely
Again run the dpkg -l | grep -i docker
which will list package still there in system.
For example:
ii docker-ce-cli 5:19.03.6~3-0~ubuntu-xenial
amd64 Docker CLI: the open-source application container engine
Now remove them as show below :
sudo apt-get purge -y docker-ce-cli
sudo apt-get autoremove -y --purge docker-ce-cli
sudo apt-get autoclean
Hope this will resolve it, as it did in my case.
Just a generic note. a way to keep it flexible.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
We can use getMinutes(), but it return only one number for the first 9 minutes.
let epoch = new Date() // Or any unix timestamp_x000D_
_x000D_
let za = new Date(epoch),_x000D_
zaR = za.getUTCFullYear(),_x000D_
zaMth = za.getUTCMonth(),_x000D_
zaDs = za.getUTCDate(),_x000D_
zaTm = za.toTimeString().substr(0,5);_x000D_
_x000D_
console.log(zaR +"-" + zaMth + "-" + zaDs, zaTm)
_x000D_
Date.prototype.getDate()
Returns the day of the month (1-31) for the specified date according to local time.
Date.prototype.getDay()
Returns the day of the week (0-6) for the specified date according to local time.
Date.prototype.getFullYear()
Returns the year (4 digits for 4-digit years) of the specified date according to local time.
Date.prototype.getHours()
Returns the hour (0-23) in the specified date according to local time.
Date.prototype.getMilliseconds()
Returns the milliseconds (0-999) in the specified date according to local time.
Date.prototype.getMinutes()
Returns the minutes (0-59) in the specified date according to local time.
Date.prototype.getMonth()
Returns the month (0-11) in the specified date according to local time.
Date.prototype.getSeconds()
Returns the seconds (0-59) in the specified date according to local time.
Date.prototype.getTime()
Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for prior times).
Date.prototype.getTimezoneOffset()
Returns the time-zone offset in minutes for the current locale.
Date.prototype.getUTCDate()
Returns the day (date) of the month (1-31) in the specified date according to universal time.
Date.prototype.getUTCDay()
Returns the day of the week (0-6) in the specified date according to universal time.
Date.prototype.getUTCFullYear()
Returns the year (4 digits for 4-digit years) in the specified date according to universal time.
Date.prototype.getUTCHours()
Returns the hours (0-23) in the specified date according to universal time.
Date.prototype.getUTCMilliseconds()
Returns the milliseconds (0-999) in the specified date according to universal time.
Date.prototype.getUTCMinutes()
Returns the minutes (0-59) in the specified date according to universal time.
Date.prototype.getUTCMonth()
Returns the month (0-11) in the specified date according to universal time.
Date.prototype.getUTCSeconds()
Returns the seconds (0-59) in the specified date according to universal time.
Date.prototype.getYear()
Returns the year (usually 2-3 digits) in the specified date according to local time. Use getFullYear() instead.
Well by studying the code above a bit (specifically using TextTestRunner
and defaultTestLoader
), I was able to get pretty close. Eventually I fixed my code by also just passing all test suites to a single suites constructor, rather than adding them "manually", which fixed my other problems. So here is my solution.
import glob
import unittest
test_files = glob.glob('test_*.py')
module_strings = [test_file[0:len(test_file)-3] for test_file in test_files]
suites = [unittest.defaultTestLoader.loadTestsFromName(test_file) for test_file in module_strings]
test_suite = unittest.TestSuite(suites)
test_runner = unittest.TextTestRunner().run(test_suite)
Yeah, it is probably easier to just use nose than to do this, but that is besides the point.
You need to delete your old db folder and recreate new one. It will resolve your issue.
In Visual Studio 2008 SP1 and later the XML Schema Explorer can create an XML document with some basic sample data:
Using Spring's UriComponentsBuilder:
UriComponentsBuilder
.fromUriString(url)
.build()
.encode()
.toUri()
You can use ternary operator for conditional statements in dart, It's use is simple
(condition) ? statement1 : statement2
if the condition
is true then the statement1
will be executed otherwise statement2
.
Taking a practical example
Center(child: condition ? Widget1() : Widget2())
Remember if you are going to use null
as Widget2
it is better to use SizedBox.shrink()
because some parent widgets will throw an exception after getting a null
child.
Using template literals...
var json = `{"1440167924916":{"id":1440167924916,"type":"text","content":"It's a test!"}}`;
You can't. You need to create another php script to return the image data, e.g. getImage.php. Change catalog.php to:
<body>
<img src="getImage.php?id=1" width="175" height="200" />
</body>
Then getImage.php is
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "");
mysql_select_db("dvddb");
$sql = "SELECT dvdimage FROM dvd WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['dvdimage'];
?>
I suggest using the Google Charts API because you can specify the text, text color, fill color and outline color, all using hex color codes, e.g. #FF0000 for red. You can call it as follows:
function getIcon(text, fillColor, textColor, outlineColor) {
if (!text) text = '•'; //generic map dot
var iconUrl = "http://chart.googleapis.com/chart?cht=d&chdp=mapsapi&chl=pin%27i\\%27[" + text + "%27-2%27f\\hv%27a\\]h\\]o\\" + fillColor + "%27fC\\" + textColor + "%27tC\\" + outlineColor + "%27eC\\Lauto%27f\\&ext=.png";
return iconUrl;
}
Then, when you create your marker you just set the icon property as such, where the myColor variables are hex values (minus the hash sign):
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
animation: google.maps.Animation.DROP,
map: map,
icon: getIcon(null, myColor, myColor2, myColor3)
});
You can use http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=•|FF0000
, which is a bit easier to decipher, as an alternate URL if you only need to set text and fill color.
khurram's answer refers to a 3rd party site that redirects to the Google Charts API. This means if that person takes down their server you're hosed. I prefer having the flexibility the Google API offers as well as the reliability of going directly to Google. Just make sure you specify a value for each of the colors or it won't work.
With ES6 you can now do it like this
Example Codepen URl to load
const iframe = '<iframe height="265" style="width: 100%;" scrolling="no" title="fx." src="//codepen.io/ycw/embed/JqwbQw/?height=265&theme-id=0&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true">See the Pen <a href="https://codepen.io/ycw/pen/JqwbQw/">fx.</a> by ycw(<a href="https://codepen.io/ycw">@ycw</a>) on <a href="https://codepen.io">CodePen</a>.</iframe>';
A function component to load Iframe
function Iframe(props) {
return (<div dangerouslySetInnerHTML={ {__html: props.iframe?props.iframe:""}} />);
}
Usage:
import React from "react";
import ReactDOM from "react-dom";
function App() {
return (
<div className="App">
<h1>Iframe Demo</h1>
<Iframe iframe={iframe} />,
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Edit on CodeSandbox:
If you don't mind a crass writing style, Redis vs Memcached on the Systoilet blog is worth a read from a usability standpoint, but be sure to read the back & forth in the comments before drawing any conclusions on performance; there are some methodological problems (single-threaded busy-loop tests), and Redis has made some improvements since the article was written as well.
And no benchmark link is complete without confusing things a bit, so also check out some conflicting benchmarks at Dormondo's LiveJournal and the Antirez Weblog.
Edit -- as Antirez points out, the Systoilet analysis is rather ill-conceived. Even beyond the single-threading shortfall, much of the performance disparity in those benchmarks can be attributed to the client libraries rather than server throughput. The benchmarks at the Antirez Weblog do indeed present a much more apples-to-apples (with the same mouth) comparison.
I usually use
if(!(jQuery.inArray("test", myarray) < 0))
or
if(jQuery.inArray("test", myarray) >= 0)
In my case I have different application.properties depending on the environment, something like:
application.properties (base file)
application-dev.properties
application-qa.properties
application-prod.properties
and application.properties contains a property spring.profiles.active to pick the proper file.
For my integration tests, I created a new application-test.properties
file inside test/resources
and with the @TestPropertySource({ "/application-test.properties" })
annotation this is the file who is in charge of picking the application.properties I want depending on my needs for those tests
For me I had to set the environment variable for a php application. I resloved it by adding the following code to my crontab.
$ sudo crontab -e
crontab:
ENVIRONMENT_VAR=production
* * * * * /home/deploy/my_app/cron/cron.doSomethingWonderful.php
and inside doSomethingWonderful.php I could get the environment value with:
<?php
echo $_SERVER['ENVIRONMENT_VAR']; # => "production"
I hope this helps!
You could use:
echo date('F Y', strtotime('20130814'));
which should do the trick.
Edit: You have a date which is in a string format. To be able to format it nicelt, you first need to change it into a date itself - which is where strtotime comes in. It is a fantastic feature that converts almost any plausible expression of a date into a date itself. Then we can actually use the date() function to format the output into what you want.
You need to have a look at Same Origin Policy:
In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.
For you to be able to get data, it has to be:
Same protocol and host
You need to implement JSONP to workaround it.
Based on this example I made following function:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(host, port, user, pwd, recipients, subject, body, html=None, from_=None):
""" copied and adapted from
https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python#12424439
returns None if all ok, but if problem then returns exception object
"""
PORT_LIST = (25, 587, 465)
FROM = from_ if from_ else user
TO = recipients if isinstance(recipients, (list, tuple)) else [recipients]
SUBJECT = subject
TEXT = body.encode("utf8") if isinstance(body, unicode) else body
HTML = html.encode("utf8") if isinstance(html, unicode) else html
if not html:
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
else:
# https://stackoverflow.com/questions/882712/sending-html-email-using-python#882770
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = ", ".join(TO)
# Record the MIME types of both parts - text/plain and text/html.
# utf-8 -> https://stackoverflow.com/questions/5910104/python-how-to-send-utf-8-e-mail#5910530
part1 = MIMEText(TEXT, 'plain', "utf-8")
part2 = MIMEText(HTML, 'html', "utf-8")
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
message = msg.as_string()
try:
if port not in PORT_LIST:
raise Exception("Port %s not one of %s" % (port, PORT_LIST))
if port in (465,):
server = smtplib.SMTP_SSL(host, port)
else:
server = smtplib.SMTP(host, port)
# optional
server.ehlo()
if port in (587,):
server.starttls()
server.login(user, pwd)
server.sendmail(FROM, TO, message)
server.close()
# logger.info("SENT_EMAIL to %s: %s" % (recipients, subject))
except Exception, ex:
return ex
return None
if you pass only body
then plain text mail will be sent, but if you pass html
argument along with body
argument, html email will be sent (with fallback to text content for email clients that don't support html/mime types).
Example usage:
ex = send_email(
host = 'smtp.gmail.com'
#, port = 465 # OK
, port = 587 #OK
, user = "[email protected]"
, pwd = "xxx"
, from_ = '[email protected]'
, recipients = ['[email protected]']
, subject = "Test from python"
, body = "Test from python - body"
)
if ex:
print("Mail sending failed: %s" % ex)
else:
print("OK - mail sent"
Btw. If you want to use gmail as testing or production SMTP server, enable temp or permanent access to less secured apps:
Extract the common code into a class library project and add that class library project to your solutions. Then you can add a reference to the common code from other projects by adding a project reference to that class library. The advantage of having a project reference as opposed to a binary/assembly reference is that if you change your build configuration to debug, release, custom, etc, the common class library project will be built based on that configuration as well.
You can use
Trace.WriteLine()
to write to the Output window when debugging a unit test.
Specify the buildpack while creating the app.
heroku create appname --buildpack heroku/python
i had this problem when running the magento indexer in osx. and yes its related to php problem when connecting to mysql through pdo
in mac osx xampp, to fix this you have create symbolic link to directory /var/mysql, here is how
cd /var/mysql && sudo ln -s /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
if the directory /var/mysql doesnt exist, we must create it with
sudo mkdir /var/mysql
Last year, I took Prof: Andrew Ng’s online machine learning course. His recommendation was:
Training: 60%
Cross validation: 20%
Testing: 20%
Here's a good one:
Set line-height
equal to whatever the height
is; works like a charm!
E.g:
li {
height: 30px;
line-height: 30px;
}
I use this as a daily scheduled task to hide users disabled in AD from the Global Address List
$mailboxes = get-user | where {$_.UserAccountControl -like '*AccountDisabled*' -and $_.RecipientType -eq 'UserMailbox' } | get-mailbox | where {$_.HiddenFromAddressListsEnabled -eq $false}
foreach ($mailbox in $mailboxes) { Set-Mailbox -HiddenFromAddressListsEnabled $true -Identity $mailbox }
Another silly mistake you can do is copy recursive function from non class environment to class and don`t change inner self calls to $this->method_name()
i`m writing this because couldn`t understand why i got this error and this thread is first in google when you search for this error.
For recent versions of Android Studio, if changing just the Kotlin Target VM version didn't work.
File ? Project Structure ? Modules (app
): set both "Source Compatibility" and "Target Compatibility" to "1.8 (Java 8)". Press "OK" and sync project with Gradle.
RUN: Can be many, and it is used in build process, e.g. install multiple libraries
CMD: Can only have 1, which is your execute start point (e.g. ["npm", "start"]
, ["node", "app.js"]
)
If you are streaming an mp3 or video that may not necessarily be over HTTP, in fact I'd be suprised if it was. It would probably be another protocol over TCP but I see no reason why you cannot stream over UDP.
If you do you have to take into account that there is no certainty that your data will arrive at the other end, but I can take it that you know about UDP.
To answer you question, No, HTTP does NOT use UDP. For what you talk about though, mp3/video streaming COULD happen over UDP and in my opinion should never happen over HTTP.
jQuery
$(function() {
$("td[colspan=3]").find("div").hide();
$("tr").click(function(event) {
var $target = $(event.target);
$target.closest("tr").next().find("div").slideToggle();
});
});
HTML
<table>
<thead>
<tr>
<th>one</th><th>two</th><th>three</th>
</tr>
</thead>
<tbody>
<tr>
<td><p>data<p></td><td>data</td><td>data</td>
</tr>
<tr>
<td colspan="3">
<div>
<table>
<tr>
<td>data</td><td>data</td>
</tr>
</table>
</div>
</td>
</tr>
</tbody>
</table>
This is much like a previous example above. I found when trying to implement that example that if the table row to be expanded was clicked while it was not expanded it would disappear, and it would no longer be expandable
To fix that I simply removed the ability to click the expandable element for slide up and made it so that you can only toggle using the above table row.
I also made some minor changes to HTML and corresponding jQuery.
NOTE: I would have just made a comment but am not allowed to yet therefore the long post. Just wanted to post this as it took me a bit to figure out what was happening to the disappearing table row.
Credit to Peter Ajtai
To avoid explicitly checking for these variants of 'yes' you could use the bash regular expression operator '=~' with a regular expression:
read -p "Are you sure you want to continue? <y/N> " prompt
if [[ $prompt =~ [yY](es)* ]]
then
(etc...)
That tests whether the user input starts with 'y' or 'Y' and is followed by zero or more 'es's.
Of course, "Fagner Antunes Dornelles" is correct in its answer. But it seems to me that it is worth checking the registry branch itself in addition, or be sure of the part that is exactly there.
For example ("dirty hack"), i need to establish trust in the RMS infrastructure, otherwise when i open Word or Excel documents, i will be prompted for "Active Directory Rights Management Services". Here's how i can add remote trust to me servers in the enterprise infrastructure.
foreach (var strServer in listServer)
{
try
{
RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC\\{strServer}", false);
if (regCurrentUser == null)
throw new ApplicationException("Not found registry SubKey ...");
if (regCurrentUser.GetValueNames().Contains("UserConsent") == false)
throw new ApplicationException("Not found value in SubKey ...");
}
catch (ApplicationException appEx)
{
Console.WriteLine(appEx);
try
{
RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC", true);
RegistryKey newKey = regCurrentUser.CreateSubKey(strServer, true);
newKey.SetValue("UserConsent", 1, RegistryValueKind.DWord);
}
catch(Exception ex)
{
Console.WriteLine($"{ex} Pipec kakoito ...");
}
}
}
There is a little known feature, which makes this even better. You can use a configurable default value instead of a hard-coded one, here is an example:
config.properties:
timeout.default=30
timeout.myBean=60
context.xml:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>config.properties</value>
</property>
</bean>
<bean id="myBean" class="Test">
<property name="timeout" value="${timeout.myBean:${timeout.default}}" />
</bean>
To use the default while still being able to easily override later, do this in config.properties:
timeout.myBean = ${timeout.default}
with bash:
shopt -s globstar nullglob
rename _dbg.txt .txt **/*dbg*
Also, you can create your own outerHeight
for HTML elements. I don't know if it works in IE, but it works in Chrome. Perhaps, you can enhance the code below using currentStyle
, suggested in the answer above.
Object.defineProperty(Element.prototype, 'outerHeight', {
'get': function(){
var height = this.clientHeight;
var computedStyle = window.getComputedStyle(this);
height += parseInt(computedStyle.marginTop, 10);
height += parseInt(computedStyle.marginBottom, 10);
height += parseInt(computedStyle.borderTopWidth, 10);
height += parseInt(computedStyle.borderBottomWidth, 10);
return height;
}
});
This piece of code allow you to do something like this:
document.getElementById('foo').outerHeight
According to caniuse.com, getComputedStyle is supported by main browsers (IE, Chrome, Firefox).
When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:
return StatusCode(500, "My error");
Or
return StatusCode((int)HttpStatusCode.InternalServerError, "My error");
Or
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { responseText = "my error" });
Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error:
in client side (ajax).
you can have ajax call like:
$.ajax({
type: "POST",
url: "/General/ContactRequestPartial",
data: {
HashId: id
},
success: function (response) {
console.log("Custom message : " + response.responseText);
}, //Is Called when Status Code is 200[OK] or other Http success code
error: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
}, //Is Called when Status Code is 500[InternalServerError] or other Http Error code
})
Additionally you can handle different HTTP errors from jQuery side like:
$.ajax({
type: "POST",
url: "/General/ContactRequestPartial",
data: {
HashId: id
},
statusCode: {
500: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
501: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
}
})
statusCode:
is useful when you want to call different functions for different status codes that you return from server.
You can see list of different Http Status codes here:Wikipedia
Additional resources:
Given the Django use case, there are two answers to this. Here is its django.utils.html.escape
function, for reference:
def escape(html):
"""Returns the given HTML with ampersands, quotes and carets encoded."""
return mark_safe(force_unicode(html).replace('&', '&').replace('<', '&l
t;').replace('>', '>').replace('"', '"').replace("'", '''))
To reverse this, the Cheetah function described in Jake's answer should work, but is missing the single-quote. This version includes an updated tuple, with the order of replacement reversed to avoid symmetric problems:
def html_decode(s):
"""
Returns the ASCII decoded version of the given HTML string. This does
NOT remove normal HTML tags like <p>.
"""
htmlCodes = (
("'", '''),
('"', '"'),
('>', '>'),
('<', '<'),
('&', '&')
)
for code in htmlCodes:
s = s.replace(code[1], code[0])
return s
unescaped = html_decode(my_string)
This, however, is not a general solution; it is only appropriate for strings encoded with django.utils.html.escape
. More generally, it is a good idea to stick with the standard library:
# Python 2.x:
import HTMLParser
html_parser = HTMLParser.HTMLParser()
unescaped = html_parser.unescape(my_string)
# Python 3.x:
import html.parser
html_parser = html.parser.HTMLParser()
unescaped = html_parser.unescape(my_string)
# >= Python 3.5:
from html import unescape
unescaped = unescape(my_string)
As a suggestion: it may make more sense to store the HTML unescaped in your database. It'd be worth looking into getting unescaped results back from BeautifulSoup if possible, and avoiding this process altogether.
With Django, escaping only occurs during template rendering; so to prevent escaping you just tell the templating engine not to escape your string. To do that, use one of these options in your template:
{{ context_var|safe }}
{% autoescape off %}
{{ context_var }}
{% endautoescape %}
In PHP, a variable or array element which has never been set is different from one whose value is null
; attempting to access such an unset value is a runtime error.
That's what you're running into: the array $_POST
does not have any element at the key "username"
, so the interpreter aborts your program before it ever gets to the nullity test.
Fortunately, you can test for the existence of a variable or array element without actually trying to access it; that's what the special operator isset
does:
if (isset($_POST["username"]))
{
$user = $_POST["username"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
This looks like it will blow up in exactly the same way as your code, when PHP tries to get the value of $_POST["username"]
to pass as an argument to the function isset()
. However, isset()
is not really a function at all, but special syntax recognized before the evaluation stage, so the PHP interpreter checks for the existence of the value without actually trying to retrieve it.
It's also worth mentioning that as runtime errors go, a missing array element is considered a minor one (assigned the E_NOTICE
level). If you change the error_reporting
level so that notices are ignored, your original code will actually work as written, with the attempted array access returning null
. But that's considered bad practice, especially for production code.
Side note: PHP does string interpolation, so the echo
statements in the if
block can be combined into one:
echo "$user is your username";
This error appears because the spring project doesn't read the file properties (bootstrap.yml or application.yml). In order to resolve this, you must add dependency in your pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
</dependency>
There seems to be a new solution at the horizon. It's called EmailJS. They claim that no server code is needed. You can request an invitation.
Update August 2016: EmailJS seems to be live already. You can send up to 200 emails per month for free and it offers subscriptions for higher volumes.
The table normally contains multiple rows. Use a loop and use row.Field<string>(0)
to access the value of each row.
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>("File");
}
You can also access it via index:
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>(0);
}
If you expect only one row, you can also use the indexer of DataRowCollection
:
string file = dt.Rows[0].Field<string>(0);
Since this fails if the table is empty, use dt.Rows.Count
to check if there is a row:
if(dt.Rows.Count > 0)
file = dt.Rows[0].Field<string>(0);
You can get the index of the tab by name with the following script:
var index = $('#tabs ul').index($('#simple-tab-2'));
$('#tabs ul').tabs('select', index);
grep '^[0-9]\{1,16\}' | wc -l
Gives the counts with exact match count with limit
I using Xcode 6+ and I just do:
*.xcodeproj or *.xcworkspace
Here is done, but name of window Xcode and *.xcodeproj or *.xcworkspace
still <old-name>
. Then I do:
pop install
<new name>.xcworkspace
This script will run after the entire page has loaded.
<script type="text/javascript">
$(window).load(function() {
//This execute when entire finished loaded
window.print();
});
</script>
To add something to this (cause I found it while searching on this problem, and my solution involved slightly more)...
If you don't have a "Browse with..." option for .aspx files (as I didn't in a MVC application), the easiest solution is to add a dummy HTML file, and right-click it to set the option as described in the answer. You can remove the file afterward.
The option is actually set in: C:\Documents and Settings[user]\Local Settings\Application Data\Microsoft\VisualStudio[version]\browser.xml
However, if you modify the file directly while VS is running, VS will overwrite it with your previous option on next run. Also, if you edit the default in VS you won't have to worry about getting the schema right, so the work-around dummy file is probably the easiest way.
THIS IS JUST A NOTE FOR ANYONE DEALING WITH THIS PROBLEM USING THE RUBY DRIVER
I had this same problem when using the Ruby Gem.
To set slaveOk in Ruby, you just pass it as an argument when you create the client like this:
mongo_client = MongoClient.new("localhost", 27017, { slave_ok: true })
https://github.com/mongodb/mongo-ruby-driver/wiki/Tutorial#making-a-connection
mongo_client = MongoClient.new # (optional host/port args)
Notice that 'args' is the third optional argument.
You need to upgrade your pip before installing psycopg2. Use this command
pip install --upgrade pip
I recommend using Inquirer, since it provides a collection of common interactive command line user interfaces.
const inquirer = require('inquirer');
const questions = [{
type: 'input',
name: 'name',
message: "What's your name?",
}];
const answers = await inquirer.prompt(questions);
console.log(answers);
import datetime
import pytz
# datetime object with timezone awareness:
datetime.datetime.now(tz=pytz.utc)
# seconds from epoch:
datetime.datetime.now(tz=pytz.utc).timestamp()
# ms from epoch:
int(datetime.datetime.now(tz=pytz.utc).timestamp() * 1000)
A much easier and resource friendly approach would be.
import UIKit
@IBDesignable
class CircleDrawView: UIView {
@IBInspectable var borderColor: UIColor = UIColor.red;
@IBInspectable var borderSize: CGFloat = 4
override func draw(_ rect: CGRect)
{
layer.borderColor = borderColor.cgColor
layer.borderWidth = borderSize
layer.cornerRadius = self.frame.height/2
}
}
With Border Color
and Border Size
and the default Background
property you can define the appearance of the circle.
Please note, to draw a circle the view's height and width have to be equal in size.
The code is working for Swift >= 4
and Xcode >= 9
.
According to the error message ("Could not find or load main class"), there are two categories of problems:
Main class could not be found when there is typo or wrong syntax in the fully qualified class name or it does not exist in the provided classpath.
Main class could not be loaded when the class cannot be initiated, typically the main class extends another class and that class does not exist in the provided classpath.
For example:
public class YourMain extends org.apache.camel.spring.Main
If camel-spring is not included, this error will be reported.
There is another way to pass multiple ranges to a function, which I think feels much cleaner for the user. When you call your function in the spreadsheet you wrap each set of ranges in brackets, for example: calculateIt( (A1,A3), (B6,B9) )
The above call assumes your two Sessions are in A1 and A3, and your two Customers are in B6 and B9.
To make this work, your function needs to loop through each of the Areas
in the input ranges. For example:
Function calculateIt(Sessions As Range, Customers As Range) As Single
' check we passed the same number of areas
If (Sessions.Areas.Count <> Customers.Areas.Count) Then
calculateIt = CVErr(xlErrNA)
Exit Function
End If
Dim mySession, myCustomers As Range
' run through each area and calculate
For a = 1 To Sessions.Areas.Count
Set mySession = Sessions.Areas(a)
Set myCustomers = Customers.Areas(a)
' calculate them...
Next a
End Function
The nice thing is, if you have both your inputs as a contiguous range, you can call this function just as you would a normal one, e.g. calculateIt(A1:A3, B6:B9)
.
Hope that helps :)
Must be used convert, not cast:
SELECT
CONVERT(varchar(50), N'æøåáälcçcédnoöruýtžš')
COLLATE Cyrillic_General_CI_AI
Press Ctrl+H (Replace)
Select Extended
from SearchMode
Put \r\n\r\n
in Find What
Put \r\n
in ReplaceWith
Click on Replace All
The percent sign is escaped using a percent sign:
System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);
The complete syntax can be accessed in java docs. This particular information is in the section Conversions
of the first link.
The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. %
is not a valid character.
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
The 2nd parameter of http.post is the body of the message, ie the payload and not the url search parameters. Pass data
in that parameter.
From the documentation
post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response>
public post(cmd: string, data: object): Observable<any> {
const params = new URLSearchParams();
params.set('cmd', cmd);
const options = new RequestOptions({
headers: this.getAuthorizedHeaders(),
responseType: ResponseContentType.Json,
params: params,
withCredentials: false
});
console.log('Options: ' + JSON.stringify(options));
return this.http.post(this.BASE_URL, data, options)
.map(this.handleData)
.catch(this.handleError);
}
You should also check out the 1st parameter (BASE_URL
). It must contain the complete url (minus query string) that you want to reach. I mention in due to the name you gave it and I can only guess what the value currently is (maybe just the domain?).
Also there is no need to call JSON.stringify
on the data/payload that is sent in the http body.
If you still can't reach your end point look in the browser's network activity in the development console to see what is being sent. You can then further determine if the correct end point is being called wit the correct header and body. If it appears that is correct then use POSTMAN or Fiddler or something similar to see if you can hit your endpoint that way (outside of Angular).
I've used the solution described here http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!130.entry successfully in PowerShell v1.0. It definitely will be easier in PowerShell v2.0.
The error you are receiving is due to how you define jet
. You are creating the base class Colormap
with the name 'jet', but this is very different from getting the default definition of the 'jet' colormap. This base class should never be created directly, and only the subclasses should be instantiated.
What you've found with your example is a buggy behavior in Matplotlib. There should be a clearer error message generated when this code is run.
This is an updated version of your example:
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np
# define some random data that emulates your indeded code:
NCURVES = 10
np.random.seed(101)
curves = [np.random.random(20) for i in range(NCURVES)]
values = range(NCURVES)
fig = plt.figure()
ax = fig.add_subplot(111)
# replace the next line
#jet = colors.Colormap('jet')
# with
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
print scalarMap.get_clim()
lines = []
for idx in range(len(curves)):
line = curves[idx]
colorVal = scalarMap.to_rgba(values[idx])
colorText = (
'color: (%4.2f,%4.2f,%4.2f)'%(colorVal[0],colorVal[1],colorVal[2])
)
retLine, = ax.plot(line,
color=colorVal,
label=colorText)
lines.append(retLine)
#added this to get the legend to work
handles,labels = ax.get_legend_handles_labels()
ax.legend(handles, labels, loc='upper right')
ax.grid()
plt.show()
Resulting in:
Using a ScalarMappable
is an improvement over the approach presented in my related answer:
creating over 20 unique legend colors using matplotlib